Skip to content

The agent that grows with you

feat(release): sequence stable publication oldest first

ethernet1201949d3042
diff --git a/.github/workflows/stable-release-publication.yml b/.github/workflows/stable-release-publication.yml
new file mode 100644
index 00000000000..d33159290bd
--- /dev/null
+++ b/.github/workflows/stable-release-publication.yml
@@ -0,0 +1,54 @@
+name: Stable Release Publication
+
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: 'Green stable version to publish (for example 0.21.5)'
+ required: false
+ type: string
+ default: ''
+ workflow_run:
+ workflows: ['Stable Release']
+ types: [completed]
+ schedule:
+ - cron: '17 * * * *'
+
+concurrency:
+ group: stable-release
+ cancel-in-progress: false
+
+permissions:
+ contents: write
+ actions: read
+
+jobs:
+ reconcile:
+ if: >-
+ github.event_name != 'workflow_run' ||
+ (github.event.workflow_run.conclusion != 'success' &&
+ github.event.workflow_run.event == 'workflow_dispatch' &&
+ github.event.workflow_run.head_repository.full_name == github.repository)
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ environment: release-signing
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ github.event.repository.default_branch }}
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: ./.github/actions/setup-pm
+ with:
+ toolchain: node
+ cache-python: false
+ - name: Reconcile stable drafts and protected heads
+ run: python -m scripts.releases.sequencer
+ env:
+ GH_TOKEN: ${{ github.token }}
+ REQUESTED_VERSION: ${{ inputs.version || '' }}
+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml
index 79ebc7be1e8..92f051d1d01 100644
--- a/.github/workflows/stable-release.yml
+++ b/.github/workflows/stable-release.yml
@@ -258,26 +258,10 @@ jobs:
tag: ${{ needs.admit.outputs.tag }}
version: ${{ needs.admit.outputs.version }}
- promote-bundles:
- name: Advance stable bundle channels
- needs: [admit, publication, candidates]
- permissions:
- contents: write
- actions: read
- packages: write
- id-token: write
- uses: ./.github/workflows/desktop-bundled-release.yml
- with:
- tag: ${{ needs.admit.outputs.tag }}
- claim-tag: ${{ needs.admit.outputs.claim-tag }}
- claim-object: ${{ needs.admit.outputs.claim-object }}
- release-phase: promote
- manifest-sha256: ${{ needs.candidates.outputs.manifest-sha256 }}
-
complete:
name: Stable release is green
if: always()
- needs: [admit, ci, docker, acceptance, candidates, publication, promote-docker, promote-bundles, windows-packaged, macos-packaged]
+ needs: [admit, ci, docker, acceptance, candidates, publication, promote-docker, windows-packaged, macos-packaged]
runs-on: ubuntu-24.04
environment: release-signing
permissions:
@@ -296,7 +280,7 @@ jobs:
with:
toolchain: node
cache-python: false
- - run: python -m scripts.releases.stable gate admit ci docker acceptance candidates publication promote-docker promote-bundles
+ - run: python -m scripts.releases.stable gate admit ci docker acceptance candidates publication promote-docker
env:
RELEASE_NEEDS: ${{ toJSON(needs) }}
- name: Create the final tag and retarget the accepted release
@@ -325,3 +309,13 @@ jobs:
run: |
python scripts/render-builds-table.py --tag "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \
--candidate-manifest-sha256 "$CANDIDATE_MANIFEST_SHA256" --candidate-commit "$RELEASE_COMMIT"
+ - name: Reconcile ordered stable publication
+ run: python -m scripts.releases.sequencer
+ env:
+ GH_TOKEN: ${{ github.token }}
+ REQUESTED_VERSION: ''
+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
diff --git a/scripts/release.py b/scripts/release.py
index 35446e32386..7450e0d4f19 100755
--- a/scripts/release.py
+++ b/scripts/release.py
@@ -2913,6 +2913,14 @@ def main():
release_cmd.add_argument("--autopublish", action="store_true",
help="Publish on green instead of leaving a draft")
release_cmd.add_argument("--remote", type=str)
+ publish_cmd = subcommands.add_parser(
+ "publish", help="Publish a green stable release through the ordered sequencer")
+ publish_cmd.add_argument("--version", required=True)
+ publish_cmd.add_argument("--remote", type=str)
+ abandon_cmd = subcommands.add_parser(
+ "abandon", help="Delete a stable draft while retaining its spent claim")
+ abandon_cmd.add_argument("--version", required=True)
+ abandon_cmd.add_argument("--remote", type=str)
from scripts.releases.channel_build import add_arguments, validate_arguments, cmd_channel
add_arguments(parser)
@@ -2922,6 +2930,14 @@ def main():
from scripts.releases.entrypoint import cmd_release
cmd_release(args)
return
+ if args.command == "publish":
+ from scripts.releases.entrypoint import cmd_publish
+ cmd_publish(args)
+ return
+ if args.command == "abandon":
+ from scripts.releases.entrypoint import cmd_abandon
+ cmd_abandon(args)
+ return
if validate_arguments(parser, args):
cmd_channel(args)
return
diff --git a/scripts/releases/channel_releases.py b/scripts/releases/channel_releases.py
index 4c47498aedf..abf0cb8bd6d 100644
--- a/scripts/releases/channel_releases.py
+++ b/scripts/releases/channel_releases.py
@@ -17,7 +17,6 @@ from scripts.releases import handoff, r2, stable
from scripts.releases.channels import ChannelPublisher, R2ChannelStore
NATIVE_LEGS = ("darwin-arm64", "darwin-x64", "win32-arm64", "win32-x64", "windows-universal")
-STABLE_NEEDS = ("admit", "ci", "docker", "acceptance", "candidates", "publication", "promote-docker", "promote-bundles", "windows-packaged", "macos-packaged")
CANARY_NEEDS = ("validate", "build-win32", "build-darwin", "build-linux", "builds-table", "assemble-win32-bundle",
"smoke-darwin", "smoke-win32", "smoke-win32-universal", "publish-win32-updater", "publish-darwin-updater")
@@ -105,13 +104,27 @@ def admit_transaction(policy: str, env: dict, *, run=stable.output) -> tuple[str
raise ChannelError("Invalid protected release tag")
if (policy == "canary-release") != is_canary_tag(tag):
raise ChannelError("Protected release policy/tag mismatch")
- if env.get("GITHUB_ACTIONS") != "true" or env.get("GITHUB_EVENT_NAME") != "workflow_dispatch":
+ if env.get("GITHUB_ACTIONS") != "true":
raise ChannelError("Protected heads require the accepted release workflow")
default = ""
if policy == "stable-release":
- expected = f"{repository}/.github/workflows/stable-release.yml@refs/tags/{tag}"
- required = STABLE_NEEDS
+ default = run(["gh", "api", f"repos/{repository}", "--jq", ".default_branch"])
+ claim_tag = env.get("RELEASE_CLAIM_TAG", "")
+ expected = {
+ f"{repository}/.github/workflows/stable-release.yml@refs/tags/{claim_tag}",
+ f"{repository}/.github/workflows/stable-release-publication.yml@refs/heads/{default}",
+ }
+ if (env.get("GITHUB_EVENT_NAME") not in {"workflow_dispatch", "workflow_run", "schedule"}
+ or env.get("GITHUB_WORKFLOW_REF") not in expected):
+ raise ChannelError("Protected publication requires its stable release controller")
+ try:
+ verified_tag, verified_commit, _claim = stable.final_context(env, run=run)
+ except (ValueError, subprocess.CalledProcessError) as error:
+ raise ChannelError(str(error)) from error
+ return verified_tag, verified_commit
elif policy == "canary-release":
+ if env.get("GITHUB_EVENT_NAME") != "workflow_dispatch":
+ raise ChannelError("Protected heads require the accepted release workflow")
default = run(["gh", "api", f"repos/{repository}", "--jq", ".default_branch"])
expected = f"{repository}/.github/workflows/desktop-bundled-release.yml@refs/heads/{default}"
required = CANARY_NEEDS
@@ -120,20 +133,17 @@ def admit_transaction(policy: str, env: dict, *, run=stable.output) -> tuple[str
if env.get("GITHUB_WORKFLOW_REF") != expected:
raise ChannelError("Protected publication requires its existing release workflow")
stable.require_success(json.loads(env.get("RELEASE_NEEDS", "{}")), list(required))
- if policy == "stable-release":
- tag, commit = stable.check_tag(env, run=run)
- else:
- commit = require_commit(env.get("RELEASE_COMMIT"))
- actual = run(["git", "rev-parse", f"refs/tags/{tag}^{{commit}}"])
- remote = dict(line.split()[::-1] for line in run(
- ["git", "ls-remote", "origin", f"refs/tags/{tag}", f"refs/tags/{tag}^{{}}"] ).splitlines())
- if actual != commit or remote.get(f"refs/tags/{tag}^{{}}", remote.get(f"refs/tags/{tag}")) != commit:
- raise ChannelError("Canary release tag moved")
- run(["git", "merge-base", "--is-ancestor", commit, f"origin/{default}"])
+ commit = require_commit(env.get("RELEASE_COMMIT"))
+ actual = run(["git", "rev-parse", f"refs/tags/{tag}^{{commit}}"])
+ remote = dict(line.split()[::-1] for line in run(
+ ["git", "ls-remote", "origin", f"refs/tags/{tag}", f"refs/tags/{tag}^{{}}"] ).splitlines())
+ if actual != commit or remote.get(f"refs/tags/{tag}^{{}}", remote.get(f"refs/tags/{tag}")) != commit:
+ raise ChannelError("Canary release tag moved")
+ run(["git", "merge-base", "--is-ancestor", commit, f"origin/{default}"])
release = json.loads(run(["gh", "release", "view", tag, "--repo", repository,
"--json", "tagName,isDraft,isPrerelease"]))
if (release.get("tagName") != tag or release.get("isDraft") is not False
- or release.get("isPrerelease") is not (policy == "canary-release")):
+ or release.get("isPrerelease") is not True):
raise ChannelError("Protected head requires the published GitHub release transaction")
return tag, commit
@@ -147,14 +157,51 @@ def accepted_stable(publisher: ChannelPublisher, env: dict, tag: str, commit: st
raise ChannelError("Accepted candidate URL differs from release archive")
candidate = decode_json(publisher.reader.read_bytes(key, digest))
stable.validate_candidates(candidate, tag, commit, publisher.public_base)
- accepted = publisher.store.get("releases/stable/release-candidates.json")
- if accepted is None or decode_json(accepted[0]) != candidate:
- raise ChannelError("Stable accepted manifest transaction has not completed")
- if decode_json(publisher.reader.read_bytes("releases/stable/release-candidates.json")) != candidate:
- raise ChannelError("Stable accepted manifest is not publicly visible")
return candidate
+def stable_head_version(env: dict) -> str | None:
+ """Return the protected stable head's source version, if one exists."""
+ publisher = ChannelPublisher(R2ChannelStore(*r2.credentials()), env["GITHUB_REPOSITORY"],
+ r2.public_base_url(), authorize=lambda _action, _record: None)
+ current = publisher._read(select_channel(publisher, "stable-release"))
+ if current is None or current[0]["head"] is None:
+ return None
+ head = current[0]["head"]
+ found = publisher.store.get(head["manifestKey"])
+ if found is None or hashlib.sha256(found[0]).hexdigest() != head["sha256"]:
+ raise ChannelError("Stable protected head manifest is unavailable or changed")
+ manifest = json.loads(found[0])
+ return manifest["request"]["version"]
+
+
+def advance_stable(env: dict, release: dict, root: Path) -> dict:
+ """Advance one published release from its immutable tag-scoped receipts."""
+ creds, base, bucket = r2.credentials()
+ store = R2ChannelStore(creds, base, bucket)
+ public_base = r2.public_base_url()
+ key = f"releases/tag/{release['tag']}/release-candidates.json"
+ found = store.get(key)
+ if found is None:
+ raise ChannelError("Stable candidate manifest is unavailable")
+ scoped_env = {
+ **env,
+ "RELEASE_TAG": release["tag"],
+ "RELEASE_COMMIT": release["commit"],
+ "RELEASE_CLAIM_TAG": release["claim_tag"],
+ "RELEASE_CLAIM_OBJECT": release["claim_object"],
+ "CANDIDATE_MANIFEST_URL": f"{public_base}/{key}",
+ "CANDIDATE_MANIFEST_SHA256": hashlib.sha256(found[0]).hexdigest(),
+ }
+ return publish_release("stable-release", scoped_env, root)
+
+
+def promote_stable_feeds(candidate: dict, root: Path, public_base: str) -> None:
+ from scripts.bundles.release_artifacts import promote
+
+ promote(candidate, root, public_base)
+
+
def verify_bootstrap(request: dict, manifest: dict, base: str, repository: str) -> bool:
"""Bootstrap from published release outputs, never caller attestations."""
from hermes_cli.release_channels import ChannelReader, decode_json
@@ -269,7 +316,13 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:
return pinned == request and actual == expected
publisher.verify_build = qualified
- return publisher.promote_protected(request["buildId"], policy=policy, release_gate=release_gate)
+ result = publisher.promote_protected(request["buildId"], policy=policy, release_gate=release_gate)
+ if accepted is not None:
+ publisher._write("releases/stable/release-candidates.json", accepted)
+ if publisher.reader.read_bytes("releases/stable/release-candidates.json") != canonical_json(accepted):
+ raise ChannelError("Stable candidate pointer read-back differs")
+ promote_stable_feeds(accepted, root, publisher.public_base)
+ return result
def main(argv: list[str] | None = None) -> None:
diff --git a/scripts/releases/entrypoint.py b/scripts/releases/entrypoint.py
index 33f4cc30463..406acbe8864 100644
--- a/scripts/releases/entrypoint.py
+++ b/scripts/releases/entrypoint.py
@@ -6,6 +6,7 @@ because a burned version is never retried under the same number.
"""
from __future__ import annotations
+import json
import subprocess
from pathlib import Path
@@ -67,7 +68,13 @@ def release(commit: str, *, bump: str, repo: Path, remote: str, repository: str,
_require_ancestry(repo, commit)
version = derive_next_version(published=None, claims=_claims(repo), bump=bump)
tag = f"v{version}-rc"
- _git(repo, "tag", "-a", tag, commit, "-m", f"claim v{version}")
+ claim = json.dumps({
+ "schema": 1,
+ "version": version,
+ "commit": commit,
+ "autopublish": autopublish,
+ }, sort_keys=True, separators=(",", ":"))
+ _git(repo, "tag", "-a", tag, commit, "-m", claim)
_git(repo, "push", remote, f"refs/tags/{tag}")
url = f"https://github.com/{repository}/releases/tag/{tag}"
try:
@@ -86,13 +93,18 @@ def release(commit: str, *, bump: str, repo: Path, remote: str, repository: str,
"autopublish": autopublish}
-def publish(version: str, *, repo: Path, repository: str, green, edit) -> dict:
- """Flip a green waiting draft. The flip is the publish; nothing rebuilds."""
+def publish(version: str, *, repository: str, dispatch) -> dict:
+ """Request ordered publication through the one production sequencer."""
tag = f"v{version}"
- if not green(tag):
- raise ReleaseRefused(f"{version} is not green — refusing to publish")
- edit(["gh", "release", "edit", tag, "--repo", repository, "--draft=false"])
- return {"flipped": tag}
+ from hermes_cli.update_channel import STABLE_TAG_RE
+
+ if not STABLE_TAG_RE.fullmatch(tag):
+ raise ReleaseRefused(f"{version} is not a stable version")
+ dispatch([
+ "gh", "workflow", "run", "stable-release-publication.yml",
+ "--repo", repository, "--raw-field", f"version={version}",
+ ])
+ return {"requested": tag}
def abandon(version: str, *, repo: Path, repository: str, delete) -> dict:
@@ -120,3 +132,31 @@ def cmd_release(args) -> None:
result = release(commit, bump=args.bump, repo=repo, remote=remote, repository=repository,
execute=execute, autopublish=args.autopublish)
print(result["url"])
+
+
+def _command_repository(args) -> tuple[Path, str]:
+ from scripts import release as release_script
+
+ repo = release_script.REPO_ROOT
+ remote = release_script.resolve_push_remote(args.remote)
+ repository = release_script.remote_github_repo(remote)
+ if not repository:
+ raise SystemExit(f"release: remote {remote!r} does not point at a GitHub repository")
+ return repo, repository
+
+
+def _execute(repo: Path, command: list[str]) -> None:
+ completed = subprocess.run(command, cwd=repo, capture_output=True, text=True, encoding="utf-8")
+ if completed.returncode != 0:
+ raise ReleaseRefused(completed.stderr.strip() or "release command failed")
+
+
+def cmd_publish(args) -> None:
+ repo, repository = _command_repository(args)
+ publish(args.version, repository=repository, dispatch=lambda command: _execute(repo, command))
+
+
+def cmd_abandon(args) -> None:
+ repo, repository = _command_repository(args)
+ abandon(args.version, repo=repo, repository=repository,
+ delete=lambda command: _execute(repo, command))
diff --git a/scripts/releases/sequencer.py b/scripts/releases/sequencer.py
new file mode 100644
index 00000000000..fe88a971c6f
--- /dev/null
+++ b/scripts/releases/sequencer.py
@@ -0,0 +1,270 @@
+"""Discover and reconcile stable releases in version order.
+
+The planner is pure. Production discovery reads only remote annotated tags,
+GitHub releases/runs, and the protected R2 head; execution flips exact release
+IDs before advancing each eligible head oldest-first.
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+from hermes_cli.update_channel import STABLE_TAG_RE
+
+CLAIM_TAG_RE = re.compile(r"^(v(?:0|[1-9]\d{0,2})\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))-rc$")
+
+
+def _key(version: str) -> tuple[int, int, int]:
+ major, minor, patch = version.split(".")
+ return int(major), int(minor), int(patch)
+
+
+def plan(claims: list[dict], *, head: str | None,
+ requested_version: str | None = None) -> list[dict]:
+ """Return eligible draft flips followed by each ordered head advance."""
+ ordered = sorted(claims, key=lambda claim: _key(claim["version"]))
+ head_key = _key(head) if head is not None else None
+ flips: list[dict] = []
+ advances: list[dict] = []
+
+ for index, claim in enumerate(ordered):
+ version = claim["version"]
+ version_key = _key(version)
+ state = claim["state"]
+
+ if head_key is not None and version_key <= head_key:
+ if state in {"published", "burned"}:
+ continue
+ raise ValueError(f"refusing to move the head backwards from {head}")
+
+ if state == "published":
+ advances.append({"advance": version})
+ continue
+ if state == "burned":
+ continue
+ if state == "running":
+ break
+ if state != "green":
+ raise ValueError(f"unknown claim state {state!r}")
+
+ has_later_live_claim = any(
+ later["state"] != "burned" for later in ordered[index + 1:]
+ )
+ eligible = (
+ claim.get("autopublish", False)
+ or version == requested_version
+ or has_later_live_claim
+ )
+ if not eligible:
+ break
+ flips.append({"flip": version})
+ advances.append({"advance": version})
+
+ return flips + advances
+
+
+def output(argv: list[str]) -> str:
+ return subprocess.check_output(argv, text=True, encoding="utf-8").strip()
+
+
+def _pages(argv: list[str], run=output) -> list:
+ pages = json.loads(run(["gh", "api", "--paginate", "--slurp", *argv]))
+ if not isinstance(pages, list):
+ raise ValueError("GitHub pagination returned an invalid response")
+ return pages
+
+
+def _release_rows(repository: str, run=output) -> list[dict]:
+ rows = []
+ for page in _pages([f"repos/{repository}/releases?per_page=100"], run):
+ if not isinstance(page, list):
+ raise ValueError("GitHub releases response is invalid")
+ rows.extend(page)
+ return rows
+
+
+def _workflow_runs(repository: str, run=output) -> list[dict]:
+ rows = []
+ endpoint = f"repos/{repository}/actions/workflows/stable-release.yml/runs?event=workflow_dispatch&per_page=100"
+ for page in _pages([endpoint], run):
+ if not isinstance(page, dict) or not isinstance(page.get("workflow_runs"), list):
+ raise ValueError("GitHub workflow runs response is invalid")
+ rows.extend(page["workflow_runs"])
+ return rows
+
+
+def _remote_tags(run=output) -> dict[str, dict[str, str]]:
+ refs: dict[str, dict[str, str]] = {}
+ for line in run(["git", "ls-remote", "--tags", "origin", "refs/tags/v*"]).splitlines():
+ sha, ref = line.split()
+ peeled = ref.endswith("^{}")
+ tag = ref.removeprefix("refs/tags/").removesuffix("^{}")
+ if STABLE_TAG_RE.fullmatch(tag) or CLAIM_TAG_RE.fullmatch(tag):
+ refs.setdefault(tag, {})["commit" if peeled else "object"] = sha
+ return refs
+
+
+def _tag_message(tag: str, expected_object: str, run=output) -> dict:
+ local_object = run(["git", "rev-parse", f"refs/tags/{tag}"])
+ if local_object != expected_object or run(["git", "cat-file", "-t", local_object]) != "tag":
+ raise ValueError(f"{tag} differs from its remote annotated object")
+ try:
+ message = json.loads(run(["git", "tag", "-l", tag, "--format=%(contents)"]))
+ except json.JSONDecodeError as error:
+ raise ValueError(f"{tag} metadata is invalid") from error
+ if not isinstance(message, dict):
+ raise ValueError(f"{tag} metadata is invalid")
+ return message
+
+
+def discover(repository: str, run=output) -> list[dict]:
+ """Derive every stable claim state from remote refs and GitHub objects."""
+ run(["git", "fetch", "origin", "+refs/tags/v*:refs/tags/v*"])
+ refs = _remote_tags(run)
+ releases = _release_rows(repository, run)
+ workflow_runs = _workflow_runs(repository, run)
+ records = []
+
+ for claim_tag, claim_ref in refs.items():
+ match = CLAIM_TAG_RE.fullmatch(claim_tag)
+ if match is None:
+ continue
+ if set(claim_ref) != {"object", "commit"}:
+ raise ValueError(f"{claim_tag} must be an annotated remote tag")
+ tag = match.group(1)
+ version = tag[1:]
+ commit = claim_ref["commit"]
+ claim = _tag_message(claim_tag, claim_ref["object"], run)
+ expected_claim = {
+ "schema": 1, "version": version, "commit": commit,
+ "autopublish": claim.get("autopublish"),
+ }
+ if claim != expected_claim or not isinstance(claim["autopublish"], bool):
+ raise ValueError(f"{claim_tag} metadata differs from its ref")
+
+ family_releases = [row for row in releases if row.get("tag_name") in {claim_tag, tag}]
+ if len(family_releases) > 1:
+ raise ValueError(f"{claim_tag} owns multiple GitHub releases")
+ release = family_releases[0] if family_releases else None
+ final_ref = refs.get(tag)
+ needs_retarget = False
+
+ if final_ref is not None:
+ if set(final_ref) != {"object", "commit"}:
+ raise ValueError(f"{tag} must be an annotated remote tag")
+ if final_ref["commit"] != commit:
+ raise ValueError(f"{tag} points at a different commit than {claim_tag}")
+ final = _tag_message(tag, final_ref["object"], run)
+ expected_final = {
+ "schema": 1, "version": version, "commit": commit,
+ "claimTag": claim_tag, "claimTagObject": claim_ref["object"],
+ "autopublish": claim["autopublish"],
+ }
+ if final != expected_final:
+ raise ValueError(f"{tag} metadata differs from {claim_tag}")
+ if release is None or release.get("prerelease") is not False:
+ raise ValueError(f"{tag} has no valid GitHub release")
+ needs_retarget = release.get("tag_name") == claim_tag
+ if release.get("tag_name") not in {claim_tag, tag}:
+ raise ValueError(f"{tag} release identity changed")
+ if release.get("draft") is True:
+ state = "green"
+ elif release.get("draft") is False and release.get("published_at"):
+ if needs_retarget:
+ raise ValueError(f"{claim_tag} was published before final retargeting")
+ state = "published"
+ else:
+ raise ValueError(f"{tag} release state is invalid")
+ else:
+ if release is not None and (release.get("tag_name") != claim_tag
+ or release.get("draft") is not True
+ or release.get("prerelease") is not False):
+ raise ValueError(f"{claim_tag} draft state is invalid")
+ matching_runs = [row for row in workflow_runs
+ if row.get("head_branch") == claim_tag and row.get("head_sha") == commit]
+ if any(row.get("status") != "completed" for row in matching_runs):
+ state = "running"
+ elif any(row.get("conclusion") == "success" for row in matching_runs):
+ raise ValueError(f"{claim_tag} succeeded without a final tag")
+ else:
+ state = "burned"
+
+ records.append({
+ "version": version,
+ "state": state,
+ "autopublish": claim["autopublish"],
+ "claim_tag": claim_tag,
+ "claim_object": claim_ref["object"],
+ "tag": tag,
+ "commit": commit,
+ "release_id": release.get("id") if release else None,
+ "needs_retarget": needs_retarget,
+ })
+
+ return sorted(records, key=lambda record: _key(record["version"]))
+
+
+def reconcile(env: dict, *, run=output, read_head=None, advance_head=None) -> list[dict]:
+ """Converge GitHub publication and protected heads oldest-first."""
+ from scripts.releases import channel_releases, stable
+
+ repository = env["GITHUB_REPOSITORY"]
+ records = discover(repository, run)
+ for record in records:
+ if record["needs_retarget"]:
+ stable.retarget_release(repository, record["release_id"], record["tag"],
+ record["commit"], publish=False, run=run)
+ if any(record["needs_retarget"] for record in records):
+ records = discover(repository, run)
+
+ read_head = read_head or (lambda: channel_releases.stable_head_version(env))
+ head = read_head()
+ requested = env.get("REQUESTED_VERSION") or None
+ steps = plan(records, head=head, requested_version=requested)
+ by_version = {record["version"]: record for record in records}
+
+ for step in steps:
+ if "flip" not in step:
+ continue
+ record = by_version[step["flip"]]
+ stable.retarget_release(repository, record["release_id"], record["tag"],
+ record["commit"], publish=True, run=run)
+
+ if advance_head is None:
+ def production_advance(record: dict) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ channel_releases.advance_stable(env, record, Path(directory))
+ advance_head = production_advance
+
+ for step in steps:
+ if "advance" in step:
+ advance_head(by_version[step["advance"]])
+
+ final = {record["version"]: record for record in discover(repository, run)}
+ for step in steps:
+ if "flip" in step and final[step["flip"]]["state"] != "published":
+ raise ValueError(f"Stable release {step['flip']} did not publish")
+ if requested and (requested not in final or final[requested]["state"] != "published"):
+ raise ValueError(f"Requested stable release {requested} did not publish")
+ if any("advance" in step for step in steps):
+ expected = next(step["advance"] for step in reversed(steps) if "advance" in step)
+ if read_head() != expected:
+ raise ValueError("Stable protected head did not reach the planned version")
+ return steps
+
+
+def main(argv: list[str] | None = None, env: dict | None = None) -> None:
+ if argv is None:
+ argv = sys.argv[1:]
+ if argv:
+ raise ValueError("The stable sequencer takes no positional arguments")
+ print(json.dumps(reconcile(dict(os.environ if env is None else env)), sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/releases/stable.py b/scripts/releases/stable.py
index 2a12d8fa45b..900041f6a56 100644
--- a/scripts/releases/stable.py
+++ b/scripts/releases/stable.py
@@ -98,8 +98,6 @@ def validate_candidates(manifest: dict, tag: str, commit: str, public_base: str,
raise ValueError(f"Invalid candidate digest or identity: {target}")
if item["platform"] == "windows":
windows_version(item.get("version", ""))
- if item["version"] != f"{tag[1:]}.0":
- raise ValueError("Stable Windows package version must match its release tag")
if not item.get("publisher") or not item.get("applicationId") or not url.path.endswith(".msixbundle"):
raise ValueError("Windows candidate needs publisher, applicationId and MSIX bundle")
elif item["platform"] == "macos":
@@ -170,6 +168,20 @@ def output(argv: list[str]) -> str:
return subprocess.check_output(argv, text=True, encoding="utf-8").strip()
+def _claim_metadata(raw: str, *, version: str, commit: str) -> dict:
+ try:
+ metadata = json.loads(raw)
+ except (TypeError, json.JSONDecodeError) as error:
+ raise ValueError("Stable claim metadata is invalid") from error
+ expected = {"schema": 1, "version": version, "commit": commit}
+ if (not isinstance(metadata, dict)
+ or any(metadata.get(key) != value for key, value in expected.items())
+ or not isinstance(metadata.get("autopublish"), bool)
+ or set(metadata) != {*expected, "autopublish"}):
+ raise ValueError("Stable claim metadata is invalid")
+ return metadata
+
+
def check_claim(env: dict, run=output) -> dict:
"""Bind the run to one remote annotated claim object and its commit."""
claim_tag, commit = env.get("RELEASE_CLAIM_TAG"), env.get("GITHUB_SHA")
@@ -192,7 +204,7 @@ def check_claim(env: dict, run=output) -> dict:
or (expected_object and remote_object != expected_object)
or run(["git", "rev-parse", "HEAD"]) != commit):
raise ValueError("Stable claim tag or checkout moved")
- run(["git", "fetch", "origin", "main"])
+ run(["git", "fetch", "origin", "+refs/heads/main:refs/remotes/origin/main"])
def on_main(sha: str) -> bool:
try:
@@ -202,7 +214,10 @@ def check_claim(env: dict, run=output) -> dict:
return True
admitted = admit_claim(claim_tag, commit, on_main=on_main)
- return {**admitted, "claim_object": local_object}
+ raw_metadata = run(["git", "tag", "-l", claim_tag, "--format=%(contents)"])
+ metadata = _claim_metadata(raw_metadata, version=admitted["version"], commit=commit)
+ return {**admitted, "claim_object": local_object,
+ "autopublish": metadata["autopublish"]}
def stable_context(env: dict, run=output) -> tuple[str, str, dict]:
@@ -213,6 +228,61 @@ def stable_context(env: dict, run=output) -> tuple[str, str, dict]:
return tag, claim["commit"], claim
+def final_context(env: dict, run=output) -> tuple[str, str, dict]:
+ """Verify the final annotated receipt, its claim, and published release."""
+ repository = env.get("GITHUB_REPOSITORY", "")
+ tag = env.get("RELEASE_TAG", "")
+ commit = env.get("RELEASE_COMMIT", "")
+ claim_tag = env.get("RELEASE_CLAIM_TAG", "")
+ claim_object = env.get("RELEASE_CLAIM_OBJECT", "")
+ require_stable_identity(tag, commit)
+ admitted = admit_claim(claim_tag, commit, on_main=lambda _commit: True)
+ if admitted["tag"] != tag or not SHA.fullmatch(claim_object):
+ raise ValueError("Final release differs from its claim")
+
+ refs = {}
+ for line in run(["git", "ls-remote", "origin",
+ f"refs/tags/{claim_tag}", f"refs/tags/{claim_tag}^{{}}",
+ f"refs/tags/{tag}", f"refs/tags/{tag}^{{}}"]).splitlines():
+ sha, ref = line.split()
+ refs[ref] = sha
+ if (refs.get(f"refs/tags/{claim_tag}") != claim_object
+ or refs.get(f"refs/tags/{claim_tag}^{{}}") != commit
+ or refs.get(f"refs/tags/{tag}^{{}}") != commit
+ or not refs.get(f"refs/tags/{tag}")):
+ raise ValueError("Final release tag custody changed")
+
+ run(["git", "fetch", "origin", "+refs/heads/main:refs/remotes/origin/main",
+ f"+refs/tags/{claim_tag}:refs/tags/{claim_tag}",
+ f"+refs/tags/{tag}:refs/tags/{tag}"])
+ for receipt, expected_object in ((claim_tag, claim_object),
+ (tag, refs[f"refs/tags/{tag}"])):
+ local_object = run(["git", "rev-parse", f"refs/tags/{receipt}"])
+ if local_object != expected_object or run(["git", "cat-file", "-t", local_object]) != "tag":
+ raise ValueError("Final release local tag differs from the remote")
+ run(["git", "merge-base", "--is-ancestor", commit, "origin/main"])
+ claim = _claim_metadata(
+ run(["git", "tag", "-l", claim_tag, "--format=%(contents)"]),
+ version=admitted["version"], commit=commit,
+ )
+ final = json.loads(run(["git", "tag", "-l", tag, "--format=%(contents)"]))
+ expected = {
+ "schema": 1, "version": admitted["version"], "commit": commit,
+ "claimTag": claim_tag, "claimTagObject": claim_object,
+ "autopublish": claim["autopublish"],
+ }
+ if final != expected:
+ raise ValueError("Final tag metadata differs from its claim")
+ release = json.loads(run([
+ "gh", "api", f"repos/{repository}/releases/tags/{tag}",
+ ]))
+ if (release.get("tag_name") != tag or release.get("draft") is not False
+ or release.get("prerelease") is not False or not release.get("published_at")):
+ raise ValueError("Stable channel requires the published final release")
+ return tag, commit, {**admitted, "claim_object": claim_object,
+ "autopublish": claim["autopublish"]}
+
+
def emit(values: dict, env: dict) -> None:
with Path(env["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as file:
for key, value in values.items():
@@ -314,6 +384,7 @@ def ensure_final_tag(tag: str, commit: str, claim: dict, run=output) -> str:
message = json.dumps({
"schema": 1, "version": tag[1:], "commit": commit,
"claimTag": claim["claim_tag"], "claimTagObject": claim["claim_object"],
+ "autopublish": claim["autopublish"],
}, sort_keys=True, separators=(",", ":"))
run([
"git", "-c", "user.name=Hermes Release Automation",
@@ -349,10 +420,15 @@ def _autopublish(value: str | None) -> bool:
def retarget_release(repository: str, release_id: int, tag: str, commit: str, *, publish: bool,
run=output) -> None:
endpoint = f"repos/{repository}/releases/{release_id}"
+ current = json.loads(run(["gh", "api", endpoint]))
+ if (current.get("id") == release_id and current.get("tag_name") == tag
+ and current.get("prerelease") is False and current.get("draft") is False):
+ return
run([
"gh", "api", "--method", "PATCH", endpoint,
"--raw-field", f"tag_name={tag}", "--raw-field", f"target_commitish={commit}",
- "--field", "prerelease=false", "--field", f"draft={str(not publish).lower()}",
+ "--field", "prerelease=false", "--raw-field", "make_latest=true",
+ "--field", f"draft={str(not publish).lower()}",
])
release = json.loads(run(["gh", "api", endpoint]))
if (release.get("id") != release_id or release.get("tag_name") != tag
@@ -369,8 +445,9 @@ def complete(env: dict) -> None:
release_id = env.get("RELEASE_ID", "")
if not str(release_id).isdigit():
raise ValueError("Stable release database ID is required")
- publish = _autopublish(env.get("AUTOPUBLISH"))
- retarget_release(env["GITHUB_REPOSITORY"], int(release_id), tag, commit, publish=publish)
+ if _autopublish(env.get("AUTOPUBLISH")) is not claim["autopublish"]:
+ raise ValueError("Workflow autopublish input differs from the immutable claim")
+ retarget_release(env["GITHUB_REPOSITORY"], int(release_id), tag, commit, publish=False)
def main(argv: list[str] | None = None, env: dict | None = None) -> None:
diff --git a/tests/ci/test_desktop_release_tag_admission.py b/tests/ci/test_desktop_release_tag_admission.py
index 74701d64e8e..82124e2b4d1 100644
--- a/tests/ci/test_desktop_release_tag_admission.py
+++ b/tests/ci/test_desktop_release_tag_admission.py
@@ -13,6 +13,7 @@ unreviewed commit must never reach the signing build. Two layers are tested:
from __future__ import annotations
+import json
import os
import shutil
import subprocess
@@ -179,9 +180,18 @@ def _run_admission(clone: Path, tag: str, claim_tag: str) -> subprocess.Complete
)
+def _claim_message(clone: Path) -> str:
+ return json.dumps({
+ "schema": 1,
+ "version": "0.1.2",
+ "commit": _git("rev-parse", "HEAD", cwd=clone),
+ "autopublish": False,
+ }, sort_keys=True, separators=(",", ":"))
+
+
def test_claim_on_origin_main_is_admitted_and_exports_the_full_sha(tmp_path: Path):
_origin, clone = _seed_repo(tmp_path)
- _git("tag", "-a", "v0.1.2-rc", "-m", "claim", cwd=clone)
+ _git("tag", "-a", "v0.1.2-rc", "-m", _claim_message(clone), cwd=clone)
_git("push", "origin", "refs/tags/v0.1.2-rc", cwd=clone)
proc = _run_admission(clone, "v0.1.2", "v0.1.2-rc")
@@ -198,7 +208,7 @@ def test_claim_not_on_origin_main_is_refused(tmp_path: Path):
(clone / "rogue.txt").write_text("unreviewed\n", encoding="utf-8")
_git("add", "-A", cwd=clone)
_git("commit", "-m", "rogue", cwd=clone)
- _git("tag", "-a", "v0.1.2-rc", "-m", "claim", cwd=clone)
+ _git("tag", "-a", "v0.1.2-rc", "-m", _claim_message(clone), cwd=clone)
_git("push", "origin", "refs/tags/v0.1.2-rc", cwd=clone)
proc = _run_admission(clone, "v0.1.2", "v0.1.2-rc")
diff --git a/tests/ci/test_stable_release_graph.py b/tests/ci/test_stable_release_graph.py
index 83d6e2797f6..0dee7aef290 100644
--- a/tests/ci/test_stable_release_graph.py
+++ b/tests/ci/test_stable_release_graph.py
@@ -34,9 +34,9 @@ def test_release_reuses_whole_ci_and_docker_before_publication():
assert required <= ancestors(jobs, "acceptance")
for name in ("publish-docker", "publish-bundles"):
assert required <= ancestors(jobs, name)
- for name in ("promote-docker", "promote-bundles"):
- assert {"publish-docker", "publish-bundles", "publication"} <= ancestors(jobs, name)
- assert {"promote-docker", "promote-bundles"} <= ancestors(jobs, "complete")
+ assert {"publish-docker", "publish-bundles", "publication"} <= ancestors(jobs, "promote-docker")
+ assert "promote-docker" in ancestors(jobs, "complete")
+ assert "promote-bundles" not in jobs
for name in ("acceptance", "publication", "complete"):
assert jobs[name]["if"] == "always()"
@@ -55,7 +55,7 @@ def test_claim_custody_and_final_payload_identity_reach_every_privileged_phase()
assert release["on"]["workflow_dispatch"]["inputs"]["autopublish"]["required"] == "true"
assert {"claim-tag", "claim-object", "tag", "commit", "version", "release-id"} <= \
set(jobs["admit"]["outputs"])
- for name in ("candidates", "publish-bundles", "promote-bundles"):
+ for name in ("candidates", "publish-bundles"):
call = jobs[name]["with"]
assert call["tag"] == "${{ needs.admit.outputs.tag }}"
assert call["claim-tag"] == "${{ needs.admit.outputs.claim-tag }}"
@@ -65,4 +65,25 @@ def test_claim_custody_and_final_payload_identity_reach_every_privileged_phase()
complete = jobs["complete"]["steps"]
final = next(i for i, step in enumerate(complete) if step.get("name", "").startswith("Create the final tag"))
render = next(i for i, step in enumerate(complete) if step.get("name", "").startswith("Render the admitted"))
- assert final < render
+ reconcile = next(i for i, step in enumerate(complete) if step.get("name", "").startswith("Reconcile ordered"))
+ assert final < render < reconcile
+
+
+def test_publication_reconciler_has_every_recovery_trigger_and_shared_lock():
+ stable = workflow("stable-release.yml")
+ publication = workflow("stable-release-publication.yml")
+
+ assert stable["concurrency"] == publication["concurrency"] == {
+ "group": "stable-release", "cancel-in-progress": "false",
+ }
+ assert {"workflow_dispatch", "workflow_run", "schedule"} <= set(publication["on"])
+ assert publication["on"]["workflow_run"] == {
+ "workflows": ["Stable Release"], "types": ["completed"],
+ }
+ reconcile = publication["jobs"]["reconcile"]
+ assert reconcile["environment"] == "release-signing"
+ assert publication["permissions"] == {"contents": "write", "actions": "read"}
+ assert "conclusion != 'success'" in reconcile["if"]
+ checkout = reconcile["steps"][0]
+ assert checkout["with"]["ref"] == "${{ github.event.repository.default_branch }}"
+ assert checkout["with"]["persist-credentials"] == "false"
diff --git a/tests/scripts/test_release_channels.py b/tests/scripts/test_release_channels.py
index f26c29956ad..6d2bf50041a 100644
--- a/tests/scripts/test_release_channels.py
+++ b/tests/scripts/test_release_channels.py
@@ -435,6 +435,7 @@ def test_accepted_release_receipts_feed_the_protected_head_without_rebuilding(tm
from scripts.releases import r2, commit_build
monkeypatch.setattr(channel_releases, "admit_transaction", lambda policy, env: (tag, commit))
monkeypatch.setattr(channel_releases, "accepted_stable", lambda *args: accepted)
+ monkeypatch.setattr(channel_releases, "promote_stable_feeds", lambda *args: None)
monkeypatch.setattr(channel_releases, "product_identity", lambda tag: dict(identity))
monkeypatch.setattr(commit_build, "version_at", lambda *args: "2.0.0")
monkeypatch.setattr(r2, "credentials", lambda: (pub.store.creds, url, "bucket"))
@@ -453,35 +454,36 @@ def test_accepted_release_receipts_feed_the_protected_head_without_rebuilding(tm
channel_releases.read_native_receipts(tmp_path, tag, commit)
-def test_protected_transaction_refuses_custom_workflow_failed_gate_and_unpublished_release():
+def test_protected_transaction_refuses_custom_workflow_and_unpublished_release(monkeypatch):
from scripts.releases import channel_releases
from hermes_cli.release_channels import ChannelError
tag, commit = "v2.0.0", "a" * 40
env = {"GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "workflow_dispatch",
- "GITHUB_REPOSITORY": "example/hermes-agent", "GITHUB_SHA": commit,
- "GITHUB_REF": "refs/tags/" + tag, "RELEASE_TAG": tag,
- "GITHUB_WORKFLOW_REF": "example/hermes-agent/.github/workflows/stable-release.yml@refs/tags/" + tag,
- "RELEASE_NEEDS": json.dumps({key: {"result": "success"} for key in channel_releases.STABLE_NEEDS})}
- published = {"tagName": tag, "isDraft": False, "isPrerelease": False}
+ "GITHUB_REPOSITORY": "example/hermes-agent", "RELEASE_TAG": tag,
+ "RELEASE_COMMIT": commit, "RELEASE_CLAIM_TAG": tag + "-rc",
+ "RELEASE_CLAIM_OBJECT": "b" * 40,
+ "GITHUB_WORKFLOW_REF": "example/hermes-agent/.github/workflows/stable-release.yml@refs/tags/" + tag + "-rc"}
+ published = [True]
+
+ def final_context(_env, run):
+ if not published[0]:
+ raise ValueError("Stable channel requires the published final release")
+ return tag, commit, {}
+
+ monkeypatch.setattr(channel_releases.stable, "final_context", final_context)
def run(command):
- if command[:3] == ["gh", "release", "view"]:
- return json.dumps(published)
- if command[:2] == ["git", "ls-remote"]:
- return commit + "\trefs/tags/" + tag
- if command[:2] == ["git", "rev-parse"]:
- return commit
+ if command[-1] == ".default_branch":
+ return "main"
return ""
assert channel_releases.admit_transaction("stable-release", env, run=run) == (tag, commit)
- published["isDraft"] = True
+ published[0] = False
with pytest.raises(ChannelError, match="published"):
channel_releases.admit_transaction("stable-release", env, run=run)
- published["isDraft"] = False
- with pytest.raises(ChannelError, match="workflow"):
+ published[0] = True
+ with pytest.raises(ChannelError, match="controller"):
channel_releases.admit_transaction("stable-release", dict(env, GITHUB_WORKFLOW_REF="custom.yml"), run=run)
- with pytest.raises(ValueError, match="blocked"):
- channel_releases.admit_transaction("stable-release", dict(env, RELEASE_NEEDS="{}"), run=run)
from hermes_cli.release_channels import canonical_json
with object_server() as (url, objects, headers, requests, faults):
pub = publisher(url)
@@ -500,9 +502,6 @@ def test_protected_transaction_refuses_custom_workflow_failed_gate_and_unpublish
key = f"releases/tag/{tag}/release-candidates.json"
objects[key] = raw
candidate_env = {"CANDIDATE_MANIFEST_SHA256": hashlib.sha256(raw).hexdigest(), "CANDIDATE_MANIFEST_URL": pub.public_base + "/" + key}
- with pytest.raises(ChannelError, match="transaction"):
- channel_releases.accepted_stable(pub, candidate_env, tag, commit)
- objects["releases/stable/release-candidates.json"] = raw
assert channel_releases.accepted_stable(pub, candidate_env, tag, commit) == candidate
faults["stale_public"] = b"{}"
with pytest.raises(ChannelError):
diff --git a/tests/scripts/test_release_entrypoint.py b/tests/scripts/test_release_entrypoint.py
index 8389cfd4f24..fa437c218c2 100644
--- a/tests/scripts/test_release_entrypoint.py
+++ b/tests/scripts/test_release_entrypoint.py
@@ -3,6 +3,7 @@
The claim is the tag push, and it pushes exactly the claim ref. A release that
never starts is an error, not a warning the operator has to notice.
"""
+import json
import subprocess
import pytest
@@ -49,6 +50,12 @@ def test_release_claims_the_derived_version_creates_a_draft_and_dispatches(sourc
assert result["commit"] == commit
assert result["url"] == "https://github.com/example/hermes-agent/releases/tag/v0.21.5-rc"
assert git(source, "rev-parse", "v0.21.5-rc^{commit}") == commit
+ assert json.loads(git(source, "tag", "-l", "v0.21.5-rc", "--format=%(contents)")) == {
+ "autopublish": True,
+ "commit": commit,
+ "schema": 1,
+ "version": "0.21.5",
+ }
assert calls == [
["gh", "release", "create", "v0.21.5-rc", "--repo", "example/hermes-agent",
"--verify-tag", "--draft", "--generate-notes", "--title", "Hermes Agent v0.21.5"],
@@ -89,16 +96,18 @@ def test_a_dispatch_that_never_starts_is_an_error(source):
assert "v0.21.5-rc" in git(source, "tag", "--list")
-def test_publish_flips_a_green_draft_and_abandon_keeps_the_claim(source):
+def test_publish_dispatches_the_sequencer_and_abandon_keeps_the_claim(source):
from scripts.releases.entrypoint import abandon, publish
commit = git(source, "rev-parse", "HEAD")
_claim(source, "0.21.5", commit)
calls = []
- published = publish("0.21.5", repo=source, repository="example/hermes-agent",
- green=lambda tag: tag == "v0.21.5", edit=calls.append)
- assert published["flipped"] == "v0.21.5"
- assert calls == [["gh", "release", "edit", "v0.21.5", "--repo", "example/hermes-agent", "--draft=false"]]
+ published = publish("0.21.5", repository="example/hermes-agent", dispatch=calls.append)
+ assert published["requested"] == "v0.21.5"
+ assert calls == [[
+ "gh", "workflow", "run", "stable-release-publication.yml",
+ "--repo", "example/hermes-agent", "--raw-field", "version=0.21.5",
+ ]]
abandoned = abandon("0.21.5", repo=source, repository="example/hermes-agent", delete=calls.append)
assert abandoned["burned"] == "0.21.5"
diff --git a/tests/scripts/test_release_sequencer.py b/tests/scripts/test_release_sequencer.py
new file mode 100644
index 00000000000..18a31b659e9
--- /dev/null
+++ b/tests/scripts/test_release_sequencer.py
@@ -0,0 +1,186 @@
+"""Stable publication is ordered, held by default, and idempotent.
+
+A green draft publishes when it opted into autopublish, or when a later green
+release needs it resolved. A running older claim blocks only the versions above
+it; already-resolvable older green claims still make progress.
+"""
+import json
+
+import pytest
+
+
+def _claims(*rows):
+ return [dict(version=version, state=state, autopublish=autopublish)
+ for version, state, autopublish in rows]
+
+
+def _flips(steps):
+ return [step["flip"] for step in steps if "flip" in step]
+
+
+def test_a_sole_green_draft_waits_without_autopublish():
+ from scripts.releases.sequencer import plan
+
+ assert plan(_claims(("0.21.5", "green", False)), head="0.21.4") == []
+
+
+def test_autopublish_flips_the_current_green_release():
+ from scripts.releases.sequencer import plan
+
+ steps = plan(_claims(("0.21.5", "green", True)), head="0.21.4")
+ assert _flips(steps) == ["0.21.5"]
+ assert steps[-1] == {"advance": "0.21.5"}
+
+
+def test_a_newer_green_release_flushes_the_older_waiting_draft():
+ from scripts.releases.sequencer import plan
+
+ steps = plan(_claims(
+ ("0.21.5", "green", False),
+ ("0.21.6", "green", False),
+ ), head="0.21.4")
+
+ assert _flips(steps) == ["0.21.5"]
+ assert steps[-1] == {"advance": "0.21.5"}
+
+
+def test_green_progress_before_a_running_blocker_is_preserved():
+ from scripts.releases.sequencer import plan
+
+ steps = plan(_claims(
+ ("0.21.5", "green", False),
+ ("0.21.6", "running", False),
+ ("0.21.7", "green", True),
+ ), head="0.21.4")
+
+ assert _flips(steps) == ["0.21.5"]
+ assert steps[-1] == {"advance": "0.21.5"}
+
+
+def test_a_burned_claim_is_spent_and_skipped():
+ from scripts.releases.sequencer import plan
+
+ steps = plan(_claims(
+ ("0.21.5", "burned", False),
+ ("0.21.6", "green", True),
+ ), head="0.21.4")
+
+ assert _flips(steps) == ["0.21.6"]
+ assert steps[-1] == {"advance": "0.21.6"}
+
+
+def test_advances_each_published_version_and_ignores_a_later_burned_claim():
+ from scripts.releases.sequencer import plan
+
+ assert plan(_claims(
+ ("0.21.5", "published", False),
+ ("0.21.6", "published", False),
+ ), head="0.21.4") == [
+ {"advance": "0.21.5"},
+ {"advance": "0.21.6"},
+ ]
+ assert plan(_claims(
+ ("0.21.5", "green", False),
+ ("0.21.6", "burned", False),
+ ), head="0.21.4") == []
+
+
+def test_explicit_publish_uses_the_same_oldest_first_plan():
+ from scripts.releases.sequencer import plan
+
+ assert plan(_claims(
+ ("0.21.5", "green", False),
+ ("0.21.6", "green", False),
+ ), head="0.21.4", requested_version="0.21.6") == [
+ {"flip": "0.21.5"},
+ {"flip": "0.21.6"},
+ {"advance": "0.21.5"},
+ {"advance": "0.21.6"},
+ ]
+
+
+def test_published_history_at_or_below_the_head_is_an_idempotent_noop():
+ from scripts.releases.sequencer import plan
+
+ assert plan(_claims(
+ ("0.21.4", "published", False),
+ ("0.21.5", "green", False),
+ ), head="0.21.4") == []
+
+
+def test_an_unpublished_claim_below_the_head_is_refused():
+ from scripts.releases.sequencer import plan
+
+ with pytest.raises(ValueError, match="backwards"):
+ plan(_claims(("0.21.4", "green", True)), head="0.21.5")
+
+
+def test_reconcile_discovers_custody_flips_then_advances_oldest_first():
+ from scripts.releases.sequencer import reconcile
+
+ commit = "a" * 40
+ tags = {}
+ releases = []
+ for index, version in enumerate(("0.21.5", "0.21.6"), start=1):
+ claim_tag, tag = f"v{version}-rc", f"v{version}"
+ claim_object, final_object = str(index) * 40, str(index + 2) * 40
+ claim = {"schema": 1, "version": version, "commit": commit, "autopublish": False}
+ final = {**claim, "claimTag": claim_tag, "claimTagObject": claim_object}
+ tags[claim_tag] = (claim_object, commit, claim)
+ tags[tag] = (final_object, commit, final)
+ releases.append({
+ "id": index, "tag_name": tag, "draft": True, "prerelease": False,
+ "published_at": None,
+ })
+
+ events = []
+
+ def run(argv):
+ if argv[:2] == ["git", "fetch"]:
+ return ""
+ if argv[:3] == ["git", "ls-remote", "--tags"]:
+ return "\n".join(
+ f"{sha}\trefs/tags/{tag}\n{target}\trefs/tags/{tag}^{{}}"
+ for tag, (sha, target, _message) in tags.items()
+ )
+ if argv[:2] == ["git", "rev-parse"]:
+ return tags[argv[-1].removeprefix("refs/tags/")][0]
+ if argv[:3] == ["git", "cat-file", "-t"]:
+ return "tag"
+ if argv[:3] == ["git", "tag", "-l"]:
+ return json.dumps(tags[argv[3]][2])
+ if argv[:4] == ["gh", "api", "--paginate", "--slurp"]:
+ if "/releases?" in argv[-1]:
+ return json.dumps([releases])
+ return json.dumps([{"workflow_runs": []}])
+ if argv[:3] == ["gh", "api", "--method"]:
+ release_id = int(argv[4].rsplit("/", 1)[1])
+ release = next(row for row in releases if row["id"] == release_id)
+ release.update(tag_name=f"v0.21.{4 + release_id}", draft=False,
+ prerelease=False, published_at="2026-09-22T01:00:00Z")
+ events.append(("flip", release["tag_name"]))
+ return "{}"
+ if argv[:2] == ["gh", "api"] and "/releases/" in argv[2]:
+ release_id = int(argv[2].rsplit("/", 1)[1])
+ return json.dumps(next(row for row in releases if row["id"] == release_id))
+ raise AssertionError(argv)
+
+ head = ["0.21.4"]
+
+ def advance(record):
+ events.append(("advance", record["tag"]))
+ head[0] = record["version"]
+
+ steps = reconcile(
+ {"GITHUB_REPOSITORY": "example/project", "REQUESTED_VERSION": "0.21.6"},
+ run=run, read_head=lambda: head[0], advance_head=advance,
+ )
+
+ assert steps == [
+ {"flip": "0.21.5"}, {"flip": "0.21.6"},
+ {"advance": "0.21.5"}, {"advance": "0.21.6"},
+ ]
+ assert events == [
+ ("flip", "v0.21.5"), ("flip", "v0.21.6"),
+ ("advance", "v0.21.5"), ("advance", "v0.21.6"),
+ ]
diff --git a/tests/scripts/test_stable_release.py b/tests/scripts/test_stable_release.py
index 608dea85644..d73d5e7f007 100644
--- a/tests/scripts/test_stable_release.py
+++ b/tests/scripts/test_stable_release.py
@@ -20,12 +20,13 @@ ROOT = Path(__file__).resolve().parents[2]
def candidates(tag, commit, digest):
packages = []
+ native_version = f"2026.5761.{100 + int(tag.rsplit('.', 1)[1])}.0"
for platform in ("windows", "macos"):
for arch in ("x64", "arm64"):
packages.append({
"platform": platform, "arch": arch, "tag": tag, "commit": commit,
"identity": "test.application",
- "version": f"{tag[1:]}.0" if platform == "windows" else tag[1:],
+ "version": native_version if platform == "windows" else tag[1:],
**({"publisher": "CN=Test", "applicationId": "App"} if platform == "windows" else {"teamId": "ABCDEFGHIJ"}),
"artifact": {"sha256": digest,
"url": f"{BASE}/releases/tag/{tag}/{arch}" + (".msixbundle" if platform == "windows" else ".zip")},
@@ -200,11 +201,17 @@ def test_claim_object_movement_and_lightweight_tags_fail_closed(tmp_path, monkey
return "tag"
if argv[1] == "rev-parse":
return claim_object if argv[-1] == ref else commit
+ if argv[1] == "tag":
+ return json.dumps({
+ "schema": 1, "version": "1.2.3", "commit": commit,
+ "autopublish": False,
+ })
return ""
assert check_claim(env, git) == {
"claim_tag": "v1.2.3-rc", "claim_object": claim_object,
"tag": "v1.2.3", "version": "1.2.3", "commit": commit,
+ "autopublish": False,
}
with pytest.raises(ValueError, match="moved"):
check_claim(env, lambda argv: f"{'c' * 40}\t{ref}\n{commit}\t{ref}^{{}}"
@@ -225,7 +232,11 @@ def test_claim_object_movement_and_lightweight_tags_fail_closed(tmp_path, monkey
subprocess.run(["git", "commit", "-m", "first"], check=True, capture_output=True)
actual = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True, encoding="utf-8").strip()
subprocess.run(["git", "remote", "add", "origin", str(remote)], check=True)
- subprocess.run(["git", "tag", "-a", "v1.2.3-rc", "-m", "claim"], check=True)
+ metadata = json.dumps({
+ "schema": 1, "version": "1.2.3", "commit": actual,
+ "autopublish": False,
+ }, sort_keys=True, separators=(",", ":"))
+ subprocess.run(["git", "tag", "-a", "v1.2.3-rc", "-m", metadata], check=True)
subprocess.run(["git", "push", "origin", "main", "v1.2.3-rc"], check=True, capture_output=True)
env.update({"GITHUB_SHA": actual, "RELEASE_CLAIM_OBJECT": subprocess.check_output(
["git", "rev-parse", ref], text=True, encoding="utf-8").strip()})
@@ -247,17 +258,23 @@ def test_claim_object_movement_and_lightweight_tags_fail_closed(tmp_path, monkey
def test_retarget_release_preserves_the_database_id_and_explicit_draft_policy(publish):
commit = "a" * 40
calls = []
+ patched = False
def gh(argv):
+ nonlocal patched
calls.append(argv)
+ if argv[1:3] == ["api", "--method"]:
+ patched = True
+ return "{}"
if argv[1:3] == ["api", "repos/example/project/releases/42"]:
return json.dumps({
- "id": 42, "tag_name": "v1.2.3", "target_commitish": commit,
- "prerelease": False, "draft": not publish,
+ "id": 42, "tag_name": "v1.2.3" if patched else "v1.2.3-rc",
+ "target_commitish": commit, "prerelease": False,
+ "draft": not publish if patched else True,
})
return "{}"
retarget_release("example/project", 42, "v1.2.3", commit, publish=publish, run=gh)
- assert ["--field", f"draft={str(not publish).lower()}"] == calls[0][-2:]
- assert calls[1] == ["gh", "api", "repos/example/project/releases/42"]
+ assert ["--field", f"draft={str(not publish).lower()}"] == calls[1][-2:]
+ assert calls[2] == ["gh", "api", "repos/example/project/releases/42"]