Files
hermes-agent/scripts/releases/linux.py
BearHuddleston e3164075e9 refactor(releases): share the Linux identity and smoke checks with admission
record_evidence's _arch_evidence_reasons was a copy of the commit, tag
and per-arch smoke checks in admit_publication. A rule change would have
needed the same edit in both places. admit_publication now starts from
the helper and adds only its ChannelAuthority checks, and the helper
moves above it.

The only observable change is reason order: authority refusals now come
after the evidence refusals. Nothing reads that order. The 92 tests in
test_release_linux.py and test_release_sequencer.py pass on the previous
head and on this one. Dropping the helper call from admit_publication
fails 9 of them.

Reported by Greptile on #161406.
2026-11-29 01:31:39 -06:00

791 lines
29 KiB
Python

"""Linux AppImage electron-updater feed planning, admission, and R2 publication.
Mirrors ``scripts/releases/darwin.py`` for Linux AppImages while enforcing
two-architecture all-or-nothing publication admission and exact channel
publication authority (``publish-canary`` for canary; verified ordered
``scripts/releases/sequencer.py`` promotion for stable).
"""
from __future__ import annotations
import argparse
import base64
import binascii
from collections.abc import Mapping
from dataclasses import dataclass
import json
import os
from pathlib import Path
import re
import tempfile
from typing import Any, Literal
import hermes_yaml as yaml
from hermes_cli.update_channel import is_canary_tag, release_version
from scripts.releases import handoff, r2
from scripts.releases.semver import compare as semver_compare, is_valid_version
ARCHES: tuple[Literal["x64", "arm64"], ...] = ("x64", "arm64")
APPIMAGE_ARCH: dict[str, str] = {"x64": "x86_64", "arm64": "arm64"}
EVIDENCE_FILENAME = "linux-evidence.json"
_SHA256_OR_COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
_CANARY_RE = re.compile(r"\+canary\.(\d{8}T\d{6}Z)$")
@dataclass(frozen=True)
class ArchEvidence:
"""Verified per-architecture diagnostic build + smoke outcome for one claim."""
arch: Literal["x64", "arm64"]
claim_tag: str
commit: str
staged: bool
smoke_passed: bool
@dataclass(frozen=True)
class ChannelAuthority:
"""Verified downstream publication authority for a target channel.
Canary feeds require ``publish_canary_succeeded`` (``stable-release.yml``
``publish-canary``). Stable feeds require ``sequencer_promoted`` — positive
proof that ``scripts/releases/sequencer.py`` actually promoted this exact
claim and commit, never ``publish-bundles`` / ``publication`` alone and
never a no-op sequencer exit.
"""
channel: Literal["canary", "stable"]
claim_tag: str
commit: str
publish_canary_succeeded: bool = False
sequencer_promoted: bool = False
abandoned: bool = False
@dataclass(frozen=True)
class AdmissionResult:
"""Result of the all-or-nothing Linux feed publication admission gate."""
admitted: bool
reasons: tuple[str, ...]
def linux_feed_spec(channel: str, arch: str) -> dict[str, Any]:
"""Feed directory and filename contract (parity with apps/desktop/update-feed.cjs)."""
if channel not in {"canary", "stable"}:
raise ValueError(f"Unsupported Linux feed channel: {channel!r}")
if arch not in APPIMAGE_ARCH:
raise ValueError(f"Unsupported Linux architecture: {arch!r}")
suffix = "" if arch == "x64" else f"-{arch}"
directory = f"releases/linux/{channel}"
file_name = f"{channel}-linux{suffix}.yml"
return {
"directory": directory,
"channel": channel,
"arch": arch,
"fileName": file_name,
"key": f"{directory}/{file_name}",
"allowPrerelease": channel != "stable",
}
def is_linux_feed_key(key: str) -> bool:
"""Return True for canonical Linux channel updater feed keys under releases/linux/."""
return key.startswith("releases/linux/") and key.endswith(("-linux.yml", "-linux-arm64.yml"))
def _is_valid_sha512(value: Any) -> bool:
if not isinstance(value, str) or not value:
return False
try:
raw = base64.b64decode(value, validate=True)
except (ValueError, binascii.Error):
return False
return len(raw) == 64 and base64.b64encode(raw).decode("ascii") == value
def _is_positive_int(value: Any) -> bool:
return isinstance(value, int) and not isinstance(value, bool) and value > 0
def _validate_feed_entry(entry: Any) -> dict[str, Any]:
if not isinstance(entry, dict):
raise ValueError("Invalid Linux feed: file entry must be a mapping")
url = entry.get("url")
if not isinstance(url, str) or not url:
raise ValueError("Invalid Linux feed: file entry missing url")
if not _is_valid_sha512(entry.get("sha512")):
raise ValueError("Invalid Linux feed: file entry has invalid sha512")
if not _is_positive_int(entry.get("size")):
raise ValueError("Invalid Linux feed: file entry has invalid size")
result: dict[str, Any] = {
"url": url,
"sha512": entry["sha512"],
"size": entry["size"],
}
if "blockMapSize" in entry:
if not _is_positive_int(entry["blockMapSize"]):
raise ValueError("Invalid Linux feed: invalid blockMapSize")
result["blockMapSize"] = entry["blockMapSize"]
return result
def parse_linux_feed(text: str) -> dict[str, Any]:
"""Parse and validate an electron-builder Linux YAML feed."""
if not isinstance(text, str) or not text.strip():
raise ValueError("Invalid Linux feed: empty document")
doc = yaml.safe_load(text)
if not isinstance(doc, dict):
raise ValueError("Invalid Linux feed: expected a YAML mapping")
version = doc.get("version")
if not isinstance(version, str) or not is_valid_version(version):
raise ValueError(f"Invalid Linux feed version: {version!r}")
files_raw = doc.get("files")
if not isinstance(files_raw, list) or len(files_raw) != 1:
raise ValueError("Invalid Linux feed: expected exactly one files[] entry")
entry = _validate_feed_entry(files_raw[0])
if "path" in doc and doc["path"] != entry["url"]:
raise ValueError("Invalid Linux feed: top-level path disagrees with files[0].url")
if "sha512" in doc and doc["sha512"] != entry["sha512"]:
raise ValueError("Invalid Linux feed: top-level sha512 disagrees with files[0].sha512")
release_date = doc.get("releaseDate")
if release_date is not None and not isinstance(release_date, str):
raise ValueError("Invalid Linux feed: releaseDate must be a string")
release_notes = doc.get("releaseNotes")
if release_notes is not None and not isinstance(release_notes, str):
raise ValueError("Invalid Linux feed: releaseNotes must be a string")
out: dict[str, Any] = {
"version": version,
"files": [entry],
"path": entry["url"],
"sha512": entry["sha512"],
}
if release_date is not None:
out["releaseDate"] = release_date
if release_notes is not None:
out["releaseNotes"] = release_notes
return out
def linux_feed_references(text: str) -> list[str]:
"""Return every R2 object key referenced by a published Linux feed (AppImage only; embedded blockmap)."""
feed = parse_linux_feed(text)
refs: list[str] = []
for entry in feed["files"]:
url = entry["url"]
if not url.startswith("/releases/tag/"):
raise ValueError(f"Linux feed URL must start with /releases/tag/: {url!r}")
if ".." in url.split("/") or "?" in url or "#" in url:
raise ValueError(f"Linux feed URL contains invalid path characters: {url!r}")
if not url.endswith(".AppImage"):
raise ValueError(f"Linux feed URL must reference an .AppImage: {url!r}")
refs.append(url[1:])
return refs
def _expected_appimage_name(version: str, arch: str) -> str:
return f"HermesBundled-{version}-linux-{APPIMAGE_ARCH[arch]}.AppImage"
def _format_feed_yaml(feed: dict[str, Any]) -> str:
return yaml.safe_dump(feed, sort_keys=False, allow_unicode=False)
def plan_linux_feeds(
feeds_by_arch: Mapping[str, str],
tag: str,
*,
archive: str | None = None,
) -> dict[str, dict[str, Any]]:
"""Prevalidate and rewrite both Linux arch feeds together before any R2 write.
Preserves literal ``+`` in canary versions and filenames. Fails closed if
either architecture is missing, an unexpected architecture is passed, or
either manifest disagrees with ``tag`` / ``archive``.
"""
version = release_version(tag)
if not version or not is_valid_version(version):
raise ValueError(f"Tag {tag!r} does not produce a valid release version")
channel = "canary" if is_canary_tag(tag) else "stable"
archive_tag = archive or tag
if "/" in archive_tag or ".." in archive_tag or not archive_tag:
raise ValueError(f"Invalid archive tag: {archive_tag!r}")
provided = set(feeds_by_arch)
expected_arches = set(ARCHES)
if provided != expected_arches:
missing = sorted(expected_arches - provided)
extra = sorted(provided - expected_arches)
raise ValueError(f"Linux feed publication requires exact arches {sorted(expected_arches)} (missing={missing}, extra={extra})")
plans: dict[str, dict[str, Any]] = {}
for arch in ARCHES:
parsed = parse_linux_feed(feeds_by_arch[arch])
if parsed["version"] != version:
raise ValueError(f"Linux {arch} feed version {parsed['version']!r} != expected {version!r}")
entry = parsed["files"][0]
raw_url = entry["url"]
if "/" in raw_url or "\\" in raw_url or ".." in raw_url:
raise ValueError(f"Linux {arch} input feed url must be a bare filename, got {raw_url!r}")
expected_name = _expected_appimage_name(version, arch)
if raw_url != expected_name:
raise ValueError(f"Linux {arch} feed artifact {raw_url!r} != expected {expected_name!r}")
artifact_key = f"releases/tag/{archive_tag}/{expected_name}"
rewritten_url = f"/{artifact_key}"
rewritten_entry = {**entry, "url": rewritten_url}
rewritten_feed: dict[str, Any] = {
"version": version,
"files": [rewritten_entry],
"path": rewritten_url,
"sha512": entry["sha512"],
}
if "releaseDate" in parsed:
rewritten_feed["releaseDate"] = parsed["releaseDate"]
if "releaseNotes" in parsed:
rewritten_feed["releaseNotes"] = parsed["releaseNotes"]
spec = linux_feed_spec(channel, arch)
plans[arch] = {
"arch": arch,
"channel": channel,
"key": spec["key"],
"version": version,
"artifact_key": artifact_key,
"feed": rewritten_feed,
"text": _format_feed_yaml(rewritten_feed),
}
return plans
def _arch_evidence_reasons(
tag: str,
commit: str,
arch_evidence: Mapping[str, ArchEvidence],
archive: str,
) -> list[str]:
"""Identity and smoke refusals shared by record_evidence and admit_publication."""
reasons: list[str] = []
if not _SHA256_OR_COMMIT_RE.match(commit):
reasons.append(f"invalid commit SHA: {commit!r}")
version = release_version(tag)
if not version or not is_valid_version(version):
reasons.append(f"invalid release tag: {tag!r}")
for arch in ARCHES:
ev = arch_evidence.get(arch)
if ev is None:
reasons.append(f"missing smoke evidence for linux-{arch}")
continue
if ev.arch != arch:
reasons.append(f"evidence arch mismatch for linux-{arch}: got {ev.arch!r}")
if ev.claim_tag != archive:
reasons.append(f"linux-{arch} claim {ev.claim_tag!r} != {archive!r}")
if ev.commit != commit:
reasons.append(f"linux-{arch} commit {ev.commit!r} != {commit!r}")
if not ev.staged:
reasons.append(f"linux-{arch} candidate was not staged")
if not ev.smoke_passed:
reasons.append(f"linux-{arch} diagnostic smoke did not pass")
return reasons
def admit_publication(
tag: str,
commit: str,
arch_evidence: Mapping[str, ArchEvidence],
authority: ChannelAuthority,
*,
archive: str | None = None,
) -> AdmissionResult:
"""All-or-nothing publication admission gate for Linux updater feeds."""
expected_channel: Literal["canary", "stable"] = "canary" if is_canary_tag(tag) else "stable"
expected_claim = archive or tag
reasons = _arch_evidence_reasons(tag, commit, arch_evidence, expected_claim)
if authority.abandoned:
reasons.append("candidate claim is abandoned")
if authority.channel != expected_channel:
reasons.append(f"authority channel {authority.channel!r} != {expected_channel!r}")
if authority.claim_tag != expected_claim:
reasons.append(f"authority claim {authority.claim_tag!r} != {expected_claim!r}")
if authority.commit != commit:
reasons.append(f"authority commit {authority.commit!r} != {commit!r}")
if expected_channel == "canary" and not authority.publish_canary_succeeded:
reasons.append("publish-canary has not succeeded for this claim")
if expected_channel == "stable" and not authority.sequencer_promoted:
reasons.append("sequencer has not promoted this stable claim")
return AdmissionResult(admitted=not reasons, reasons=tuple(reasons))
def _canary_stamp(version: str) -> str | None:
match = _CANARY_RE.search(version)
return match.group(1) if match else None
def _compare_feed_versions(new_version: str, live_version: str) -> int:
cmp = semver_compare(new_version, live_version)
if cmp != 0:
return cmp
new_stamp, live_stamp = _canary_stamp(new_version), _canary_stamp(live_version)
if new_stamp and live_stamp:
return (new_stamp > live_stamp) - (new_stamp < live_stamp)
if new_stamp or live_stamp:
raise ValueError(f"Cannot compare mixed canary/stable versions: {new_version!r} vs {live_version!r}")
return 0
def _feeds_match_artifacts(candidate: dict[str, Any], live: dict[str, Any]) -> bool:
return (
candidate["version"] == live["version"]
and candidate["files"] == live["files"]
and candidate.get("path") == live.get("path")
and candidate.get("sha512") == live.get("sha512")
)
def _get_live_feed(
creds: dict[str, str],
base: str,
bucket: str,
key: str,
now: str,
) -> tuple[str | None, str | None]:
url = r2.R2Scope.configured().object_url(base, bucket, key)
try:
response = r2.signed_request("GET", url, creds=creds, now=now)
except r2.R2RequestError as err:
if err.status == 404:
return None, None
raise
etag = response.header("etag")
if not etag:
raise ValueError(f"No ETag for {key}")
return response.text(), etag
def _preflight_feed(
creds: dict[str, str],
base: str,
bucket: str,
plan: dict[str, Any],
now: str,
) -> tuple[dict[str, Any], str | None, Literal["put", "noop"]]:
live_text, live_etag = _get_live_feed(creds, base, bucket, plan["key"], now)
action: Literal["put", "noop"] = "put"
if live_text is not None:
live_feed = parse_linux_feed(live_text)
order = _compare_feed_versions(plan["version"], live_feed["version"])
if order < 0:
raise ValueError(
f"Refusing to move Linux {plan['arch']} feed backward from "
f"{live_feed['version']} to {plan['version']}"
)
if order == 0:
if not (_feeds_match_artifacts(plan["feed"], live_feed) and plan["text"] == live_text):
raise ValueError(
f"Linux {plan['arch']} feed already serves {plan['version']} with different artifacts"
)
action = "noop"
# A feed that is already live still has its AppImage checked: a retry after a partial
# publish writes the other arch's feed only while both AppImages verify.
entry = plan["feed"]["files"][0]
artifact_url = r2.R2Scope.configured().object_url(base, bucket, plan["artifact_key"])
r2.verify_remote_artifact(artifact_url, creds, now, entry["size"], entry["sha512"])
return plan, live_etag, action
def _put_and_verify_feed(
creds: dict[str, str],
base: str,
bucket: str,
plan: dict[str, Any],
live_etag: str | None,
now: str,
) -> None:
r2.put_object(
creds,
base,
bucket,
plan["key"],
plan["text"].encode("utf-8"),
now,
"application/yaml",
{"If-Match": live_etag} if live_etag else {"If-None-Match": "*"},
)
readback_text, _ = _get_live_feed(creds, base, bucket, plan["key"], now)
if readback_text != plan["text"]:
raise ValueError(f"Linux {plan['arch']} feed readback differs after PUT to {plan['key']}")
def publish_admitted(
*,
tag: str,
commit: str,
feeds_by_arch: Mapping[str, str],
arch_evidence: Mapping[str, ArchEvidence],
authority: ChannelAuthority,
archive: str | None = None,
) -> dict[str, Any]:
"""Publish both Linux updater feeds only when admission and preflight pass for both arches.
Refusal at admission produces zero R2 requests (zero PUTs). When admitted,
BOTH manifests are parsed/rewritten and preflighted against R2 (downgrade
checks + AppImage size/sha512 verification) before the very first PUT.
If the second PUT fails, retrying is safe and idempotent: the already-written
first feed becomes a no-op and never overwrites a newer release.
"""
admission = admit_publication(tag, commit, arch_evidence, authority, archive=archive)
if not admission.admitted:
return {
"published": False,
"written": [],
"skipped": [],
"reasons": list(admission.reasons),
}
plans = plan_linux_feeds(feeds_by_arch, tag, archive=archive)
creds, base, bucket = r2.credentials()
now = r2.amz_timestamp()
prepared = [
_preflight_feed(creds, base, bucket, plans[arch], now)
for arch in ARCHES
]
written: list[str] = []
skipped: list[str] = []
for plan, live_etag, action in prepared:
if action == "noop":
skipped.append(plan["key"])
continue
_put_and_verify_feed(creds, base, bucket, plan, live_etag, now)
written.append(plan["key"])
return {
"published": True,
"written": written,
"skipped": skipped,
"reasons": [],
}
def load_feeds_from_dir(directory: str, tag: str) -> dict[str, str]:
"""Read both staged Linux feed files from ``directory`` for ``tag``."""
channel = "canary" if is_canary_tag(tag) else "stable"
feeds: dict[str, str] = {}
for arch in ARCHES:
spec = linux_feed_spec(channel, arch)
path = os.path.join(directory, spec["fileName"])
if not os.path.isfile(path):
raise FileNotFoundError(f"Missing staged Linux {arch} feed file: {path}")
with open(path, encoding="utf-8-sig") as handle:
feeds[arch] = handle.read()
return feeds
def fetch_staged_feeds(
tag: str,
commit: str,
directory: str,
*,
archive: str | None = None,
) -> dict[str, str]:
"""Download both staged Linux feeds through the receipt-bound handoff transport, then read them."""
channel = "canary" if is_canary_tag(tag) else "stable"
for arch in ARCHES:
# One receipt per fetch, so each arch's feed can only come from that arch's own receipt.
include = linux_feed_spec(channel, arch)["fileName"]
handoff.fetch(archive or tag, commit, [f"linux-{arch}"], Path(directory), [include])
return load_feeds_from_dir(directory, tag)
def _is_true(value: str | None) -> bool:
return (value or "").strip().lower() == "true"
def evidence_key(archive: str) -> str:
"""Immutable R2 key for cross-run Linux smoke evidence under a claim archive."""
if not archive or "/" in archive or ".." in archive:
raise ValueError(f"Invalid archive tag: {archive!r}")
return r2.staging_key_for(archive, EVIDENCE_FILENAME)
def parse_evidence(
raw: bytes | str,
*,
tag: str,
commit: str,
archive: str,
) -> dict[str, ArchEvidence]:
"""Parse and strictly identity-check a staged Linux smoke evidence receipt."""
text = raw.decode("utf-8-sig") if isinstance(raw, bytes) else raw
doc = json.loads(text)
if not isinstance(doc, dict) or doc.get("schema") != 1:
raise ValueError("Invalid Linux smoke evidence receipt: unsupported schema")
for field, expected in (("tag", tag), ("archive", archive), ("commit", commit)):
if doc.get(field) != expected:
raise ValueError(
f"Linux smoke evidence receipt {field} {doc.get(field)!r} != expected {expected!r}"
)
arches_raw = doc.get("arches")
if not isinstance(arches_raw, dict) or set(arches_raw) != set(ARCHES):
raise ValueError("Invalid Linux smoke evidence receipt: expected exact x64 and arm64 entries")
evidence: dict[str, ArchEvidence] = {}
for arch in ARCHES:
row = arches_raw[arch]
if (
not isinstance(row, dict)
or not isinstance(row.get("staged"), bool)
or not isinstance(row.get("smokePassed"), bool)
):
raise ValueError(f"Invalid Linux smoke evidence entry for {arch}")
evidence[arch] = ArchEvidence(
arch=arch,
claim_tag=archive,
commit=commit,
staged=row["staged"],
smoke_passed=row["smokePassed"],
)
return evidence
def _evidence_from_env(source: Mapping[str, str], archive: str, commit: str) -> dict[str, ArchEvidence]:
return {
"x64": ArchEvidence(
arch="x64",
claim_tag=archive,
commit=commit,
staged=_is_true(source.get("LINUX_X64_STAGED")),
smoke_passed=_is_true(source.get("LINUX_X64_SMOKE_PASSED")),
),
"arm64": ArchEvidence(
arch="arm64",
claim_tag=archive,
commit=commit,
staged=_is_true(source.get("LINUX_ARM64_STAGED")),
smoke_passed=_is_true(source.get("LINUX_ARM64_SMOKE_PASSED")),
),
}
def _get_r2_text(
creds: dict[str, str],
base: str,
bucket: str,
key: str,
now: str,
) -> str | None:
url = r2.R2Scope.configured().object_url(base, bucket, key)
try:
response = r2.signed_request("GET", url, creds=creds, now=now)
except r2.R2RequestError as err:
if err.status == 404:
return None
raise
return response.text()
def record_evidence(
*,
tag: str,
commit: str,
arch_evidence: Mapping[str, ArchEvidence],
archive: str | None = None,
) -> dict[str, Any]:
"""Persist immutable cross-run Linux smoke evidence under releases/tag/<archive>/.
Refuses with zero R2 requests unless both architectures genuinely staged and
passed smoke for the exact claim and commit. Before writing, receipt-verifies
both staged feeds and verifies both AppImage artifacts on R2. Touches no live
updater feed under releases/linux/.
"""
archive_tag = archive or tag
reasons = _arch_evidence_reasons(tag, commit, arch_evidence, archive_tag)
if reasons:
return {"recorded": False, "key": None, "reasons": reasons}
with tempfile.TemporaryDirectory() as directory:
feeds = fetch_staged_feeds(tag, commit, directory, archive=archive_tag)
plans = plan_linux_feeds(feeds, tag, archive=archive_tag)
creds, base, bucket = r2.credentials()
now = r2.amz_timestamp()
for arch in ARCHES:
entry = plans[arch]["feed"]["files"][0]
artifact_url = r2.R2Scope.configured().object_url(base, bucket, plans[arch]["artifact_key"])
r2.verify_remote_artifact(artifact_url, creds, now, entry["size"], entry["sha512"])
key = evidence_key(archive_tag)
payload_text = json.dumps(
{
"schema": 1,
"tag": tag,
"archive": archive_tag,
"commit": commit,
"arches": {
arch: {"staged": True, "smokePassed": True}
for arch in ARCHES
},
},
sort_keys=True,
separators=(",", ":"),
) + "\n"
payload = payload_text.encode("utf-8")
existing = _get_r2_text(creds, base, bucket, key, now)
if existing is not None:
if existing != payload_text:
raise ValueError(f"Conflicting Linux smoke evidence already exists at {key}")
return {"recorded": True, "key": key, "skipped": True, "reasons": []}
r2.put_object(creds, base, bucket, key, payload, now, "application/json", {"If-None-Match": "*"})
readback = _get_r2_text(creds, base, bucket, key, now)
if readback != payload_text:
raise ValueError(f"Linux smoke evidence readback differs after PUT to {key}")
return {"recorded": True, "key": key, "skipped": False, "reasons": []}
def record_evidence_from_env(env: Mapping[str, str] | None = None) -> dict[str, Any]:
"""Record cross-run Linux smoke evidence from workflow env when both arches passed."""
source = os.environ if env is None else env
tag = (source.get("RELEASE_TAG") or "").strip()
archive = (source.get("RELEASE_ARCHIVE_TAG") or tag).strip()
commit = (source.get("RELEASE_COMMIT") or "").strip()
evidence = _evidence_from_env(source, archive, commit)
return record_evidence(tag=tag, commit=commit, arch_evidence=evidence, archive=archive)
def read_evidence(
tag: str,
commit: str,
*,
archive: str | None = None,
) -> dict[str, ArchEvidence] | None:
"""Read and validate staged Linux smoke evidence from R2, or return None on 404."""
archive_tag = archive or tag
creds, base, bucket = r2.credentials()
now = r2.amz_timestamp()
text = _get_r2_text(creds, base, bucket, evidence_key(archive_tag), now)
if text is None:
return None
return parse_evidence(text, tag=tag, commit=commit, archive=archive_tag)
def publish_stable_record(record: Mapping[str, Any]) -> dict[str, Any]:
"""Publish stable Linux updater feeds for a sequencer-verified published release.
Only records whose ``state == 'published'`` and whose lanes include ``'linux'``
are eligible; held rehearsals, abandoned claims, and releases without the
opt-in Linux lane return immediately with zero R2 requests.
"""
if record.get("state") != "published":
return {
"published": False,
"written": [],
"skipped": [],
"reasons": [f"release state is {record.get('state')!r}, not 'published'"],
}
if "linux" not in record.get("lanes", ()):
return {
"published": False,
"written": [],
"skipped": [],
"reasons": ["linux lane was not opted into for this release"],
}
tag = str(record["tag"])
archive = str(record["claim_tag"])
commit = str(record["commit"])
evidence = read_evidence(tag, commit, archive=archive)
if evidence is None:
return {
"published": False,
"written": [],
"skipped": [],
"reasons": [f"missing staged Linux smoke evidence receipt at {evidence_key(archive)}"],
}
authority = ChannelAuthority(
channel="stable",
claim_tag=archive,
commit=commit,
sequencer_promoted=True,
)
admission = admit_publication(tag, commit, evidence, authority, archive=archive)
if not admission.admitted:
return {
"published": False,
"written": [],
"skipped": [],
"reasons": list(admission.reasons),
}
with tempfile.TemporaryDirectory() as directory:
feeds = fetch_staged_feeds(tag, commit, directory, archive=archive)
return publish_admitted(
tag=tag,
commit=commit,
archive=archive,
feeds_by_arch=feeds,
arch_evidence=evidence,
authority=authority,
)
def publish_from_env(env: Mapping[str, str] | None = None) -> dict[str, Any]:
"""Evaluate admission from workflow env; fetch and publish feeds only when admitted."""
source = os.environ if env is None else env
tag = (source.get("RELEASE_TAG") or "").strip()
archive = (source.get("RELEASE_ARCHIVE_TAG") or tag).strip()
commit = (source.get("RELEASE_COMMIT") or "").strip()
channel: Literal["canary", "stable"] = "canary" if is_canary_tag(tag) else "stable"
evidence = _evidence_from_env(source, archive, commit)
authority = ChannelAuthority(
channel=channel,
claim_tag=archive,
commit=commit,
publish_canary_succeeded=(source.get("PUBLISH_CANARY_RESULT") or "").strip().lower() == "success",
sequencer_promoted=_is_true(source.get("SEQUENCER_PROMOTED")),
abandoned=_is_true(source.get("CLAIM_ABANDONED")),
)
admission = admit_publication(tag, commit, evidence, authority, archive=archive)
if not admission.admitted:
return {
"published": False,
"written": [],
"skipped": [],
"reasons": list(admission.reasons),
}
with tempfile.TemporaryDirectory() as directory:
feeds = fetch_staged_feeds(tag, commit, directory, archive=archive)
return publish_admitted(
tag=tag,
commit=commit,
archive=archive,
feeds_by_arch=feeds,
arch_evidence=evidence,
authority=authority,
)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Linux AppImage updater feed publication")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("publish", help="Publish Linux updater feeds when admission and preflight pass")
sub.add_parser("record-evidence", help="Persist cross-run Linux smoke evidence under the claim archive")
args = parser.parse_args(argv)
if args.command == "publish":
result = publish_from_env()
print(json.dumps(result, sort_keys=True))
return 0
if args.command == "record-evidence":
result = record_evidence_from_env()
print(json.dumps(result, sort_keys=True))
return 0
return 2
if __name__ == "__main__":
raise SystemExit(main())