Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(release): serialize official release finalization (#1632)
Call White251f40d338aa
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex 6c9977fd5..fe5bce816 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -20,9 +20,15 @@ jobs:outputs:tag: ${{ steps.tag.outputs.tag }}publish_legacy: ${{ steps.tag.outputs.publish_legacy }}+ prerelease: ${{ steps.tag.outputs.prerelease }}+ source_sha: ${{ steps.tag.outputs.source_sha }}+ workflow_branch: ${{ steps.tag.outputs.workflow_branch }}+ workflow_sha: ${{ steps.tag.outputs.workflow_sha }}steps:- name: Resolve tagid: tag+ env:+ GH_TOKEN: ${{ github.token }}shell: bashrun: |if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then@@ -41,8 +47,32 @@ jobs:PUBLISH_LEGACY="true"fi+ PRERELEASE="false"+ if [[ "$TAG" == *-* ]]; then+ PRERELEASE="true"+ elif [[ "$TAG" =~ ^v[0-9]+(\.[0-9]+)*(([.-])?(a|b|rc|dev)[0-9]+)$ ]]; then+ PRERELEASE="true"+ fi++ SOURCE_SHA="$(gh api "repos/${GITHUB_REPOSITORY}/commits/$TAG" --jq '.sha')"+ if [ -z "$SOURCE_SHA" ]; then+ echo "Could not resolve source commit for $TAG" >&2+ exit 1+ fi++ WORKFLOW_BRANCH="$GITHUB_REF_NAME"+ WORKFLOW_SHA="$GITHUB_SHA"+ if [ "${{ github.event_name }}" = "push" ]; then+ WORKFLOW_BRANCH="$TAG"+ WORKFLOW_SHA="$SOURCE_SHA"+ fi+echo "tag=$TAG" >> "$GITHUB_OUTPUT"echo "publish_legacy=$PUBLISH_LEGACY" >> "$GITHUB_OUTPUT"+ echo "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"+ echo "source_sha=$SOURCE_SHA" >> "$GITHUB_OUTPUT"+ echo "workflow_branch=$WORKFLOW_BRANCH" >> "$GITHUB_OUTPUT"+ echo "workflow_sha=$WORKFLOW_SHA" >> "$GITHUB_OUTPUT"resolve-show-runtime-ref:runs-on: ubuntu-latest@@ -335,26 +365,25 @@ jobs:tests/e2e/test_upgrade_command.py \-v+ - name: Checkout release automation+ uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5+ with:+ ref: ${{ needs.resolve-tag.outputs.workflow_sha }}+ path: release-automation+ sparse-checkout: scripts/github_release.py+ sparse-checkout-cone-mode: false+- name: Upload GitHub release assetsenv:GH_TOKEN: ${{ github.token }}shell: bashrun: |TAG="${{ needs.resolve-tag.outputs.tag }}"- PRERELEASE="false"- if [[ "$TAG" == *-* ]]; then- PRERELEASE="true"- elif [[ "$TAG" =~ ^v[0-9]+(\.[0-9]+)*(([.-])?(a|b|rc|dev)[0-9]+)$ ]]; then- PRERELEASE="true"- fi-- if ! gh release view "$TAG" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1; then- ARGS=(release create "$TAG" --repo "${GITHUB_REPOSITORY}" --title "$TAG" --notes "Release assets for $TAG.")- if [ "$PRERELEASE" = "true" ]; then- ARGS+=(--prerelease)- fi- gh "${ARGS[@]}" || gh release view "$TAG" --repo "${GITHUB_REPOSITORY}" >/dev/null- fi+ python release-automation/scripts/github_release.py ensure-draft \+ --repo "$GITHUB_REPOSITORY" \+ --tag "$TAG" \+ --title "$TAG" \+ --notes "Release assets for $TAG."# Runtime archives + manifests are IMMUTABLE per tag and must NOT be# re-clobbered. Builds are normalized and pinned, but the wheel published@@ -402,7 +431,9 @@ jobs:path: dist/publish-avibe-os:- needs: build+ needs:+ - build+ - finalize-github-releaseruns-on: ubuntu-latestenvironment: pypipermissions:@@ -431,6 +462,7 @@ jobs:needs:- resolve-tag- build+ - finalize-github-releaseif: needs.resolve-tag.outputs.publish_legacy == 'true'runs-on: ubuntu-latest# PyPI trusted publishers issue project-scoped tokens for the exact OIDC@@ -459,3 +491,50 @@ jobs:skip-existing: true# Uses trusted publishing (OIDC), no API token needed# Configure at: https://pypi.org/manage/project/vibe-remote/settings/publishing/++ finalize-github-release:+ needs:+ - resolve-tag+ - build+ runs-on: ubuntu-latest+ permissions:+ actions: read+ contents: write+ steps:+ - name: Checkout+ uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5+ with:+ ref: ${{ needs.resolve-tag.outputs.workflow_sha }}++ - name: Wait for exact-source release notes+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ python scripts/github_release.py wait-notes \+ --repo "$GITHUB_REPOSITORY" \+ --tag "${{ needs.resolve-tag.outputs.tag }}" \+ --workflow release_ai.yml \+ --branch "${{ needs.resolve-tag.outputs.workflow_branch }}" \+ --run-sha "${{ needs.resolve-tag.outputs.workflow_sha }}" \+ --source-sha "${{ needs.resolve-tag.outputs.source_sha }}" \+ --event "${{ github.event_name }}" \+ --timeout 3600 \+ --interval 15++ - name: Publish GitHub Release+ env:+ GH_TOKEN: ${{ github.token }}+ shell: bash+ run: |+ LATEST_MODE="preserve"+ if [ "${{ needs.resolve-tag.outputs.prerelease }}" = "true" ]; then+ LATEST_MODE="false"+ elif [ "${{ github.event_name }}" = "push" ]; then+ LATEST_MODE="true"+ fi++ python scripts/github_release.py finalize \+ --repo "$GITHUB_REPOSITORY" \+ --tag "${{ needs.resolve-tag.outputs.tag }}" \+ --prerelease "${{ needs.resolve-tag.outputs.prerelease }}" \+ --latest "$LATEST_MODE"diff --git a/.github/workflows/release_ai.yml b/.github/workflows/release_ai.ymlindex 1893e1a6f..9a24116cd 100644--- a/.github/workflows/release_ai.yml+++ b/.github/workflows/release_ai.yml@@ -566,14 +566,12 @@ jobs:has_marker="true"fi- # Source 2: an already-created release body. A silent release is often- # set up by pre-creating the release with the marker comment in its body- # (e.g. via 'gh release create --notes-file'). Both this job (official- # tags) and the later softprops step (gh-v* tags) replace the body with- # release.md, which would otherwise STRIP that marker — so this applies- # to ALL tags, not just official ones. Require the STRICT HTML-comment- # form here: a body that merely DOCUMENTS the marker text as prose- # (e.g. notes about this workflow) is not an intent to go silent.+ # Source 2: an already-created release body. This keeps reruns and+ # releases created by the legacy process idempotent; new releases carry+ # intent in the annotated tag instead. Replacing the body with release.md+ # would otherwise STRIP that marker, so this applies to ALL tags. Require+ # the STRICT HTML-comment form: prose that merely documents the marker is+ # not an intent to go silent.if [ "$has_marker" != "true" ]; thenEXISTING_BODY=$(gh release view "$TAG" --repo "${GITHUB_REPOSITORY}" --json body --jq '.body' 2>/dev/null || true)if echo "$EXISTING_BODY" | grep -qE "$MARKER_COMMENT_RE"; then@@ -593,7 +591,14 @@ jobs:mv release.md.tmp release.mdfi+ SOURCE_SHA="$(git rev-parse "${TAG}^{commit}")"+ READY_MARKER="<!-- avibe:release-notes=ready source=${SOURCE_SHA} run=${GITHUB_RUN_ID} -->"+ if ! grep -qF "$READY_MARKER" release.md; then+ printf '\n\n%s\n' "$READY_MARKER" >> release.md+ fi+- name: Download release artifacts+ if: startsWith(steps.tag.outputs.tag, 'gh-v')uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8with:name: release-dist@@ -607,20 +612,11 @@ jobs:run: |set -euo pipefailTAG="${{ steps.tag.outputs.tag }}"- if ! gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then- ARGS=(release create "$TAG" --repo "$GITHUB_REPOSITORY" --title "$TAG" --notes-file release.md)- if [ "${{ steps.release_type.outputs.prerelease }}" = "true" ]; then- ARGS+=(--prerelease)- fi- if [ "${{ github.event_name }}" = "push" ] && [ "${{ steps.release_type.outputs.prerelease }}" != "true" ]; then- ARGS+=(--latest)- else- ARGS+=(--latest=false)- fi- gh "${ARGS[@]}" || gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null- else- gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --title "$TAG" --notes-file release.md- fi+ python scripts/github_release.py update-notes \+ --repo "$GITHUB_REPOSITORY" \+ --tag "$TAG" \+ --title "$TAG" \+ --notes-file release.mdexisting="$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name')"temporary="$(mktemp -d)"@@ -669,6 +665,12 @@ jobs:figh release upload "$TAG" --repo "$GITHUB_REPOSITORY" "${package_assets[@]}" --clobber+ python scripts/github_release.py finalize \+ --repo "$GITHUB_REPOSITORY" \+ --tag "$TAG" \+ --prerelease "${{ steps.release_type.outputs.prerelease }}" \+ --latest false+- name: Update official release notesif: ${{ !startsWith(steps.tag.outputs.tag, 'gh-v') }}env:@@ -676,24 +678,8 @@ jobs:shell: bashrun: |TAG="${{ steps.tag.outputs.tag }}"- if ! gh release view "$TAG" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1; then- ARGS=(release create "$TAG" --repo "${GITHUB_REPOSITORY}" --title "$TAG" --notes-file release.md)- if [ "${{ steps.release_type.outputs.prerelease }}" = "true" ]; then- ARGS+=(--prerelease)- fi- if [ "${{ github.event_name }}" = "push" ] && [ "${{ steps.release_type.outputs.prerelease }}" != "true" ]; then- ARGS+=(--latest)- fi- gh "${ARGS[@]}" || gh release edit "$TAG" --repo "${GITHUB_REPOSITORY}" --notes-file release.md- else- EDIT_ARGS=(release edit "$TAG" --repo "${GITHUB_REPOSITORY}" --title "$TAG" --notes-file release.md)- if [ "${{ steps.release_type.outputs.prerelease }}" = "true" ]; then- EDIT_ARGS+=(--prerelease)- else- EDIT_ARGS+=(--prerelease=false)- fi- if [ "${{ github.event_name }}" = "push" ] && [ "${{ steps.release_type.outputs.prerelease }}" != "true" ]; then- EDIT_ARGS+=(--latest)- fi- gh "${EDIT_ARGS[@]}"- fi+ python scripts/github_release.py update-notes \+ --repo "$GITHUB_REPOSITORY" \+ --tag "$TAG" \+ --title "$TAG" \+ --notes-file release.mddiff --git a/AGENTS.md b/AGENTS.mdindex 753cc0cbb..5d446287b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -311,7 +311,9 @@ Source-of-truth rule:## 9. Release Notes- tags follow the latest version number +1 (for example `v1.0.1` -> `v1.0.2`)-- before publishing a release, explicitly decide whether the version should notify users; add `<!-- avibe:update-notification=none -->` to the GitHub Release body when update and post-update notifications should be suppressed while automatic update behavior remains enabled. The legacy `vibe-remote` marker is still parsed for compatibility.+- before publishing a release, explicitly decide whether the version should notify users; put `<!-- avibe:update-notification=none -->` in the annotated tag message when update and post-update notifications should be suppressed while automatic update behavior remains enabled. The workflow emits both the current and legacy `vibe-remote` markers into the GitHub Release body for installed-client compatibility.+- for an official `v*` release, the annotated tag is the operator's only release-state input: put silent-update intent in the tag annotation, push the tag, and do not pre-create or manually edit a GitHub Release+- the official workflows stage assets and generated notes in a Draft; `Release (AI Notes)` may update notes but never publishes. The `Publish to PyPI` workflow is the single finalizer: it verifies the exact notes run, publishes the asset-complete GitHub Release, and only then allows PyPI publication so package manifests never point at private Draft assets- GitHub-only pre-releases should use the `gh-vX.Y.ZrcN` format (for example `gh-v2.2.8rc2`) so they stay distinct from PyPI-triggering `v*` tags- GitHub-only pre-releases must include installable artifacts in the GitHub release assets: a wheel built with `ui/dist` and bundled `vibe/show_runtime/*.tgz`, plus the sdist- releases are published automatically by workflow after tagging/pushdiff --git a/scripts/github_release.py b/scripts/github_release.pynew file mode 100644index 000000000..b7f138c05--- /dev/null+++ b/scripts/github_release.py@@ -0,0 +1,373 @@+#!/usr/bin/env python3+"""Own GitHub Release state transitions shared by release workflows."""++from __future__ import annotations++import argparse+import json+import re+import subprocess+import sys+import time+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any, Sequence+from urllib.parse import quote+++NOTES_READY_MARKER_PREFIX = "<!-- avibe:release-notes=ready source="+_SHA_RE = re.compile(r"[0-9a-f]{40}")+++class ReleaseError(RuntimeError):+ """Raised when a GitHub Release transition cannot be proven complete."""+++@dataclass(frozen=True)+class ReleaseState:+ tag: str+ draft: bool+ prerelease: bool+ body: str+ url: str+++def notes_ready_marker(source_sha: str, run_id: int) -> str:+ if _SHA_RE.fullmatch(source_sha) is None:+ raise ReleaseError(f"Invalid release source SHA: {source_sha!r}")+ if run_id <= 0:+ raise ReleaseError(f"Invalid release notes run ID: {run_id!r}")+ return f"{NOTES_READY_MARKER_PREFIX}{source_sha} run={run_id} -->"+++def _run_gh(arguments: Sequence[str], *, check: bool = True) -> subprocess.CompletedProcess[str]:+ command = ["gh", *arguments]+ completed = subprocess.run(command, capture_output=True, text=True, check=False)+ if check and completed.returncode != 0:+ detail = completed.stderr.strip() or completed.stdout.strip() or "unknown error"+ raise ReleaseError(f"{' '.join(command)} failed: {detail}")+ return completed+++def _release_path(repo: str, tag: str) -> str:+ return f"repos/{repo}/releases/tags/{quote(tag, safe='')}"+++def get_release(repo: str, tag: str) -> ReleaseState | None:+ completed = _run_gh(["api", _release_path(repo, tag)], check=False)+ if completed.returncode != 0:+ if "HTTP 404" in completed.stderr:+ return None+ detail = completed.stderr.strip() or completed.stdout.strip() or "unknown error"+ raise ReleaseError(f"Could not inspect GitHub Release {tag}: {detail}")++ try:+ payload = json.loads(completed.stdout)+ return ReleaseState(+ tag=str(payload["tag_name"]),+ draft=bool(payload["draft"]),+ prerelease=bool(payload["prerelease"]),+ body=str(payload.get("body") or ""),+ url=str(payload["html_url"]),+ )+ except (KeyError, TypeError, ValueError) as exc:+ raise ReleaseError(f"Invalid GitHub Release payload for {tag}") from exc+++def _notes_arguments(*, notes: str | None, notes_file: Path | None) -> list[str]:+ if notes_file is not None:+ return ["--notes-file", str(notes_file)]+ if notes is not None:+ return ["--notes", notes]+ raise ReleaseError("Release notes or a release notes file is required")+++def ensure_draft(+ *,+ repo: str,+ tag: str,+ title: str,+ notes: str | None,+ notes_file: Path | None,+) -> ReleaseState:+ existing = get_release(repo, tag)+ if existing is not None:+ return existing++ arguments = [+ "release",+ "create",+ tag,+ "--repo",+ repo,+ "--title",+ title,+ *_notes_arguments(notes=notes, notes_file=notes_file),+ "--draft",+ "--latest=false",+ "--verify-tag",+ ]+ created = _run_gh(arguments, check=False)+ if created.returncode != 0:+ # Another release workflow may have won the create race. Only that+ # proven state makes the failed create recoverable.+ raced = get_release(repo, tag)+ if raced is None:+ detail = created.stderr.strip() or created.stdout.strip() or "unknown error"+ raise ReleaseError(f"Could not create draft GitHub Release {tag}: {detail}")+ return raced++ for _ in range(5):+ state = get_release(repo, tag)+ if state is not None:+ return state+ time.sleep(0.2)+ raise ReleaseError(f"Draft GitHub Release {tag} was created but cannot be read back")+++def update_notes(+ *,+ repo: str,+ tag: str,+ title: str,+ notes_file: Path,+) -> ReleaseState:+ ensure_draft(+ repo=repo,+ tag=tag,+ title=title,+ notes=None,+ notes_file=notes_file,+ )+ _run_gh(+ [+ "release",+ "edit",+ tag,+ "--repo",+ repo,+ "--title",+ title,+ "--notes-file",+ str(notes_file),+ ]+ )+ state = get_release(repo, tag)+ if state is None:+ raise ReleaseError(f"GitHub Release {tag} disappeared after updating notes")+ return state+++def _ready_run_id(body: str, source_sha: str) -> int | None:+ marker = re.search(+ re.escape(NOTES_READY_MARKER_PREFIX)+ + re.escape(source_sha)+ + r" run=([1-9][0-9]*) -->",+ body,+ )+ return int(marker.group(1)) if marker else None+++def _get_workflow_run(*, repo: str, run_id: int) -> dict[str, Any]:+ completed = _run_gh(["api", f"repos/{repo}/actions/runs/{run_id}"])+ try:+ payload = json.loads(completed.stdout)+ except ValueError as exc:+ raise ReleaseError("Invalid GitHub Actions run payload") from exc+ if not isinstance(payload, dict):+ raise ReleaseError("GitHub Actions run payload is not an object")+ return payload+++def wait_for_notes(+ *,+ repo: str,+ tag: str,+ workflow: str,+ branch: str,+ run_sha: str,+ source_sha: str,+ event: str,+ timeout: float,+ interval: float,+) -> ReleaseState:+ deadline = time.monotonic() + timeout+ while True:+ state = get_release(repo, tag)+ run_id = _ready_run_id(state.body, source_sha) if state is not None else None+ if run_id is not None:+ run = _get_workflow_run(repo=repo, run_id=run_id)+ run_path = str(run.get("path") or "").split("@", 1)[0]+ expected_path = f".github/workflows/{workflow}"+ if run_path != expected_path:+ raise ReleaseError(+ f"Release notes marker points to unexpected workflow {run_path!r}"+ )+ if run.get("head_sha") != run_sha or run.get("head_branch") != branch:+ raise ReleaseError(+ f"Release notes run {run_id} does not match the expected workflow revision"+ )+ if run.get("event") != event:+ raise ReleaseError(+ f"Release notes run {run_id} has unexpected event {run.get('event')!r}"+ )+ if run.get("status") == "completed":+ if run.get("conclusion") != "success":+ raise ReleaseError(+ f"Release notes workflow did not succeed for {source_sha}: "+ f"{run.get('html_url') or run_id}"+ )+ return state++ if time.monotonic() >= deadline:+ raise ReleaseError(+ f"Timed out waiting for {workflow} notes marker for {tag}"+ )+ time.sleep(interval)+++def finalize_release(+ *,+ repo: str,+ tag: str,+ prerelease: bool,+ latest: str,+) -> ReleaseState:+ if get_release(repo, tag) is None:+ raise ReleaseError(f"Cannot finalize missing GitHub Release {tag}")++ arguments = [+ "release",+ "edit",+ tag,+ "--repo",+ repo,+ "--draft=false",+ "--prerelease" if prerelease else "--prerelease=false",+ ]+ if latest == "true":+ arguments.append("--latest")+ elif latest == "false":+ arguments.append("--latest=false")+ _run_gh(arguments)++ state = None+ for _ in range(10):+ state = get_release(repo, tag)+ if state is not None and not state.draft and state.prerelease == prerelease:+ break+ time.sleep(1)+ if state is None or state.draft:+ raise ReleaseError(f"GitHub Release {tag} is still a draft after finalization")+ if state.prerelease != prerelease:+ raise ReleaseError(f"GitHub Release {tag} has the wrong prerelease state")++ if latest != "preserve":+ for _ in range(10):+ current_latest = _run_gh(+ ["api", f"repos/{repo}/releases/latest", "--jq", ".tag_name"],+ check=False,+ )+ latest_tag = (+ current_latest.stdout.strip() if current_latest.returncode == 0 else ""+ )+ latest_matches = latest_tag == tag+ if (latest == "true" and latest_matches) or (+ latest == "false" and not latest_matches+ ):+ break+ time.sleep(1)+ else:+ if latest == "true":+ raise ReleaseError(f"GitHub Release {tag} was not made latest")+ raise ReleaseError(f"GitHub Release {tag} unexpectedly became latest")+ return state+++def _print_state(state: ReleaseState) -> None:+ print(json.dumps(asdict(state), sort_keys=True))+++def _parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__)+ subparsers = parser.add_subparsers(dest="command", required=True)++ ensure = subparsers.add_parser("ensure-draft")+ ensure.add_argument("--repo", required=True)+ ensure.add_argument("--tag", required=True)+ ensure.add_argument("--title", required=True)+ ensure_notes = ensure.add_mutually_exclusive_group(required=True)+ ensure_notes.add_argument("--notes")+ ensure_notes.add_argument("--notes-file", type=Path)++ update = subparsers.add_parser("update-notes")+ update.add_argument("--repo", required=True)+ update.add_argument("--tag", required=True)+ update.add_argument("--title", required=True)+ update.add_argument("--notes-file", required=True, type=Path)++ wait = subparsers.add_parser("wait-notes")+ wait.add_argument("--repo", required=True)+ wait.add_argument("--tag", required=True)+ wait.add_argument("--workflow", required=True)+ wait.add_argument("--branch", required=True)+ wait.add_argument("--run-sha", required=True)+ wait.add_argument("--source-sha", required=True)+ wait.add_argument("--event", required=True)+ wait.add_argument("--timeout", type=float, default=3600)+ wait.add_argument("--interval", type=float, default=15)++ finalize = subparsers.add_parser("finalize")+ finalize.add_argument("--repo", required=True)+ finalize.add_argument("--tag", required=True)+ finalize.add_argument("--prerelease", choices=("true", "false"), required=True)+ finalize.add_argument("--latest", choices=("true", "false", "preserve"), required=True)+ return parser+++def main(argv: Sequence[str] | None = None) -> int:+ arguments = _parser().parse_args(argv)+ try:+ if arguments.command == "ensure-draft":+ state = ensure_draft(+ repo=arguments.repo,+ tag=arguments.tag,+ title=arguments.title,+ notes=arguments.notes,+ notes_file=arguments.notes_file,+ )+ elif arguments.command == "update-notes":+ state = update_notes(+ repo=arguments.repo,+ tag=arguments.tag,+ title=arguments.title,+ notes_file=arguments.notes_file,+ )+ elif arguments.command == "wait-notes":+ state = wait_for_notes(+ repo=arguments.repo,+ tag=arguments.tag,+ workflow=arguments.workflow,+ branch=arguments.branch,+ run_sha=arguments.run_sha,+ source_sha=arguments.source_sha,+ event=arguments.event,+ timeout=arguments.timeout,+ interval=arguments.interval,+ )+ else:+ state = finalize_release(+ repo=arguments.repo,+ tag=arguments.tag,+ prerelease=arguments.prerelease == "true",+ latest=arguments.latest,+ )+ except ReleaseError as exc:+ print(f"::error::{exc}", file=sys.stderr)+ return 1+ _print_state(state)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_github_release.py b/tests/test_github_release.pynew file mode 100644index 000000000..98c5da4e4--- /dev/null+++ b/tests/test_github_release.py@@ -0,0 +1,404 @@+from __future__ import annotations++import json+import subprocess+from pathlib import Path++import pytest++from scripts import github_release+++REPO = "avibe-bot/avibe"+TAG = "v3.0.14"+SOURCE_SHA = "a" * 40+++def _completed(+ arguments: list[str],+ *,+ returncode: int = 0,+ stdout: str = "",+ stderr: str = "",+) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(+ ["gh", *arguments],+ returncode,+ stdout=stdout,+ stderr=stderr,+ )+++def _release_payload(*, draft: bool, prerelease: bool = False, body: str = "notes") -> str:+ return json.dumps(+ {+ "tag_name": TAG,+ "draft": draft,+ "prerelease": prerelease,+ "body": body,+ "html_url": f"https://github.com/{REPO}/releases/tag/{TAG}",+ }+ )+++def test_get_release_treats_only_http_404_as_absent(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def not_found(arguments: list[str], *, check: bool = True):+ assert check is False+ return _completed(arguments, returncode=1, stderr="gh: Not Found (HTTP 404)\n")++ monkeypatch.setattr(github_release, "_run_gh", not_found)+ assert github_release.get_release(REPO, TAG) is None++ def unauthorized(arguments: list[str], *, check: bool = True):+ assert check is False+ return _completed(arguments, returncode=1, stderr="gh: HTTP 401: Bad credentials\n")++ monkeypatch.setattr(github_release, "_run_gh", unauthorized)+ with pytest.raises(github_release.ReleaseError, match="Could not inspect"):+ github_release.get_release(REPO, TAG)+++def test_ensure_draft_creates_a_verified_non_latest_draft(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ calls: list[list[str]] = []+ release_reads = iter(+ [+ _completed([], returncode=1, stderr="gh: Not Found (HTTP 404)\n"),+ _completed([], stdout=_release_payload(draft=True)),+ ]+ )++ def fake_run(arguments: list[str], *, check: bool = True):+ calls.append(arguments)+ if arguments[0] == "api":+ return next(release_reads)+ return _completed(arguments)++ monkeypatch.setattr(github_release, "_run_gh", fake_run)+ state = github_release.ensure_draft(+ repo=REPO,+ tag=TAG,+ title=TAG,+ notes="placeholder",+ notes_file=None,+ )++ assert state.draft is True+ create = next(call for call in calls if call[:2] == ["release", "create"])+ assert create == [+ "release",+ "create",+ TAG,+ "--repo",+ REPO,+ "--title",+ TAG,+ "--notes",+ "placeholder",+ "--draft",+ "--latest=false",+ "--verify-tag",+ ]++[email protected]("draft", [True, False])+def test_ensure_draft_reuses_every_existing_release_state(+ monkeypatch: pytest.MonkeyPatch,+ draft: bool,+) -> None:+ calls: list[list[str]] = []++ def fake_run(arguments: list[str], *, check: bool = True):+ calls.append(arguments)+ return _completed(arguments, stdout=_release_payload(draft=draft))++ monkeypatch.setattr(github_release, "_run_gh", fake_run)+ state = github_release.ensure_draft(+ repo=REPO,+ tag=TAG,+ title=TAG,+ notes="placeholder",+ notes_file=None,+ )++ assert state.draft is draft+ assert all(call[:2] != ["release", "create"] for call in calls)+++def test_update_notes_never_changes_publication_flags(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ notes_file = tmp_path / "release.md"+ notes_file.write_text("release notes", encoding="utf-8")+ calls: list[list[str]] = []++ def fake_run(arguments: list[str], *, check: bool = True):+ calls.append(arguments)+ if arguments[0] == "api":+ return _completed(arguments, stdout=_release_payload(draft=True))+ return _completed(arguments)++ monkeypatch.setattr(github_release, "_run_gh", fake_run)+ github_release.update_notes(+ repo=REPO,+ tag=TAG,+ title=TAG,+ notes_file=notes_file,+ )++ edit = next(call for call in calls if call[:2] == ["release", "edit"])+ assert "--draft=false" not in edit+ assert "--latest" not in edit+ assert "--latest=false" not in edit+ assert "--prerelease" not in edit+ assert "--prerelease=false" not in edit+++def test_wait_for_notes_requires_exact_source_success_and_ready_body(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ release_states = iter(+ [+ github_release.ReleaseState(+ tag=TAG,+ draft=True,+ prerelease=False,+ body="notes without marker",+ url="https://example.test/release",+ ),+ github_release.ReleaseState(+ tag=TAG,+ draft=True,+ prerelease=False,+ body=f"notes\n{github_release.notes_ready_marker(SOURCE_SHA, 42)}",+ url="https://example.test/release",+ ),+ ]+ )+ monkeypatch.setattr(github_release.time, "sleep", lambda _seconds: None)+ monkeypatch.setattr(+ github_release,+ "get_release",+ lambda _repo, _tag: next(release_states),+ )+ monkeypatch.setattr(+ github_release,+ "_get_workflow_run",+ lambda **_kwargs: {+ "id": 42,+ "status": "completed",+ "conclusion": "success",+ "head_sha": SOURCE_SHA,+ "head_branch": TAG,+ "event": "push",+ "path": ".github/workflows/release_ai.yml",+ "html_url": "https://example.test/run/42",+ },+ )++ state = github_release.wait_for_notes(+ repo=REPO,+ tag=TAG,+ workflow="release_ai.yml",+ branch=TAG,+ run_sha=SOURCE_SHA,+ source_sha=SOURCE_SHA,+ event="push",+ timeout=10,+ interval=0,+ )+ assert state.draft is True+++def test_wait_for_notes_rejects_success_without_ready_marker(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ github_release,+ "get_release",+ lambda _repo, _tag: github_release.ReleaseState(+ tag=TAG,+ draft=True,+ prerelease=False,+ body="notes without marker",+ url="https://example.test/release",+ ),+ )++ with pytest.raises(github_release.ReleaseError, match="Timed out"):+ github_release.wait_for_notes(+ repo=REPO,+ tag=TAG,+ workflow="release_ai.yml",+ branch=TAG,+ run_sha=SOURCE_SHA,+ source_sha=SOURCE_SHA,+ event="push",+ timeout=0,+ interval=0,+ )+++def test_wait_for_notes_rejects_the_failed_run_named_by_the_tag_marker(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ github_release,+ "get_release",+ lambda _repo, _tag: github_release.ReleaseState(+ tag=TAG,+ draft=True,+ prerelease=False,+ body=github_release.notes_ready_marker(SOURCE_SHA, 43),+ url="https://example.test/release",+ ),+ )+ monkeypatch.setattr(+ github_release,+ "_get_workflow_run",+ lambda **_kwargs: {+ "id": 43,+ "status": "completed",+ "conclusion": "failure",+ "head_sha": SOURCE_SHA,+ "head_branch": TAG,+ "event": "push",+ "path": ".github/workflows/release_ai.yml",+ "html_url": "https://example.test/run/43",+ },+ )++ with pytest.raises(github_release.ReleaseError, match="run/43"):+ github_release.wait_for_notes(+ repo=REPO,+ tag=TAG,+ workflow="release_ai.yml",+ branch=TAG,+ run_sha=SOURCE_SHA,+ source_sha=SOURCE_SHA,+ event="push",+ timeout=10,+ interval=0,+ )+++def test_ready_marker_requires_an_exact_commit_sha() -> None:+ with pytest.raises(github_release.ReleaseError, match="Invalid release source SHA"):+ github_release.notes_ready_marker("main", 42)++ with pytest.raises(github_release.ReleaseError, match="Invalid release notes run ID"):+ github_release.notes_ready_marker(SOURCE_SHA, 0)+++ ("prerelease", "latest", "latest_tag", "expected_flags"),+ [+ (False, "true", TAG, {"--draft=false", "--prerelease=false", "--latest"}),+ (True, "false", "v3.0.13", {"--draft=false", "--prerelease", "--latest=false"}),+ ],+)+def test_finalize_is_the_only_explicit_publication_transition(+ monkeypatch: pytest.MonkeyPatch,+ prerelease: bool,+ latest: str,+ latest_tag: str,+ expected_flags: set[str],+) -> None:+ calls: list[list[str]] = []+ release_reads = iter(+ [+ _completed([], stdout=_release_payload(draft=True, prerelease=prerelease)),+ _completed([], stdout=_release_payload(draft=False, prerelease=prerelease)),+ ]+ )++ def fake_run(arguments: list[str], *, check: bool = True):+ calls.append(arguments)+ if arguments[0] == "api" and arguments[1].endswith("/releases/latest"):+ return _completed(arguments, stdout=f"{latest_tag}\n")+ if arguments[0] == "api":+ return next(release_reads)+ return _completed(arguments)++ monkeypatch.setattr(github_release, "_run_gh", fake_run)+ state = github_release.finalize_release(+ repo=REPO,+ tag=TAG,+ prerelease=prerelease,+ latest=latest,+ )++ assert state.draft is False+ edit = next(call for call in calls if call[:2] == ["release", "edit"])+ assert expected_flags <= set(edit)+++def test_finalize_waits_for_release_and_latest_readback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ release_reads = iter(+ [+ _completed([], stdout=_release_payload(draft=True)),+ _completed([], stdout=_release_payload(draft=True)),+ _completed([], stdout=_release_payload(draft=False)),+ ]+ )+ latest_reads = iter(["v3.0.13\n", f"{TAG}\n"])+ sleeps: list[float] = []++ def fake_run(arguments: list[str], *, check: bool = True):+ if arguments[0] == "api" and arguments[1].endswith("/releases/latest"):+ return _completed(arguments, stdout=next(latest_reads))+ if arguments[0] == "api":+ return next(release_reads)+ return _completed(arguments)++ monkeypatch.setattr(github_release, "_run_gh", fake_run)+ monkeypatch.setattr(github_release.time, "sleep", sleeps.append)++ state = github_release.finalize_release(+ repo=REPO,+ tag=TAG,+ prerelease=False,+ latest="true",+ )+ assert state.draft is False+ assert sleeps == [1, 1]+++def test_release_workflows_stage_then_finalize_once() -> None:+ root = Path(__file__).resolve().parents[1]+ publish = (root / ".github/workflows/publish.yml").read_text(encoding="utf-8")+ notes = (root / ".github/workflows/release_ai.yml").read_text(encoding="utf-8")++ assert "python release-automation/scripts/github_release.py ensure-draft" in publish+ assert "path: release-automation" in publish+ assert "ref: ${{ needs.resolve-tag.outputs.workflow_sha }}" in publish+ assert publish.index("- name: Build package") < publish.index(+ "- name: Checkout release automation"+ )+ assert "finalize-github-release:" in publish+ assert "python scripts/github_release.py wait-notes" in publish+ assert "--run-sha \"${{ needs.resolve-tag.outputs.workflow_sha }}\"" in publish+ assert "--source-sha \"${{ needs.resolve-tag.outputs.source_sha }}\"" in publish+ assert "python scripts/github_release.py finalize" in publish+ avibe_publish = publish.split(" publish-avibe-os:", 1)[1].split(+ " publish-vibe-remote:", 1+ )[0]+ legacy_publish = publish.split(" publish-vibe-remote:", 1)[1].split(+ " finalize-github-release:", 1+ )[0]+ assert "- finalize-github-release" in avibe_publish+ assert "- finalize-github-release" in legacy_publish++ official_step = notes.split("- name: Update official release notes", 1)[1]+ assert "python scripts/github_release.py update-notes" in official_step+ assert "python scripts/github_release.py finalize" not in official_step+ assert github_release.NOTES_READY_MARKER_PREFIX in notes+ assert "run=${GITHUB_RUN_ID}" in notes+ assert "<!-- avibe:update-notification=none -->" in notes+ assert "<!-- vibe-remote:update-notification=none -->" in notes