Skip to content

The agent that grows with you

feat(release): stage commit builds with verified receipts

ethernet1c4093fdc9c4
diff --git a/scripts/releases/handoff.py b/scripts/releases/handoff.py
index 559a64e42c9..249e505dfd9 100644
--- a/scripts/releases/handoff.py
+++ b/scripts/releases/handoff.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import argparse
import fnmatch
import json
-import ntpath
import os
import re
import tempfile
@@ -14,6 +13,10 @@ from scripts.releases import r2
from scripts.releases.semver import is_valid_version
+class MissingReceipt(ValueError):
+ """A missing receipt is incomplete work, not a corrupt receipt."""
+
+
def validate_identity(tag: str, commit: str, name: str) -> None:
if (not isinstance(tag, str) or not tag.startswith("v") or not is_valid_version(tag[1:])
or not re.fullmatch(r"[a-f0-9]{40}", commit or "")
@@ -21,24 +24,15 @@ def validate_identity(tag: str, commit: str, name: str) -> None:
raise ValueError("Invalid release handoff identity")
-def receipt_name(name: str) -> str:
- return f"handoff-{name}.json"
-
-
-def relative_path(value: str) -> str:
- if (not isinstance(value, str) or not value or value.startswith("/")
- or any(part in ("", ".", "..") for part in value.split("/"))
- or any(c in value for c in "\\:%?#") or any(ord(c) < 32 for c in value)
- or ntpath.isreserved(value)):
- raise ValueError("Invalid release artifact path")
- return value
+def validate_commit_identity(commit: str, name: str) -> None:
+ """Identity for commit-only handoffs: no tag, an exact full SHA."""
+ if (not r2.is_full_sha(commit)
+ or not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name or "")):
+ raise ValueError("Invalid commit handoff identity")
-def validate_receipt(receipt: dict, tag: str, commit: str, name: str) -> list[dict]:
- validate_identity(tag, commit, name)
- if (not isinstance(receipt, dict) or receipt.get("schema") != 1
- or receipt.get("tag") != tag or receipt.get("commit") != commit or receipt.get("name") != name):
- raise ValueError("Release handoff identity mismatch")
+def validate_receipt_files(receipt: dict) -> list[dict]:
+ """Shared receipt-body rules: non-empty unique paths, int sizes, digests."""
files = receipt.get("files")
if not isinstance(files, list) or not files:
raise ValueError("No files in release handoff")
@@ -46,7 +40,7 @@ def validate_receipt(receipt: dict, tag: str, commit: str, name: str) -> list[di
for row in files:
if not isinstance(row, dict):
raise ValueError("Invalid release file receipt")
- path = relative_path(row.get("path"))
+ path = r2.relative_artifact_path(row.get("path"))
if path.casefold() in seen:
raise ValueError("Duplicate release artifact path")
seen.add(path.casefold())
@@ -56,8 +50,30 @@ def validate_receipt(receipt: dict, tag: str, commit: str, name: str) -> list[di
return files
-def stage(tag: str, commit: str, name: str, root: Path, includes: list[str]) -> dict:
+def receipt_name(name: str) -> str:
+ return f"handoff-{name}.json"
+
+
+def validate_receipt(receipt: dict, tag: str, commit: str, name: str) -> list[dict]:
validate_identity(tag, commit, name)
+ if (not isinstance(receipt, dict) or receipt.get("schema") != 1
+ or receipt.get("tag") != tag or receipt.get("commit") != commit or receipt.get("name") != name):
+ raise ValueError("Release handoff identity mismatch")
+ return validate_receipt_files(receipt)
+
+
+def validate_commit_receipt(receipt: dict, commit: str, name: str) -> list[dict]:
+ """Schema-2 receipts bind the files to a commit with no tag anywhere."""
+ validate_commit_identity(commit, name)
+ if (not isinstance(receipt, dict) or receipt.get("schema") != 2
+ or receipt.get("commit") != commit or receipt.get("name") != name
+ or "tag" in receipt):
+ raise ValueError("Commit handoff identity mismatch")
+ return validate_receipt_files(receipt)
+
+
+def _select_files(root: Path, includes: list[str]) -> dict[str, Path]:
+ """Shared stage selector: pattern matching, symlink/escape rejection."""
root = root.resolve()
selected = {}
for pattern in includes:
@@ -68,20 +84,48 @@ def stage(tag: str, commit: str, name: str, root: Path, includes: list[str]) ->
if file.is_symlink() or not file.resolve().is_relative_to(root):
raise ValueError("Release artifact path escapes its build root")
selected[file.relative_to(root).as_posix()] = file
- files = [{"path": relative_path(path), "size": file.stat().st_size, "sha256": r2.file_sha256(file)}
- for path, file in sorted(selected.items())]
- receipt = {"schema": 1, "tag": tag, "commit": commit, "name": name, "files": files}
- validate_receipt(receipt, tag, commit, name)
- for row in files:
- r2.put(tag=tag, key=row["path"], file=selected[row["path"]], immutable=True)
- # The receipt is the completion marker. An interrupted upload cannot publish it.
+ return selected
+
+
+def _receipt_file_rows(selected: dict[str, Path]) -> list[dict]:
+ return [{"path": r2.relative_artifact_path(path), "size": file.stat().st_size, "sha256": r2.file_sha256(file)}
+ for path, file in sorted(selected.items())]
+
+
+def _stage(receipt: dict, selected: dict[str, Path]) -> dict:
+ """Publish completion only after every immutable artifact upload succeeds."""
+ prefix = (r2.staging_key_for(receipt["tag"], "") if "tag" in receipt
+ else r2.commit_prefix_for(receipt["commit"]))
+ for row in receipt["files"]:
+ r2.put(tag=receipt.get("tag", ""), key=prefix + row["path"],
+ file=str(selected[row["path"]]), key_is_full=True, immutable=True)
with tempfile.TemporaryDirectory() as directory:
- file = Path(directory) / receipt_name(name)
+ file = Path(directory) / receipt_name(receipt["name"])
file.write_text(json.dumps(receipt, sort_keys=True, indent=2) + "\n", encoding="utf-8")
- r2.put(tag=tag, key=file.name, file=file, immutable=True)
+ r2.put(tag=receipt.get("tag", ""), key=prefix + file.name,
+ file=str(file), key_is_full=True, immutable=True)
return receipt
+def stage(tag: str, commit: str, name: str, root: Path, includes: list[str]) -> dict:
+ validate_identity(tag, commit, name)
+ selected = _select_files(root, includes)
+ receipt = {"schema": 1, "tag": tag, "commit": commit, "name": name,
+ "files": _receipt_file_rows(selected)}
+ validate_receipt(receipt, tag, commit, name)
+ return _stage(receipt, selected)
+
+
+def stage_commit_build(commit: str, name: str, root: Path, includes: list[str]) -> dict:
+ """Stage tagless artifacts. Identical retries pass; different bytes fail."""
+ validate_commit_identity(commit, name)
+ selected = _select_files(root, includes)
+ receipt = {"schema": 2, "commit": commit, "name": name,
+ "files": _receipt_file_rows(selected)}
+ validate_commit_receipt(receipt, commit, name)
+ return _stage(receipt, selected)
+
+
def read_receipt(tag: str, commit: str, name: str) -> dict:
validate_identity(tag, commit, name)
creds, base, bucket = r2.credentials()
@@ -94,28 +138,61 @@ def read_receipt(tag: str, commit: str, name: str) -> dict:
return receipt
+def read_commit_receipt(commit: str, name: str) -> dict:
+ validate_commit_identity(commit, name)
+ creds, base, bucket = r2.credentials()
+ key = r2.commit_key_for(commit, receipt_name(name))
+ try:
+ text = r2.get_object(creds, base, bucket, key, r2.amz_timestamp())
+ except r2.R2RequestError as err:
+ if err.status == 404:
+ raise MissingReceipt(f"Missing commit handoff: {name}") from err
+ raise
+ if text is None:
+ raise MissingReceipt(f"Missing commit handoff: {name}")
+ receipt = json.loads(text)
+ validate_commit_receipt(receipt, commit, name)
+ return receipt
+
+
def fetch(tag: str, commit: str, names: list[str], root: Path,
includes: list[str] | None = None) -> list[dict]:
receipts = [read_receipt(tag, commit, name) for name in names]
+ return _fetch_receipts(receipts, root, includes)
+
+
+def fetch_commit_build(commit: str, names: list[str], root: Path,
+ includes: list[str] | None = None) -> list[dict]:
+ """Fetch commit artifacts through the shared receipt-bound transport."""
+ receipts = [read_commit_receipt(commit, name) for name in names]
+ return _fetch_receipts(receipts, root, includes)
+
+
+def _fetch_receipts(receipts: list[dict], root: Path,
+ includes: list[str] | None = None) -> list[dict]:
+ """Download exact receipt-bound bytes before writing local receipt copies."""
root = root.resolve()
selected = {}
for receipt in receipts:
+ prefix = (r2.staging_key_for(receipt["tag"], "") if "tag" in receipt
+ else r2.commit_prefix_for(receipt["commit"]))
for row in receipt["files"]:
if includes and not any(fnmatch.fnmatchcase(row["path"], pattern) for pattern in includes):
continue
+ item = row, prefix + row["path"]
prior = selected.get(row["path"].casefold())
- if prior is not None and prior != row:
+ if prior is not None and prior != item:
raise ValueError("Conflicting release file receipts")
target = root / PurePosixPath(row["path"])
if not target.resolve().is_relative_to(root):
raise ValueError("Release artifact path escapes its download root")
- selected[row["path"].casefold()] = row
+ selected[row["path"].casefold()] = item
if not selected:
raise ValueError("No files selected from release handoff")
root.mkdir(parents=True, exist_ok=True)
creds, base, bucket = r2.credentials()
- for row in selected.values():
- r2.download_object(creds, base, bucket, r2.staging_key_for(tag, row["path"]),
+ for row, key in selected.values():
+ r2.download_object(creds, base, bucket, key,
root / row["path"], r2.amz_timestamp(),
expected_size=row["size"], expected_sha256=row["sha256"])
for receipt in receipts:
@@ -127,11 +204,28 @@ def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["stage", "fetch"])
parser.add_argument("--tag", default=os.environ.get("HERMES_PAYLOAD_TAG") or os.environ.get("RELEASE_TAG"), required=False)
- parser.add_argument("--commit", default=os.environ.get("GITHUB_SHA"))
+ parser.add_argument("--commit-build", default=os.environ.get("HERMES_BUILD_COMMIT"),
+ help="Commit-only mode: stage/fetch under releases/commit/<sha>/ "
+ "with schema-2 receipts (no tag; exact full SHA required)")
+ parser.add_argument("--commit", default=None,
+ help="Artifact commit. Must equal --commit-build when both are supplied.")
parser.add_argument("--name", action="append", required=True)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--include", action="append")
args = parser.parse_args(argv)
+ if args.commit_build:
+ if args.tag:
+ parser.error("--commit-build and --tag are mutually exclusive")
+ if args.commit and args.commit != args.commit_build:
+ parser.error("--commit must equal --commit-build (they name the same commit)")
+ commit = args.commit_build
+ if args.command == "stage":
+ if len(args.name) != 1 or not args.include:
+ parser.error("stage needs one name and at least one include pattern")
+ stage_commit_build(commit, args.name[0], args.root, args.include)
+ else:
+ fetch_commit_build(commit, args.name, args.root, args.include)
+ return
if args.command == "stage":
if len(args.name) != 1 or not args.include:
parser.error("stage needs one name and at least one include pattern")
diff --git a/scripts/releases/r2.py b/scripts/releases/r2.py
index bd5b3f4adf7..a6ea92a0be4 100644
--- a/scripts/releases/r2.py
+++ b/scripts/releases/r2.py
@@ -6,6 +6,7 @@ import json
from pathlib import Path
import hmac
import http.client
+import ntpath
import os
import re
import sys
@@ -401,6 +402,34 @@ def staging_key_for(tag: str, filename: str) -> str:
return f"releases/tag/{tag}/{filename}"
+_FULL_SHA_RE = re.compile(r"[a-f0-9]{40}")
+
+
+def is_full_sha(value: str) -> bool:
+ return bool(isinstance(value, str) and _FULL_SHA_RE.fullmatch(value))
+
+
+def relative_artifact_path(value: str) -> str:
+ """Validate the original path before any filesystem normalization."""
+ if (not isinstance(value, str) or not value or value.startswith("/")
+ or any(part in ("", ".", "..") for part in value.split("/"))
+ or any(c in value for c in "\\:%?#") or any(ord(c) < 32 for c in value)
+ or ntpath.isreserved(value)):
+ raise ValueError("Invalid release artifact path")
+ return value
+
+
+def commit_key_for(commit: str, filename: str) -> str:
+ """Keep nested artifacts inside the exact commit namespace."""
+ return commit_prefix_for(commit) + relative_artifact_path(filename)
+
+
+def commit_prefix_for(commit: str) -> str:
+ if not is_full_sha(commit):
+ raise ValueError("Commit builds require an exact full 40-character SHA")
+ return f"releases/commit/{commit}/"
+
+
def feed_dir_for(platform: str, channel: str) -> str:
return f"releases/{platform}/{channel}"
diff --git a/scripts/render-builds-table.py b/scripts/render-builds-table.py
index 9c9796ab909..a4a3086a7ea 100644
--- a/scripts/render-builds-table.py
+++ b/scripts/render-builds-table.py
@@ -35,6 +35,13 @@ import os
import re
import subprocess
import sys
+from pathlib import Path
+from urllib.parse import quote
+
+# Direct-script invocation starts with scripts/, not the repository root.
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from scripts.releases import handoff, r2 # noqa: E402
MARKER = "<!-- HERMES_BUILDS_TABLE -->"
END_MARKER = "<!-- /HERMES_BUILDS_TABLE -->"
@@ -129,23 +136,141 @@ def filter_names_for_version(names: list[str], version: str) -> list[str]:
return out
+# ---------------------------------------------------------------------------
+# Commit-build summary: every expected binary of a commit run, built or not.
+# ---------------------------------------------------------------------------
+
+# A row needs a unique receipt-listed artifact and its uploaded object.
+_COMMIT_EXPECTED = [
+ ("Windows x64 (MSIX)", "win32-x64",
+ r"^HermesBundled-[^-]+(?:-canary\.\d+)?-win-x64\.msix$"),
+ ("Windows ARM64 (MSIX)", "win32-arm64",
+ r"^HermesBundled-[^-]+(?:-canary\.\d+)?-win-arm64\.msix$"),
+ ("Windows x64 (Store MSIX)", "win32-x64",
+ r"^Store-HermesBundled-[^-]+(?:-canary\.\d+)?-win-x64\.msix$"),
+ ("Windows ARM64 (Store MSIX)", "win32-arm64",
+ r"^Store-HermesBundled-[^-]+(?:-canary\.\d+)?-win-arm64\.msix$"),
+ ("Windows universal bundle (MSIXBUNDLE)", "windows-universal",
+ r"^HermesBundled-[^-]+(?:-canary\.\d+)?-win\.msixbundle$"),
+ ("Windows universal Store bundle (MSIXBUNDLE)", "windows-universal",
+ r"^Store-HermesBundled-[^-]+(?:-canary\.\d+)?-win\.msixbundle$"),
+ ("macOS Apple Silicon (DMG)", "darwin-arm64",
+ r"^HermesBundled-[^-]+(?:-canary\.\d+)?-mac-arm64\.dmg$"),
+ ("macOS Intel (DMG)", "darwin-x64",
+ r"^HermesBundled-[^-]+(?:-canary\.\d+)?-mac-x64\.dmg$"),
+ ("macOS Apple Silicon (ZIP)", "darwin-arm64",
+ r"^HermesBundled-[^-]+(?:-canary\.\d+)?-mac-arm64\.zip$"),
+ ("macOS Intel (ZIP)", "darwin-x64",
+ r"^HermesBundled-[^-]+(?:-canary\.\d+)?-mac-x64\.zip$"),
+ ("Termux aarch64 (.deb)", "termux", r"^.*\.deb$"),
+]
+
+COMMIT_RECEIPT_NAMES = sorted({leg for _label, leg, _pattern in _COMMIT_EXPECTED})
+_COMMIT_JOBS = {
+ "win32-x64": "build-win32", "win32-arm64": "build-win32",
+ "darwin-x64": "build-darwin", "darwin-arm64": "build-darwin",
+ "windows-universal": "publish-win32-updater", "termux": "termux-deb",
+}
+
+
+def commit_expected_rows(names: list[str],
+ receipts: dict[str, dict | None]) -> list[dict]:
+ """Classify artifacts from validated receipts without trusting orphan objects."""
+ objects = set(names)
+ rows: list[dict] = []
+ for label, leg, pattern in _COMMIT_EXPECTED:
+ receipt = receipts.get(leg)
+ listed = [r2.commit_key_for(receipt["commit"], row["path"])
+ for row in receipt["files"]
+ if re.fullmatch(pattern, row["path"].rsplit("/", 1)[-1])] if receipt else []
+ if receipt is None:
+ state, key = "receipt-missing", None
+ elif not listed:
+ state, key = "receipt-omits", None
+ elif len(listed) > 1:
+ state, key = "ambiguous", None
+ elif listed[0] not in objects:
+ state, key = "object-missing", None
+ else:
+ state, key = "built", listed[0]
+ rows.append({"label": label, "leg": leg, "key": key, "state": state})
+ return rows
+
+
+def render_commit_summary(names: list[str], base_url: str, commit: str,
+ receipts: dict[str, dict | None],
+ failed_legs: list[str] | None = None) -> str:
+ """Render every expected product without reading or changing a release."""
+ r2.commit_prefix_for(commit)
+ for leg, receipt in receipts.items():
+ if receipt is not None:
+ handoff.validate_commit_receipt(receipt, commit, leg)
+ base = base_url.rstrip("/")
+ failed = set(failed_legs or [])
+ lines = [
+ f"## Commit build `{commit[:12]}`",
+ "",
+ "| Binary | Status | Download |",
+ "|---|---|---|",
+ ]
+ for row in commit_expected_rows(names, receipts):
+ label, key, state = row["label"], row["key"], row["state"]
+ if state == "built":
+ basename = key.rsplit("/", 1)[-1]
+ link = f"{base}/{quote(key, safe='/')}"
+ lines.append(f"| {label} | ✅ Built | [{basename}]({link}) |")
+ elif state == "receipt-missing":
+ related = failed.intersection({row["leg"], _COMMIT_JOBS[row["leg"]]})
+ blame = f"failed: {', '.join(sorted(related))}" if related \
+ else "leg incomplete or upload interrupted"
+ lines.append(f"| {label} | ❌ Not built ({blame}) | — |")
+ elif state == "object-missing":
+ lines.append(f"| {label} | ❌ Not built (receipt present but object missing) | — |")
+ elif state == "receipt-omits":
+ lines.append(f"| {label} | ❌ Not built (artifact absent from receipt) | — |")
+ else:
+ lines.append(f"| {label} | ❌ Not built (ambiguous: multiple objects match) | — |")
+ for label in ("Linux x64 (AppImage)", "Linux ARM64 (AppImage)"):
+ lines.append(f"| {label} | ❌ Not built (release leg disabled) | — |")
+ return "\n".join([*lines, ""])
+
+
+def read_commit_receipts(commit: str,
+ names: list[str] | None = None) -> dict[str, dict | None]:
+ """Missing receipts describe incomplete legs; corrupt receipts raise."""
+ out: dict[str, dict | None] = {}
+ for name in (names or COMMIT_RECEIPT_NAMES):
+ try:
+ out[name] = handoff.read_commit_receipt(commit, name)
+ except handoff.MissingReceipt:
+ out[name] = None
+ return out
+
+
+def failed_legs_from_release_needs(release_needs_json: str | None) -> list[str]:
+ """Read failure labels from the optional workflow result summary."""
+ if not release_needs_json:
+ return []
+ try:
+ needs = json.loads(release_needs_json)
+ except (ValueError, TypeError):
+ return []
+ if not isinstance(needs, dict):
+ return []
+ return sorted(name for name, info in needs.items()
+ if isinstance(info, dict) and info.get("result") not in ("success", "skipped"))
+
+
+def r2_object_names_under(prefix: str) -> list[str]:
+ return r2.list_objects(prefix=prefix)["keys"]
+
+
def r2_object_names(tag: str) -> list[str]:
"""Object keys in the R2 staging dir for `tag`, under releases/tag/<tag>/.
- Exact version match, never prefix: 'v0.28.0' must not pick up
- '0.28.0-canary.20260818...' objects (they live under their own tag
- directory, and the basename filter would reject them anyway). The list
- call shells out to scripts/releases/r2.py, which reads the R2 env vars
- and needs only Python (no application environment).
+ A tag prefix and exact version match exclude neighboring releases.
"""
- run = subprocess.run(
- [sys.executable, "-m", "scripts.releases.r2", "list", "--prefix", f"releases/tag/{tag}/"],
- capture_output=True, text=True, encoding="utf-8", errors="replace",
- )
- if run.returncode != 0:
- print(f"::error::r2 list failed: {run.stderr.strip() or run.stdout.strip()}")
- raise SystemExit(1)
- keys = [line.strip() for line in run.stdout.splitlines() if line.strip()]
+ keys = r2_object_names_under(f"releases/tag/{tag}/")
return filter_names_for_version(keys, tag.lstrip("v"))
@@ -159,7 +284,17 @@ def splice(body: str, block: str) -> str:
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--tag", required=True)
+ parser.add_argument("--tag", required=False, help="Release tag to render the release-body table for")
+ parser.add_argument("--summary-commit", default=None,
+ help="Commit-only mode: render the FULL expected-binary matrix for "
+ "releases/commit/<sha>/ into --summary-out. Never touches a "
+ "GitHub release; every expected binary gets a row, built or not")
+ parser.add_argument("--summary-out", default=None,
+ help="With --summary-commit: file the summary block is written to "
+ "(the workflow passes $GITHUB_STEP_SUMMARY)")
+ parser.add_argument("--summary-failed-legs", default="",
+ help="With --summary-commit: comma-separated failed job names, "
+ "blamed on the Not built rows")
parser.add_argument("--repo", default="NousResearch/hermes-agent")
parser.add_argument("--r2-base-url", default=os.environ.get("CLOUDFLARE_R2_PUBLIC_URL"),
help="Public base URL of the R2 bucket (default: $CLOUDFLARE_R2_PUBLIC_URL)")
@@ -170,6 +305,37 @@ def main() -> int:
"instead of the tables")
args = parser.parse_args()
+ if args.summary_commit and (args.tag or args.pending_run_url):
+ parser.error("--summary-commit cannot be combined with release-body arguments")
+
+ if args.summary_commit:
+
+ if not args.summary_out:
+ print("::error::--summary-out is required with --summary-commit")
+ return 1
+ if not args.r2_base_url:
+ print("::error::--r2-base-url (or CLOUDFLARE_R2_PUBLIC_URL) is required to render the summary")
+ return 1
+ commit = args.summary_commit
+ try:
+ prefix = r2.commit_prefix_for(commit)
+ except ValueError as err:
+ print(f"::error::{err}")
+ return 1
+ names = r2_object_names_under(prefix)
+ receipts = read_commit_receipts(commit)
+ failed_legs = (failed_legs_from_release_needs(os.environ.get("RELEASE_NEEDS"))
+ or [leg.strip() for leg in args.summary_failed_legs.split(",") if leg.strip()])
+ block = render_commit_summary(names, args.r2_base_url, commit, receipts, failed_legs)
+ with open(args.summary_out, "a", encoding="utf-8") as out:
+ out.write(block)
+ built = sum(1 for row in commit_expected_rows(names, receipts) if row["state"] == "built")
+ print(f"✓ Commit summary appended to {args.summary_out} ({built}/{len(_COMMIT_EXPECTED)} binaries built)")
+ return 0
+
+ if not args.tag:
+ parser.error("--tag is required (or use --summary-commit for a commit build summary)")
+
view = subprocess.run(
["gh", "release", "view", args.tag, "--repo", args.repo,
"--json", "body"],
diff --git a/tests/scripts/test_release_handoff.py b/tests/scripts/test_release_handoff.py
index 827fd2cc256..4991c0673a3 100644
--- a/tests/scripts/test_release_handoff.py
+++ b/tests/scripts/test_release_handoff.py
@@ -70,7 +70,8 @@ def test_failed_stage_never_publishes_a_receipt_or_channel(tmp_path, monkeypatch
real_put = r2.put
def fail_second(**kwargs):
- if kwargs["key"] == "two.msix":
+ # The transfer API receives the full key, not the basename.
+ if kwargs["key"] == f"releases/tag/{tag}/two.msix":
raise RuntimeError("upload interrupted")
real_put(**kwargs)
@@ -85,3 +86,53 @@ def test_failed_stage_never_publishes_a_receipt_or_channel(tmp_path, monkeypatch
with pytest.raises(ValueError, match="identity"):
handoff.stage("../bad", commit, "win32-x64", tmp_path, ["*.msix"])
assert r2_server.requests == []
+
+
[email protected]("commit_only", [False, True])
+def test_shared_receipt_files_download_once_and_conflicts_leave_targets_intact(tmp_path, r2_server, commit_only):
+ from scripts.releases import handoff
+
+ commit, tag = "a" * 40, "v1.2.3"
+ artifact = tmp_path / "shared.bin"
+ artifact.write_bytes(b"same shared bytes")
+ if commit_only:
+ stage = lambda name: handoff.stage_commit_build(commit, name, tmp_path, ["*.bin"])
+ fetch = lambda target: handoff.fetch_commit_build(commit, ["one", "two"], target)
+ prefix = r2.commit_prefix_for(commit)
+ else:
+ stage = lambda name: handoff.stage(tag, commit, name, tmp_path, ["*.bin"])
+ fetch = lambda target: handoff.fetch(tag, commit, ["one", "two"], target)
+ prefix = r2.staging_key_for(tag, "")
+ stage("one")
+ stage("two")
+ r2_server.requests.clear()
+ target = tmp_path / "download"
+ fetch(target)
+ assert (target / "shared.bin").read_bytes() == artifact.read_bytes()
+ gets = [url for method, url, _ in r2_server.requests if method == "GET"]
+ assert sum(url.endswith(prefix + "shared.bin") for url in gets) == 1
+
+ receipt_key = prefix + "handoff-two.json"
+ receipt = json.loads(r2_server.store[receipt_key][0])
+ receipt["files"][0]["sha256"] = "0" * 64
+ r2_server.store[receipt_key] = (json.dumps(receipt).encode(), '"changed"')
+ before = {file.name: file.read_bytes() for file in target.iterdir()}
+ with pytest.raises(ValueError, match="Conflicting"):
+ fetch(target)
+ assert {file.name: file.read_bytes() for file in target.iterdir()} == before
+
+
+def test_conflicting_bytes_at_the_transport_never_replace_the_object(tmp_path, r2_server):
+ """A conflicting immutable upload must preserve the existing object."""
+ from scripts.releases import handoff
+
+ tag, commit = "v1.2.3", "a" * 40
+ (tmp_path / "one.msix").write_bytes(b"first")
+ handoff.stage(tag, commit, "win32-x64", tmp_path, ["*.msix"])
+ key = f"releases/tag/{tag}/one.msix"
+ assert r2_server.store[key][0] == b"first"
+ handoff.stage(tag, commit, "win32-x64", tmp_path, ["*.msix"])
+ (tmp_path / "one.msix").write_bytes(b"conflicting")
+ with pytest.raises(Exception):
+ handoff.stage(tag, commit, "win32-x64", tmp_path, ["*.msix"])
+ assert r2_server.store[key][0] == b"first"
diff --git a/tests/scripts/test_release_handoff_commit.py b/tests/scripts/test_release_handoff_commit.py
new file mode 100644
index 00000000000..04e748ca245
--- /dev/null
+++ b/tests/scripts/test_release_handoff_commit.py
@@ -0,0 +1,328 @@
+"""Commit-only handoff receipts (schema 2) bind files to a bare commit."""
+import copy
+import json
+import os
+import unittest.mock as mock
+
+import pytest
+
+from scripts.releases import r2
+from tests.scripts.test_release_r2 import r2_server # noqa: F401
+
+
+COMMIT = "b" * 40
+
+
+def test_commit_key_namespace_never_overlaps_tag_or_channel_dirs():
+ assert r2.commit_key_for(COMMIT, "app.msix") == f"releases/commit/{COMMIT}/app.msix"
+ assert r2.commit_prefix_for(COMMIT) == f"releases/commit/{COMMIT}/"
+ for bad in ("abc", COMMIT[:39], "g" * 40, "", None, " " * 40):
+ with pytest.raises(ValueError):
+ r2.commit_key_for(bad, "app.msix")
+ # Traversal / absolute / backslash paths stay forbidden...
+ for bad_name in ("../outside", "a/../../b", "/abs.msix", "C:\\x.msix", "",
+ "a//b", "./a", "C:/b", "a%2fb", "a?b", "a#b", "NUL", "a/../b"):
+ with pytest.raises(ValueError):
+ r2.commit_key_for(COMMIT, bad_name)
+ # ...but REAL nested artifact paths (the Termux receipt shape) fetch.
+ assert (r2.commit_key_for(COMMIT, "deb/pool/hermes_0.28.0_aarch64.deb")
+ == f"releases/commit/{COMMIT}/deb/pool/hermes_0.28.0_aarch64.deb")
+ key = r2.commit_key_for(COMMIT, "app.msix")
+ assert not key.startswith("releases/tag/")
+ assert not key.startswith(("releases/win32/", "releases/darwin/", "releases/termux/"))
+
+
+def test_commit_stage_fetch_roundtrip_is_receipt_last_and_tag_free(tmp_path, r2_server):
+ from scripts.releases import handoff
+
+ root = tmp_path / "built"
+ root.mkdir()
+ data = b"commit build transport fixture\n" * 50000
+ (root / "HermesBundled-0.28.0-win-x64.msix").write_bytes(data)
+ # No --commit flag: the commit-build identity comes ONLY from
+ # --commit-build. --commit never defaults from ambient $GITHUB_SHA.
+ handoff.main(["stage", "--commit-build", COMMIT, "--name", "win32-x64",
+ "--root", str(root), "--include", "*.msix"])
+ receipt_key = f"releases/commit/{COMMIT}/handoff-win32-x64.json"
+ receipt = json.loads(r2_server.store[receipt_key][0])
+ assert receipt["schema"] == 2 and receipt["commit"] == COMMIT
+ assert "tag" not in receipt
+ assert receipt["files"][0]["sha256"] == r2.file_sha256(root / "HermesBundled-0.28.0-win-x64.msix")
+ assert set(r2_server.store) <= {f"releases/commit/{COMMIT}/{name}" for name in
+ ("HermesBundled-0.28.0-win-x64.msix", "handoff-win32-x64.json")}
+ puts = [path for method, path, _ in r2_server.requests if method == "PUT"]
+ assert puts[-1].endswith(receipt_key), "receipt must be the completion marker"
+ assert all(headers.get("If-None-Match") == "*"
+ for method, _, headers in r2_server.requests if method == "PUT")
+
+ downloaded = tmp_path / "downloaded"
+ handoff.main(["fetch", "--commit-build", COMMIT,
+ "--name", "win32-x64", "--root", str(downloaded)])
+ assert (downloaded / "HermesBundled-0.28.0-win-x64.msix").read_bytes() == data
+
+ # Same-SHA retry with identical bytes succeeds (verified-conflict path).
+ handoff.stage_commit_build(COMMIT, "win32-x64", root, ["*.msix"])
+ # Conflicting different bytes must fail, never delete the existing object.
+ (root / "HermesBundled-0.28.0-win-x64.msix").write_bytes(b"different")
+ with pytest.raises(Exception):
+ handoff.stage_commit_build(COMMIT, "win32-x64", root, ["*.msix"])
+ assert r2_server.store[f"releases/commit/{COMMIT}/HermesBundled-0.28.0-win-x64.msix"][0] == data
+
+
+def test_commit_stage_fetch_nested_paths_roundtrip(tmp_path, r2_server):
+ """The Termux leg stages deb/*.deb (nested receipt paths). The fetch
+ must rebuild the same nested layout — the old commit_key_for forbade
+ any slash, so the workflow's own stage shape was unfetchable."""
+ from scripts.releases import handoff
+
+ root = tmp_path / "termux-build"
+ (root / "deb" / "pool").mkdir(parents=True)
+ deb = root / "deb" / "pool" / "hermes_0.28.0_aarch64.deb"
+ deb.write_bytes(b"!<arch>\ndeb-bytes")
+ handoff.main(["stage", "--commit-build", COMMIT, "--name", "termux",
+ "--root", str(root), "--include", "deb/**/*.deb"])
+ receipt = json.loads(r2_server.store[f"releases/commit/{COMMIT}/handoff-termux.json"][0])
+ assert receipt["files"][0]["path"] == "deb/pool/hermes_0.28.0_aarch64.deb"
+
+ downloaded = tmp_path / "out"
+ handoff.main(["fetch", "--commit-build", COMMIT, "--name", "termux", "--root", str(downloaded)])
+ assert (downloaded / "deb" / "pool" / "hermes_0.28.0_aarch64.deb").read_bytes() == b"!<arch>\ndeb-bytes"
+
+
+def test_commit_cli_rejects_conflicting_commit_value(tmp_path, r2_server):
+ """--commit is a SEPARATE explicit flag: it never defaults from ambient
+ $GITHUB_SHA (a feature-branch run must not inherit a conflicting SHA
+ that would parser.error against --commit-build), and when passed it
+ must EQUAL --commit-build."""
+ from scripts.releases import handoff
+
+ root = tmp_path / "built"
+ root.mkdir()
+ (root / "a.msix").write_bytes(b"x")
+ # Disagreeing explicit flags are a hard CLI error, never silently
+ # resolved (the old draft accepted and dropped the override).
+ with pytest.raises(SystemExit):
+ handoff.main(["stage", "--commit-build", COMMIT, "--commit", "c" * 40,
+ "--name", "win32-x64", "--root", str(root), "--include", "*.msix"])
+ # Without --commit, --commit-build alone stages fine even though the
+ # inherited environment carries an unrelated GITHUB_SHA (the old draft
+ # would parser.error here — every commit builder exports GITHUB_SHA).
+ with mock.patch.dict(os.environ, {"GITHUB_SHA": "c" * 40}):
+ handoff.main(["stage", "--commit-build", COMMIT,
+ "--name", "win32-x64", "--root", str(root), "--include", "*.msix"])
+ # Equal values are accepted (they name the same commit).
+ handoff.main(["stage", "--commit-build", COMMIT, "--commit", COMMIT,
+ "--name", "win32-x64", "--root", str(root), "--include", "*.msix"])
+
+
+def test_commit_and_tag_namespaces_stay_isolated(tmp_path, r2_server):
+ from scripts.releases import handoff
+
+ # A tag staging and a commit staging of the same artifact name must
+ # land in disjoint prefixes — neither can read or overwrite the other.
+ root = tmp_path / "built"
+ root.mkdir()
+ (root / "a.msix").write_bytes(b"commit bytes")
+ handoff.stage_commit_build(COMMIT, "win32-x64", root, ["*.msix"])
+ tag_root = tmp_path / "tagged"
+ tag_root.mkdir()
+ (tag_root / "a.msix").write_bytes(b"tag bytes")
+ handoff.stage("v0.28.0", COMMIT, "win32-x64", tag_root, ["*.msix"])
+ assert r2_server.store[f"releases/commit/{COMMIT}/a.msix"][0] == b"commit bytes"
+ assert r2_server.store["releases/tag/v0.28.0/a.msix"][0] == b"tag bytes"
+ # The schema-1 tag receipt still carries tag+commit; the schema-2
+ # commit receipt has no tag anywhere.
+ tag_receipt = json.loads(r2_server.store["releases/tag/v0.28.0/handoff-win32-x64.json"][0])
+ assert tag_receipt["schema"] == 1 and tag_receipt["tag"] == "v0.28.0" and tag_receipt["commit"] == COMMIT
+ commit_receipt = json.loads(r2_server.store[f"releases/commit/{COMMIT}/handoff-win32-x64.json"][0])
+ assert commit_receipt["schema"] == 2 and "tag" not in commit_receipt
+
+
+def test_interrupted_upload_leaves_no_commit_receipt(tmp_path, r2_server):
+ """Receipt-last means an interrupted build publishes NO receipt, so the
+ summary can never mistake a half-staged leg for a completed one."""
+ from scripts.releases import handoff
+
+ root = tmp_path / "built"
+ root.mkdir()
+ (root / "a.msix").write_bytes(b"x")
+ (root / "b.bin").write_bytes(b"y")
+ # Second include pattern's upload dies mid-leg: the receipt PUT (last)
+ # never happens, only artifacts exist.
+ real_put = r2.put
+ calls = {"n": 0}
+
+ def flaky_put(**kwargs):
+ calls["n"] += 1
+ if "b.bin" in kwargs["key"]:
+ raise OSError("connection reset mid-upload")
+ return real_put(**kwargs)
+
+ with mock.patch.object(r2, "put", side_effect=lambda **kw: flaky_put(**kw)):
+ with pytest.raises(OSError):
+ handoff.stage_commit_build(COMMIT, "win32-x64", root, ["*.msix", "*.bin"])
+ assert f"releases/commit/{COMMIT}/a.msix" in r2_server.store
+ assert f"releases/commit/{COMMIT}/b.bin" not in r2_server.store
+ assert f"releases/commit/{COMMIT}/handoff-win32-x64.json" not in r2_server.store
+
+
+def test_commit_receipt_identity_rejects_bad_sha_tag_sneak_and_traversal(tmp_path, r2_server):
+ from scripts.releases import handoff
+
+ for bad in ("abc", COMMIT[:39], "G" * 40, ""):
+ with pytest.raises(ValueError):
+ handoff.validate_commit_identity(bad, "win32-x64")
+ with pytest.raises(ValueError):
+ handoff.validate_commit_identity(COMMIT, "Bad Name")
+ receipt = {"schema": 2, "commit": COMMIT, "name": "win32-x64",
+ "files": [{"path": "a.msix", "size": 1, "sha256": "0" * 64}]}
+ with pytest.raises(ValueError, match="identity mismatch"):
+ handoff.validate_commit_receipt({**receipt, "tag": "v1.2.3"}, COMMIT, "win32-x64")
+ with pytest.raises(ValueError, match="identity mismatch"):
+ handoff.validate_commit_receipt({**receipt, "schema": 1}, COMMIT, "win32-x64")
+ bad_path = copy.deepcopy(receipt)
+ bad_path["files"][0]["path"] = "../outside"
+ with pytest.raises(ValueError, match="path"):
+ handoff.validate_commit_receipt(bad_path, COMMIT, "win32-x64")
+
+ # A fetch against a mismatched commit is refused.
+ root = tmp_path / "built"
+ root.mkdir()
+ (root / "a.msix").write_bytes(b"x")
+ handoff.stage_commit_build(COMMIT, "win32-x64", root, ["*.msix"])
+ with pytest.raises(handoff.MissingReceipt):
+ handoff.read_commit_receipt("c" * 40, "win32-x64")
+
+
+def test_corrupt_commit_receipt_is_not_reported_as_missing(tmp_path, r2_server):
+ """A present-but-invalid receipt is a distinct failure from a MISSING
+ one: the summary renderer must crash loudly on a corrupt receipt, not
+ render the leg as an ordinary "leg incomplete" row."""
+ from scripts.releases import handoff
+
+ root = tmp_path / "built"
+ root.mkdir()
+ (root / "a.msix").write_bytes(b"x")
+ handoff.stage_commit_build(COMMIT, "win32-x64", root, ["*.msix"])
+
+ # Corrupt the stored receipt (wrong schema: a validation failure).
+ receipt_key = f"releases/commit/{COMMIT}/handoff-win32-x64.json"
+ original = json.loads(r2_server.store[receipt_key][0])
+ corrupt = copy.deepcopy(original)
+ corrupt["schema"] = 1
+ r2_server.store[receipt_key] = (json.dumps(corrupt).encode(), '"e"')
+ with pytest.raises(ValueError) as excinfo:
+ handoff.read_commit_receipt(COMMIT, "win32-x64")
+ assert not isinstance(excinfo.value, handoff.MissingReceipt)
+
+ # A mismatched-commit receipt is likewise NOT a MissingReceipt.
+ corrupt2 = copy.deepcopy(original)
+ corrupt2["commit"] = "c" * 40
+ r2_server.store[receipt_key] = (json.dumps(corrupt2).encode(), '"e"')
+ with pytest.raises(ValueError) as excinfo2:
+ handoff.read_commit_receipt(COMMIT, "win32-x64")
+ assert not isinstance(excinfo2.value, handoff.MissingReceipt)
+
+ # Restore; then a genuinely absent receipt raises MissingReceipt.
+ r2_server.store[receipt_key] = (json.dumps(original).encode(), '"e"')
+ with pytest.raises(handoff.MissingReceipt):
+ handoff.read_commit_receipt("d" * 40, "win32-x64")
+
+
+def test_real_cli_stage_and_summary_run_as_subprocesses(tmp_path):
+ """Run the actual CLI parsers and signed transport against loopback HTTP."""
+ import re
+ import subprocess
+ import sys
+ import threading
+ from http.server import ThreadingHTTPServer
+ from pathlib import Path
+ from urllib.request import urlopen
+
+ repo = Path(__file__).resolve().parents[2]
+ from tests.scripts.test_release_r2 import _R2StubHandler
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _R2StubHandler)
+ server.store = {}
+ server.requests = []
+
+ def listing_xml():
+ parts = ["<?xml version='1.0'?><ListBucketResult><IsTruncated>false</IsTruncated>"]
+ for key, (body, _etag) in server.store.items():
+ parts.append(f"<Contents><Key>{key}</Key><LastModified>2026-08-01T00:00:00Z</LastModified></Contents>")
+ parts.append("</ListBucketResult>")
+ return "".join(parts)
+
+ server.listing_xml = listing_xml
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ env = dict(os.environ)
+ env.pop("PYTHONPATH", None)
+ env.pop("PYTHONHOME", None)
+ env.update({
+ "CLOUDFLARE_R2_ACCOUNT_ID": "loopback",
+ "CLOUDFLARE_R2_ACCESS_KEY_ID": "test-inert",
+ "CLOUDFLARE_R2_SECRET_ACCESS_KEY": "test-inert",
+ "CLOUDFLARE_R2_BUCKET": "hermes-releases",
+ "GITHUB_SHA": "c" * 40, # ambient, unrelated — must be ignored
+ })
+ base = f"http://127.0.0.1:{server.server_port}"
+ driver = tmp_path / "cli_driver.py"
+ driver.write_text(
+ "import runpy, sys\n"
+ f"sys.path.insert(0, {str(repo)!r})\n"
+ "from scripts.releases import r2\n"
+ f"r2.s3_endpoint = lambda account: {base!r}\n"
+ "mode = sys.argv.pop(1)\n"
+ "if mode == 'handoff':\n"
+ " runpy.run_module('scripts.releases.handoff', run_name='__main__')\n"
+ "else:\n"
+ f" runpy.run_path({str(repo / 'scripts/render-builds-table.py')!r}, run_name='__main__')\n",
+ encoding="utf-8",
+ )
+ build_root = tmp_path / "built"
+ build_root.mkdir()
+ (build_root / "HermesBundled-0.28.0-win-x64.msix").write_bytes(b"cli-bytes")
+
+ stage = subprocess.run(
+ [sys.executable, str(driver), "handoff", "stage",
+ "--commit-build", COMMIT, "--name", "win32-x64",
+ "--root", str(build_root), "--include", "*.msix"],
+ cwd=tmp_path, env=env, capture_output=True, text=True, encoding="utf-8", timeout=60)
+ assert stage.returncode == 0, stage.stdout + stage.stderr
+
+ summary = tmp_path / "summary.md"
+ render = subprocess.run(
+ [sys.executable, str(driver), "summary",
+ "--summary-commit", COMMIT, "--summary-out", str(summary),
+ "--r2-base-url", base + "/hermes-releases"],
+ cwd=tmp_path, env=env, capture_output=True, text=True, encoding="utf-8", timeout=60)
+ assert render.returncode == 0, render.stdout + render.stderr
+ text = summary.read_text(encoding="utf-8")
+ # The staged leg is receipt+object bound -> exactly one ✅ row with
+ # a link; every other leg renders an explicit ❌.
+ built = [line for line in text.splitlines() if "✅ Built" in line]
+ assert len(built) == 1, text
+ assert "HermesBundled-0.28.0-win-x64.msix" in built[0]
+ url = re.search(r"\]\((http[^)]+)\)", built[0]).group(1)
+ assert f"/releases/commit/{COMMIT}/" in url
+ with urlopen(url, timeout=5) as response:
+ assert response.read() == b"cli-bytes"
+ assert "Windows universal Store bundle (MSIXBUNDLE)" in text
+ assert "Linux x64" in text and "Linux ARM64" in text
+ assert all(key.startswith(f"releases/commit/{COMMIT}/") for key in server.store)
+
+ receipt_key = f"releases/commit/{COMMIT}/handoff-win32-x64.json"
+ server.store[receipt_key] = (b"not-json", '"invalid"')
+ failed = subprocess.run(
+ [sys.executable, str(driver), "summary", "--summary-commit", COMMIT,
+ "--summary-out", str(summary), "--r2-base-url", base + "/hermes-releases"],
+ cwd=tmp_path, env=env, capture_output=True, text=True, encoding="utf-8", timeout=60,
+ )
+ assert failed.returncode != 0
+ assert summary.read_text(encoding="utf-8") == text
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
diff --git a/tests/scripts/test_render_builds_table_commit.py b/tests/scripts/test_render_builds_table_commit.py
new file mode 100644
index 00000000000..f4acd43b438
--- /dev/null
+++ b/tests/scripts/test_render_builds_table_commit.py
@@ -0,0 +1,223 @@
+"""Commit-mode summary renderer: the receipt-bound expected-binary matrix.
+
+The commit summary is a SEPARATE sink from the release-body tables: it
+never reads or edits a GitHub release, and every expected binary gets a
+row — Built (receipt + object both present, with a link) or Not built —
+so a skipped or interrupted leg can never be a silent omission or a
+forged success.
+"""
+from __future__ import annotations
+
+import importlib.util
+import json
+from pathlib import Path
+
+import pytest
+
+_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "render-builds-table.py"
+_SPEC = importlib.util.spec_from_file_location("render_builds_table", _SCRIPT)
+assert _SPEC and _SPEC.loader
+rbt = importlib.util.module_from_spec(_SPEC)
+_SPEC.loader.exec_module(rbt)
+
+COMMIT = "a" * 40
+BASE = "https://cdn.example.com"
+
+
+def _leg_for(basename: str) -> str:
+ """The receipt name whose regex matches this artifact basename."""
+ import re
+ for _label, leg, pattern in rbt._COMMIT_EXPECTED:
+ if re.match(pattern, basename):
+ return leg
+ raise AssertionError(f"no expected row matches {basename!r}")
+
+
+# Every produced binary of a fully green commit run (Termux's .deb is a
+# nested deb/ path — the workflow stages it under deb/pool/).
+_ALL_BASENAMES = [
+ "HermesBundled-0.28.0-win-x64.msix",
+ "HermesBundled-0.28.0-win-arm64.msix",
+ "Store-HermesBundled-0.28.0-win-x64.msix",
+ "Store-HermesBundled-0.28.0-win-arm64.msix",
+ "HermesBundled-0.28.0-win.msixbundle",
+ "Store-HermesBundled-0.28.0.0-win.msixbundle",
+ "HermesBundled-0.28.0-mac-arm64.dmg",
+ "HermesBundled-0.28.0-mac-x64.dmg",
+ "HermesBundled-0.28.0-mac-arm64.zip",
+ "HermesBundled-0.28.0-mac-x64.zip",
+ "deb/pool/hermes-agent_0.28.0_aarch64.deb",
+]
+
+
+def _receipts_all_built() -> dict[str, dict | None]:
+ """Validated receipts: each leg lists exactly the artifact basenames
+ the matrix expects from it (the real staged shape)."""
+ receipts: dict[str, dict | None] = {name: None for name in rbt.COMMIT_RECEIPT_NAMES}
+ for basename in _ALL_BASENAMES:
+ leg = _leg_for(basename.rsplit("/", 1)[-1])
+ receipt = receipts[leg] or {"schema": 2, "commit": COMMIT, "name": leg, "files": []}
+ receipt["files"].append({"path": basename, "size": 1, "sha256": "0" * 64})
+ receipts[leg] = receipt
+ return receipts
+
+
+def _names(*basenames: str) -> list[str]:
+ return [f"releases/commit/{COMMIT}/{name}" for name in basenames]
+
+
+def _all_built_names() -> list[str]:
+ return _names(*_ALL_BASENAMES)
+
+
+def test_every_expected_binary_gets_a_row_built_or_not():
+ receipts = _receipts_all_built()
+ rows = rbt.commit_expected_rows(_all_built_names(), receipts)
+ assert len(rows) == len(rbt._COMMIT_EXPECTED)
+ for row in rows:
+ assert row["state"] == "built", row
+ summary = rbt.render_commit_summary(_all_built_names(), BASE, COMMIT, receipts)
+ assert summary.count("✅ Built") == len(rbt._COMMIT_EXPECTED)
+ # zip/Termux/Store rows exist in the COMMIT summary (the release-body
+ # table hides zips on purpose; the commit summary shows every binary).
+ assert any("ZIP" in row["label"] for row in rows)
+ assert any("Termux" in row["label"] for row in rows)
+ assert any("Store MSIX" in row["label"] for row in rows)
+ assert any("MSIXBUNDLE" in row["label"] for row in rows)
+ # The universal Store MSIXBUNDLE is commit-native now and links correctly.
+ bundle = next(row for row in rows if "MSIXBUNDLE" in row["label"])
+ assert bundle["key"].endswith(".msixbundle")
+
+
+def test_missing_binaries_are_explicit_rows_never_links():
+ receipts = _receipts_all_built()
+ names = _names("HermesBundled-0.28.0-win-x64.msix")
+ summary = rbt.render_commit_summary(names, BASE, COMMIT, receipts)
+ built = sum(1 for line in summary.splitlines() if "✅ Built" in line)
+ missing = sum(1 for line in summary.splitlines()
+ if "❌ Not built" in line and "release leg disabled" not in line)
+ assert built == 1
+ assert missing == len(rbt._COMMIT_EXPECTED) - built
+ # No link for an object that does not exist.
+ assert "win-arm64.msix)" not in summary
+ # Failed legs are blamed by name on the RECEIPT-missing rows; without
+ # blame the row says incomplete.
+ darwin_down = dict(receipts)
+ darwin_down["darwin-arm64"] = None
+ blamed = rbt.render_commit_summary(names, BASE, COMMIT, darwin_down, failed_legs=["build-darwin"])
+ assert "failed: build-darwin" in blamed
+ assert "Not built (leg incomplete or upload interrupted)" in rbt.render_commit_summary(names, BASE, COMMIT, darwin_down)
+
+
+def test_object_without_completion_receipt_never_renders_built():
+ """The old draft trusted raw object names: an interrupted upload that
+ left artifacts but no receipt looked ✅ Built. Now the receipt is the
+ completion marker."""
+ receipts = _receipts_all_built()
+ names = _all_built_names() # every object present...
+ for leg in ("win32-x64", "termux"):
+ receipts[leg] = None # ...two legs' receipts absent
+ summary = rbt.render_commit_summary(names, BASE, COMMIT, receipts)
+ for row in rbt.commit_expected_rows(names, receipts):
+ if row["leg"] in ("win32-x64", "termux"):
+ assert row["state"] != "built"
+ assert f"| {row['label']} | ✅ Built |" not in summary
+ else:
+ assert row["state"] == "built"
+
+
+def test_orphan_object_with_unrelated_valid_receipt_never_renders_built():
+ """An object matching a row's shape, staged under a leg whose VALID
+ receipt covers only unrelated files, is NOT evidence that the row's
+ binary was built. The old draft accepted ANY receipt object for the
+ leg; rows now bind to the receipt's own file paths."""
+ receipts = _receipts_all_built()
+ # win32-x64's receipt is valid but lists a DIFFERENT file.
+ receipts["win32-x64"] = {"schema": 2, "commit": COMMIT, "name": "win32-x64",
+ "files": [{"path": "metadata-windows-x64.json",
+ "size": 1, "sha256": "0" * 64}]}
+ names = _all_built_names() # the orphan win-x64 msix object exists
+ rows = rbt.commit_expected_rows(names, receipts)
+ x64 = next(row for row in rows if row["label"] == "Windows x64 (MSIX)")
+ assert x64["state"] != "built"
+ assert x64["key"] is None
+ summary = rbt.render_commit_summary(names, BASE, COMMIT, receipts)
+ assert "| Windows x64 (MSIX) | ✅ Built |" not in summary
+
+
+def test_receipt_without_object_is_reported_not_built():
+ receipts = _receipts_all_built()
+ summary = rbt.render_commit_summary([], BASE, COMMIT, receipts)
+ assert "Not built (receipt present but object missing)" in summary
+ assert "✅ Built" not in summary
+
+
+def test_ambiguous_or_extra_objects_never_render_a_link():
+ """Two objects that BOTH match a row's shape AND are listed by the
+ leg's receipt are genuinely ambiguous — no link is rendered. An extra
+ object the receipt does NOT list cannot poison a row whose own
+ receipt-listed object is unique (it is foreign to the binding)."""
+ receipts = _receipts_all_built()
+ # List both versions in win32-x64's receipt (a torn staging would
+ # leave exactly this shape behind two shape-matching objects).
+ receipts["win32-x64"]["files"].append(
+ {"path": "HermesBundled-0.28.1-win-x64.msix", "size": 1, "sha256": "0" * 64})
+ names = _names(
+ "HermesBundled-0.28.0-win-x64.msix",
+ "HermesBundled-0.28.1-win-x64.msix",
+ )
+ rows = rbt.commit_expected_rows(names, receipts)
+ x64 = next(row for row in rows if row["label"] == "Windows x64 (MSIX)")
+ assert x64["state"] == "ambiguous" and x64["key"] is None
+
+ # The extra 0.28.1 object without a receipt listing is NOT ambiguous:
+ # the receipt's own 0.28.0 binding stays built.
+ plain = _receipts_all_built()
+ rows = rbt.commit_expected_rows(
+ _names("HermesBundled-0.28.0-win-x64.msix",
+ "HermesBundled-0.28.1-win-x64.msix"), plain)
+ x64 = next(row for row in rows if row["label"] == "Windows x64 (MSIX)")
+ assert x64["state"] == "built"
+ assert x64["key"].endswith("HermesBundled-0.28.0-win-x64.msix")
+
+
+def test_failed_legs_from_release_needs_seam():
+ needs = json.dumps({
+ "build-win32": {"result": "success"},
+ "build-darwin": {"result": "failure"},
+ "termux-deb": {"result": "skipped"},
+ "build-linux": {"result": "failure"},
+ })
+ assert rbt.failed_legs_from_release_needs(needs) == ["build-darwin", "build-linux"]
+ assert rbt.failed_legs_from_release_needs(None) == []
+ assert rbt.failed_legs_from_release_needs("") == []
+ assert rbt.failed_legs_from_release_needs("not json") == []
+
+
+def test_summary_uses_exact_nested_keys_and_lists_both_universal_bundles():
+ from scripts.releases import handoff
+
+ paths = {
+ "windows-universal": [
+ "HermesBundled-0.28.0.0-win.msixbundle",
+ "Store-HermesBundled-0.28.0.0-win.msixbundle",
+ ],
+ "termux": ["deb/pool build/hermes-agent_0.28.0_aarch64.deb"],
+ }
+ receipts = {
+ leg: {"schema": 2, "commit": COMMIT, "name": leg,
+ "files": [{"path": path, "size": 1, "sha256": "0" * 64} for path in files]}
+ for leg, files in paths.items()
+ }
+ for leg, receipt in receipts.items():
+ handoff.validate_commit_receipt(receipt, COMMIT, leg)
+ names = _names(*(path for files in paths.values() for path in files))
+ summary = rbt.render_commit_summary(names, BASE + "/downloads", COMMIT, receipts)
+ from urllib.parse import quote
+
+ for key in names:
+ assert f"]({BASE}/downloads/{quote(key, safe='/')})" in summary
+ built = [line for line in summary.splitlines() if "✅ Built" in line]
+ assert len(built) == len(names)
+ assert any("Store" in line and "MSIXBUNDLE" in line for line in built)
+ assert "Linux x64" in summary and "Linux ARM64" in summary