The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: consolidate release publication around receipt and HTTP contracts
ethernet0b4cd35915ef
diff --git a/tests/ci/test_commit_build_staging.py b/tests/ci/test_commit_build_staging.pyindex 540b40d71f5..33a81e5a014 100644--- a/tests/ci/test_commit_build_staging.py+++ b/tests/ci/test_commit_build_staging.py@@ -8,6 +8,7 @@ import shleximport subprocessimport sysfrom urllib.request import urlopen+from urllib.parse import quote, unquoteimport pytest@@ -159,7 +160,7 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tmmissing = shell_step(tmp_path, r2_server, 'termux-deb', termux_name, env)assert missing.returncode != 0assert r2_server.store == before- deb = tmp_path / 'termux-build/deb/hermes-agent_0.33.0~commit.aaaaaaaaaaaa_aarch64.deb'+ deb = tmp_path / 'termux-build/deb/hermes agent_0.33.0~commit.aaaaaaaaaaaa_aarch64.deb'deb.parent.mkdir(parents=True)deb.write_bytes(b'transport fixture, not a native Debian package')staged = shell_step(tmp_path, r2_server, 'termux-deb', termux_name, env)@@ -180,16 +181,30 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tmtext = summary.read_text(encoding='utf-8')links = re.findall(r'\]\((http[^)]+)\)', text)# Blockmaps are receipt inputs; every other staged product has a download row.- expected = {f'{base}/{key}' for key in artifact_keys if not key.endswith('.blockmap')}+ expected = {f'{base}/{quote(key, safe="/")}' for key in artifact_keys if not key.endswith('.blockmap')}assert set(links) == expectedassert len(links) == len(expected)for url in links:with urlopen(url, timeout=5) as response:- key = url.removeprefix(base + '/')+ key = unquote(url.removeprefix(base + '/'))assert response.read() == r2_server.store[key][0]+ page_key = f'releases/commit/{sha}/index.html'+ page = r2_server.store[page_key][0].decode()+ assert all(f'href="{url}"' in page for url in expected)+ assert 'Store' not in page and 'Linux x64' in page and 'Linux ARM64' in pageassert all(key.startswith(f'releases/commit/{sha}/') for key in r2_server.store)assert not any(method == 'DELETE' for method, _, _ in r2_server.requests)+ receipt_key = f'releases/commit/{sha}/handoff-win32-x64.json'+ original = r2_server.store[receipt_key]+ r2_server.store[receipt_key] = (b'not-json', '"invalid"')+ failed = shell_step(tmp_path, r2_server, 'commit-builds-summary',+ 'Render the full expected-binary matrix', summary_env)+ assert failed.returncode != 0+ assert summary.read_text(encoding='utf-8') == text+ assert r2_server.store[page_key][0].decode() == page+ r2_server.store[receipt_key] = original+# The actual summary command remains useful after an admitted matrix failure.r2_server.store.pop(f'releases/commit/{sha}/handoff-darwin-x64.json')summary.unlink()diff --git a/tests/scripts/test_release_artifacts.py b/tests/scripts/test_release_artifacts.pyindex 8dc1427411e..df933d0b3e1 100644--- a/tests/scripts/test_release_artifacts.py+++ b/tests/scripts/test_release_artifacts.py@@ -1,14 +1,17 @@"""Native metadata and artifact publication use the same verified bytes."""import hashlib-import io+import copyimport jsonimport zipfile-from pathlib import Path+import xml.etree.ElementTree as ETimport pytestfrom scripts.bundles.release_artifacts import materialize, record, stamp_matchesfrom tests.scripts.test_release_r2 import r2_server # noqa: F401+from tests.scripts.test_stable_release import https_origin # noqa: F401+from tests.scripts.test_release_darwin import _inputs+from scripts.bundles import release_artifacts as artifactsdef test_windows_metadata_is_read_from_package_and_stale_stamp_is_rejected(tmp_path):@@ -40,11 +43,14 @@ def test_windows_metadata_is_read_from_package_and_stale_stamp_is_rejected(tmp_pstamp_matches({}, tag, commit)-def test_assemble_uses_staged_receipts_and_only_publishes_the_manifest(tmp_path, monkeypatch, r2_server):+def staged_candidate(tmp_path, r2_server, https_origin):from scripts.bundles.release_artifacts import assemblefrom scripts.releases import handoff- tag, commit, base = 'v1.2.3', 'a' * 40, 'https://releases.example'+ tag, commit, base = 'v1.2.3', 'a' * 40, https_origin.base+ https_origin.store = r2_server.store+ legs, mac_bytes = _inputs('1.2.3')built = tmp_path / 'built'built.mkdir()for platform, arches in [('windows', ('x64', 'arm64')), ('macos', ('x64', 'arm64')), ('termux', ('aarch64',))]:@@ -55,7 +61,7 @@ def test_assemble_uses_staged_receipts_and_only_publishes_the_manifest(tmp_path,package = f'Product-win-{arch}.msix'handoff_name = f'win32-{arch}'elif platform == 'macos':- package = f'Product-mac-{arch}.zip'+ package = f'HermesBundled-1.2.3-mac-{arch}.zip'row.update(version='1.2.3', teamId='ABCDEFGHIJ', filename=package)handoff_name = f'darwin-{arch}'else:@@ -64,10 +70,21 @@ def test_assemble_uses_staged_receipts_and_only_publishes_the_manifest(tmp_path,handoff_name = 'termux'file = built / packagefile.parent.mkdir(parents=True, exist_ok=True)- file.write_bytes(b'package transport fixture')+ file.write_bytes(mac_bytes.get(f'releases/tag/{tag}/{package}', b'package transport fixture'))metadata = built / f'metadata-{platform}-{arch}.json'metadata.write_text(json.dumps(row), encoding='utf-8')- handoff.stage(tag, commit, handoff_name, built, [package, metadata.name])+ includes = [package, metadata.name]+ if platform == 'macos':+ feed = f'{arch}-stable-mac.yml'+ (built / feed).write_text(legs[feed], encoding='utf-8')+ includes.append(feed)+ if platform == 'termux':+ for name in ('pool/package.deb', 'dists/hermes-stable/InRelease', 'dists/hermes-stable/Release'):+ path = built / 'apt' / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(f'index transport fixture: {name}'.encode())+ includes.append('apt/**/*')+ handoff.stage(tag, commit, handoff_name, built, includes)bundle = built / 'Product-win.msixbundle'with zipfile.ZipFile(bundle, 'w') as archive:archive.writestr('AppxMetadata/AppxBundleManifest.xml', '<Bundle><Identity Name="Product" Publisher="CN=Test" Version="1.2.3.0"/></Bundle>')@@ -84,6 +101,14 @@ def test_assemble_uses_staged_receipts_and_only_publishes_the_manifest(tmp_path,puts = [path for method, path, _ in r2_server.requests if method == 'PUT']assert puts == [f'/hermes-releases/releases/tag/{tag}/release-candidates.json']assert all(key.startswith(f'releases/tag/{tag}/') for key in r2_server.store)+ return manifest, fetched, base+++def test_assemble_rejects_missing_and_changed_receipts(tmp_path, staged_candidate):+ from scripts.bundles.release_artifacts import assemble++ manifest, fetched, base = staged_candidate+ tag, commit = manifest['tag'], manifest['commit']receipt = fetched / 'handoff-darwin-arm64.json'original = receipt.read_bytes()receipt.unlink()@@ -95,61 +120,58 @@ def test_assemble_uses_staged_receipts_and_only_publishes_the_manifest(tmp_path,assemble(fetched, tag, commit, base, tmp_path / 'changed.json')-def test_materialize_validates_the_published_file_receipt_before_using_bytes(tmp_path, monkeypatch):- base, tag, commit = 'https://releases.example', 'v1.2.3', 'a' * 40- data = b'package transport fixture, not native signing proof'- digest = hashlib.sha256(data).hexdigest()- files, packages = [], []- for platform in ('windows', 'macos'):- for arch in ('x64', 'arm64'):- filename = f'{platform}-{arch}.' + ('msixbundle' if platform == 'windows' else 'zip')- url = f'{base}/releases/tag/{tag}/{filename}'- files.append({'path': filename, 'url': url, 'sha256': digest})- packages.append({'platform': platform, 'arch': arch, 'identity': 'Product', 'tag': tag, 'commit': commit,- 'version': '1.2.3.0' if platform == 'windows' else '1.2.3',- **({'publisher': 'CN=Test', 'applicationId': 'App'} if platform == 'windows' else {'teamId': 'ABCDEFGHIJ'}),- 'artifact': {'url': url, 'sha256': digest}})- manifest = {'schema': 1, 'tag': tag, 'commit': commit, 'packages': packages, 'files': files}- class Response(io.BytesIO):- def geturl(self):- return base + "/package"-- monkeypatch.setattr('urllib.request.urlopen', lambda *a, **kw: Response(data))- materialize(manifest, tmp_path / 'good', public_base=base)- assert all((tmp_path / 'good' / f['path']).read_bytes() == data for f in files)- with pytest.raises(ValueError, match='one Store candidate'):- materialize(manifest, tmp_path / 'store-missing', public_base=base, store_only=True)- store = {'path': 'Store-App.msixbundle', 'url': f'{base}/releases/tag/{tag}/Store-App.msixbundle', 'sha256': digest}- files.append(store)- materialize(manifest, tmp_path / 'store', public_base=base, store_only=True)- assert [p.name for p in (tmp_path / 'store').iterdir()] == [store['path']]-- from scripts.bundles import release_artifacts- from scripts.releases import stable- raw_manifest = json.dumps(manifest).encode()- seen = []-- def read_remote(url, expected_hash, *, expected_origin):- seen.append((url, expected_hash, expected_origin))- return stable.read_manifest(url, expected_hash, expected_origin=expected_origin,- opener=lambda *args, **kwargs: Response(raw_manifest))-- monkeypatch.setattr(release_artifacts, 'read_manifest', read_remote)- monkeypatch.setenv('CANDIDATE_MANIFEST_SHA256', hashlib.sha256(raw_manifest).hexdigest())- release_artifacts.main(['materialize', '--tag', tag, '--commit', commit, '--public-base', base,- '--root', str(tmp_path / 'remote-store'), '--store-only'])- assert (tmp_path / 'remote-store' / store['path']).read_bytes() == data- assert seen[0][0] == f'{base}/releases/tag/{tag}/release-candidates.json'- assert seen[0][2] == base+def test_candidate_publication_and_store_selection(tmp_path, monkeypatch, r2_server, staged_candidate):+ manifest, _, base = staged_candidate+ tag, commit = manifest['tag'], manifest['commit']+ raw = r2_server.store[f'releases/tag/{tag}/release-candidates.json'][0]+ args = ['--tag', tag, '--commit', commit, '--public-base', base]+ monkeypatch.setenv('CANDIDATE_MANIFEST_SHA256', hashlib.sha256(raw).hexdigest())+ artifacts.main(['materialize', *args, '--root', str(tmp_path / 'store'), '--store-only'])+ assert [p.name for p in (tmp_path / 'store').iterdir()] == ['Store-Product-win.msixbundle']+ assert (tmp_path / 'store/Store-Product-win.msixbundle').read_bytes() == b'Store bundle transport fixture'monkeypatch.setenv('CANDIDATE_MANIFEST_SHA256', 'f' * 64)with pytest.raises(ValueError, match='digest mismatch'):- release_artifacts.main(['materialize', '--tag', tag, '--commit', commit, '--public-base', base,- '--root', str(tmp_path / 'wrong-manifest'), '--store-only'])- assert not (tmp_path / 'wrong-manifest').exists()- files[0]['sha256'] = 'b' * 64+ artifacts.main(['materialize', *args, '--root', str(tmp_path / 'wrong')])+ assert not (tmp_path / 'wrong').exists()+ missing = copy.deepcopy(manifest)+ missing['files'] = [f for f in missing['files'] if not f['path'].startswith('Store-')]+ with pytest.raises(ValueError, match='one Store candidate'):+ materialize(missing, tmp_path / 'missing-store', public_base=base, store_only=True)+ changed = copy.deepcopy(manifest)+ changed['files'][0]['sha256'] = 'b' * 64with pytest.raises(ValueError, match='receipts differ'):- materialize(manifest, tmp_path / 'bad', public_base=base)- files[0]['sha256'] = digest- monkeypatch.setattr('urllib.request.urlopen', lambda *a, **kw: Response(b'changed bytes'))+ materialize(changed, tmp_path / 'bad', public_base=base)++ r2_server.requests.clear()+ artifacts.publish(manifest, tmp_path / 'publish', base)+ assert [path for method, path, _ in r2_server.requests if method == 'PUT'] == [+ '/hermes-releases/releases/termux/stable/pool/package.deb']+ r2_server.requests.clear()+ artifacts.promote(manifest, tmp_path / 'promote', base)+ puts = [path for method, path, _ in r2_server.requests if method == 'PUT']+ assert puts == ['/hermes-releases/' + name for name in (+ 'releases/darwin/stable/stable-mac.yml', 'releases/win32/stable/stable.appinstaller',+ 'releases/termux/stable/dists/hermes-stable/Release', 'releases/termux/stable/dists/hermes-stable/InRelease')]+ for item in manifest['files']:+ assert (tmp_path / 'promote' / item['path']).read_bytes() == r2_server.store[f'releases/tag/{tag}/{item["path"]}'][0]+ descriptor = ET.fromstring(r2_server.store['releases/win32/stable/stable.appinstaller'][0])+ assert descriptor.attrib == {'Uri': base + '/releases/win32/stable/stable.appinstaller', 'Version': '1.2.3.0'}+ assert descriptor.find('{*}MainBundle').attrib == {+ 'Name': 'Product', 'Publisher': 'CN=Test', 'Version': '1.2.3.0',+ 'Uri': base + '/releases/tag/v1.2.3/Product-win.msixbundle'}+ pointer = 'releases/win32/stable/stable.appinstaller'+ original = r2_server.store[pointer]+ r2_server.corrupt_put = pointer+ r2_server.requests.clear()+ with pytest.raises(ValueError, match='Channel read-back differs'):+ artifacts.promote(manifest, tmp_path / 'bad-readback', base)+ assert [path for method, path, _ in r2_server.requests if method == 'PUT'] == ['/hermes-releases/' + pointer]+ r2_server.corrupt_put = None+ r2_server.store[pointer] = original+ before = dict(r2_server.store)+ r2_server.store[f'releases/tag/{tag}/Product-win.msixbundle'] = (b'corrupt', '"e"')+ r2_server.requests.clear()with pytest.raises(ValueError, match='digest mismatch'):- materialize(manifest, tmp_path / 'corrupt', public_base=base)+ artifacts.promote(manifest, tmp_path / 'broken', base)+ assert not any(method == 'PUT' for method, _, _ in r2_server.requests)+ assert all(value == r2_server.store[key] for key, value in before.items() if not key.startswith('releases/tag/'))diff --git a/tests/scripts/test_release_bootstrap_installer_version.py b/tests/scripts/test_release_bootstrap_installer_version.pyindex 48e45245999..5cfa3e09bfe 100644--- a/tests/scripts/test_release_bootstrap_installer_version.py+++ b/tests/scripts/test_release_bootstrap_installer_version.py@@ -88,7 +88,9 @@ def _patch_repo(tmp_path, monkeypatch, *, with_installer: bool = True):def test_update_version_files_stamps_bootstrap_installer(tmp_path, monkeypatch):paths = _patch_repo(tmp_path, monkeypatch)- release.update_version_files("0.21.1", "2026.9.10")+ staged = release.update_version_files("0.21.1", "2026.9.10")+ assert all(str(paths[key]) in staged for key in (+ 'init_py', 'pyproject', 'desktop_pkg', 'installer_pkg', 'tauri_conf', 'cargo_toml'))assert _json_version(paths["installer_pkg"]) == "0.21.1"assert _json_version(paths["tauri_conf"]) == "0.21.1"@@ -105,7 +107,9 @@ def test_update_version_files_stamps_bootstrap_installer(tmp_path, monkeypatch):def test_update_version_files_skips_missing_installer_dir(tmp_path, monkeypatch):paths = _patch_repo(tmp_path, monkeypatch, with_installer=False)- release.update_version_files("0.21.1", "2026.9.10")+ staged = release.update_version_files("0.21.1", "2026.9.10")+ assert all(str(paths[key]) not in staged for key in ('installer_pkg', 'tauri_conf', 'cargo_toml'))+ assert all(str(paths[key]) in staged for key in ('init_py', 'pyproject', 'desktop_pkg'))assert not paths["installer_pkg"].exists()assert not paths["tauri_conf"].exists()@@ -125,29 +129,3 @@ def test_update_version_files_does_not_invent_version_keys(tmp_path, monkeypatchassert paths["installer_pkg"].read_text(encoding="utf-8") == originalassert paths["tauri_conf"].read_text(encoding="utf-8") == originalassert _json_version(paths["desktop_pkg"]) == "0.21.1"---def test_updated_files_include_installer_when_present(tmp_path, monkeypatch):- paths = _patch_repo(tmp_path, monkeypatch)-- staged = release.update_version_files("0.21.1", "2026.9.10")-- assert str(paths["init_py"]) in staged- assert str(paths["pyproject"]) in staged- assert str(paths["desktop_pkg"]) in staged- assert str(paths["installer_pkg"]) in staged- assert str(paths["tauri_conf"]) in staged- assert str(paths["cargo_toml"]) in staged---def test_updated_files_omit_missing_installer(tmp_path, monkeypatch):- paths = _patch_repo(tmp_path, monkeypatch, with_installer=False)-- staged = release.update_version_files("0.21.1", "2026.9.10")-- assert str(paths["installer_pkg"]) not in staged- assert str(paths["tauri_conf"]) not in staged- assert str(paths["cargo_toml"]) not in staged- assert str(paths["desktop_pkg"]) in staged- assert str(paths["init_py"]) in staged- assert str(paths["pyproject"]) in stageddiff --git a/tests/scripts/test_release_build_commit.py b/tests/scripts/test_release_build_commit.pyindex d3ae3fccb96..a27062f7996 100644--- a/tests/scripts/test_release_build_commit.py+++ b/tests/scripts/test_release_build_commit.py@@ -6,7 +6,7 @@ import shutilimport subprocessimport sys-from scripts.releases import commit_build+import pytestROOT = Path(__file__).resolve().parents[2]@@ -16,6 +16,7 @@ def git(repo, *args):text=True, encoding='utf-8', timeout=30).stdout.strip()def fixture_repo(tmp_path):upstream = tmp_path / 'upstream.git'subprocess.run(['git', 'init', '--bare', '-q', '-b', 'main', str(upstream)], check=True)@@ -90,26 +91,29 @@ else:return repo, upstream, invoke-def test_commit_build_cli_dispatches_only_the_resolved_remote_commit(tmp_path):- repo, upstream, invoke = fixture_repo(tmp_path)+def test_commit_build_cli_dispatches_only_the_resolved_remote_commit(fixture_repo):+ repo, upstream, invoke = fixture_repotip = git(repo, 'rev-parse', 'HEAD')before = git(repo, 'show-ref', '--heads', '--tags')for revision in (tip[:8], 'main'):result, calls = invoke('--build-commit', revision)assert result.returncode == 0, result.stderr- assert f'Commit: {tip}' in result.stdout and f'releases/commit/{tip}/' in result.stdout- # The commit build's downloads page is named before anything is- # dispatched, so the URL can be opened once the matrix finishes.- assert 'Page: http' in result.stdout and f'releases/commit/{tip}/index.html' in result.stdout+ assert tip in result.stdout+ assert f'https://hermes-assets.nousresearch.com/releases/commit/{tip}/index.html' in result.stdoutassert not any(call[1:3] == ['workflow', 'run'] for call in calls)result, calls = invoke('--build-commit', tip, '--publish')assert result.returncode == 0, result.stderrdispatches = [call for call in calls if call[1:3] == ['workflow', 'run']]- assert dispatches == [commit_build.dispatch_command(tip, 'fixture-owner/fixture-repo', 'main')]- assert f'build_commit={tip}' in dispatches[0] and 'upload_release=false' in dispatches[0]+ assert dispatches == [['gh', 'workflow', 'run', 'desktop-bundled-release.yml',+ '--ref', 'main', '--repo', 'fixture-owner/fixture-repo',+ '-f', f'build_commit={tip}', '-f', 'tag=', '-f', 'upload_release=false',+ '-f', 'termux_only=false', '-f', 'termux_upgrade_from_tag=']]assert git(repo, 'show-ref', '--heads', '--tags') == beforeassert git(upstream, 'rev-parse', 'refs/heads/main') == tip+def test_commit_bundle_environment_is_literal_and_validated(fixture_repo):+ repo, _, invoke = fixture_repo+ tip = git(repo, 'rev-parse', 'HEAD')values = {'HERMES_GUEST_ONBOARDING': '1', 'HERMES_DATA_DIR_SUFFIX': 'magic-test','EMPTY': '', 'LITERAL': 'a=b "quote"\n$(not-a-command)'}flags = [part for key, value in values.items() for part in ('--bundle-env', f'{key}={value}')]@@ -138,6 +142,9 @@ def test_commit_build_cli_dispatches_only_the_resolved_remote_commit(tmp_path):result, calls = invoke('--bundle-unset', 'HERMES_HOME')assert result.returncode == 2 and not calls+def test_commit_build_requires_pushed_refs_and_github_origin(tmp_path, fixture_repo):+ repo, upstream, invoke = fixture_repo+ tip = git(repo, 'rev-parse', 'HEAD')git(repo, 'checkout', '-qb', 'feature')(repo / 'feature').write_text('pushed feature', encoding='utf-8')git(repo, 'add', 'feature')@@ -149,7 +156,7 @@ def test_commit_build_cli_dispatches_only_the_resolved_remote_commit(tmp_path):for revision in (feature[:8], 'origin/feature', 'fixture-tag'):result, calls = invoke('--build-commit', revision)assert result.returncode == 0, result.stderr- assert f'Commit: {feature}' in result.stdout+ assert feature in result.stdoutassert git(repo, 'rev-parse', 'HEAD') == tipassert not any(call[1:3] == ['workflow', 'run'] for call in calls)@@ -176,8 +183,8 @@ def test_commit_build_cli_dispatches_only_the_resolved_remote_commit(tmp_path):assert result.returncode != 0 and 'GitHub remote' in result.stderr and not calls-def test_workflow_admission_checks_trust_before_publishing_outputs(tmp_path):- repo, _, invoke = fixture_repo(tmp_path)+def test_workflow_admission_checks_trust_before_publishing_outputs(tmp_path, fixture_repo):+ repo, _, invoke = fixture_repotip = git(repo, 'rev-parse', 'HEAD')output = tmp_path / 'output'env = {'BUILD_COMMIT': tip, 'DEFAULT_BRANCH': 'main',diff --git a/tests/scripts/test_release_canary.py b/tests/scripts/test_release_canary.pydeleted file mode 100644index 9c3bd45f199..00000000000--- a/tests/scripts/test_release_canary.py+++ /dev/null@@ -1,321 +0,0 @@-"""Canary release plumbing in scripts/release.py.--The canary channel's whole safety story is tag SHAPES: canary tags-carry a -canary.YYYYMMDD suffix, every stable selector requires the-no-suffix shape, and the version math (next-MINOR over stable) makes-electron-updater's semver ordering implement both channel-switch-directions. These tests pin the shapes and the math; the workflow only-provides credentials.-"""--import importlib.util-from datetime import datetime, timezone-from pathlib import Path--import pytest--_RELEASE_PATH = Path(__file__).resolve().parents[2] / "scripts" / "release.py"-_SPEC = importlib.util.spec_from_file_location("hermes_release_canary", _RELEASE_PATH)-assert _SPEC and _SPEC.loader-release = importlib.util.module_from_spec(_SPEC)-_SPEC.loader.exec_module(release)---class TestCanaryTagShape:- def test_canary_tag_for_date_is_next_patch(self):- """The authority's math: current stable's patch + 1, any patch."""- assert release.canary_tag_for_date("0.27.4", "20260818103000") == "v0.27.5-canary.20260818103000"- assert release.canary_tag_for_date("1.4.0", "20261231235959") == "v1.4.1-canary.20261231235959"-- def test_v_prefixed_stable_tag_accepted(self):- """cmd_canary passes the stable TAG (with the v) — the authority- strips it, so both forms produce the same tag."""- assert release.canary_tag_for_date("v0.27.4", "20260818103000") == "v0.27.5-canary.20260818103000"-- def test_shape_round_trips_through_the_canary_matcher(self):- tag = release.canary_tag_for_date("0.27.4", "20260818103000")- assert release._CANARY_TAG_RE.fullmatch(tag)-- def test_legacy_date_only_shape_still_matches(self):- """Readers stay tolerant of the original 8-digit suffix so an- already-published canary keeps parsing (prune, last-canary)."""- assert release._CANARY_TAG_RE.fullmatch("v0.28.0-canary.20260818")-- def test_canary_shape_is_invisible_to_the_stable_selector(self):- """THE invariant: a canary tag must never parse as stable —- otherwise stable users update onto canaries."""- for tag in (- release.canary_tag_for_date("0.27.4", "20260818103000"),- "v0.28.0-canary.20260818",- ):- assert release._SEMVER_TAG_RE.fullmatch(tag) is None, tag-- def test_stable_shape_is_invisible_to_the_canary_matcher(self):- assert release._CANARY_TAG_RE.fullmatch("v0.27.2") is None- # Legacy CalVer must not match either (v2026.7.20 has 20-prefixed- # components that could fool a sloppy pattern).- assert release._CANARY_TAG_RE.fullmatch("v2026.7.20") is None-- def test_same_day_canaries_order_chronologically(self):- """Second precision exists so manual fires can stack in one day;- fixed-length pure-numeric identifiers order the same lexically- (git -v:refname) and numerically (semver prerelease compare)."""- a = release.canary_tag_for_date("0.27.4", "20260818090000")- b = release.canary_tag_for_date("0.27.4", "20260818171500")- assert a < b # lexical == chronological at fixed length-- def test_canary_outversions_current_stable_loses_to_next_patch(self):- """The semver ordering that makes both channel switches work,- checked with packaging's canonical comparison when available,- else by electron-updater's documented precedence rules."""- try:- from packaging.version import Version- except ImportError:- pytest.skip("packaging not installed in this env")- canary = Version("0.27.5-canary.20260818103000".replace("-canary.", "a"))- assert Version("0.27.4") < canary < Version("0.27.5")---class TestCanaryDateStamps:- def test_prune_cutoff_uses_the_tag_date(self):- """The prune window keys on the tag's own YYYYMMDD prefix, for- both suffix shapes — a 14-digit suffix compared whole against an- 8-digit cutoff would be decided by string length, not by day."""- legacy = release._CANARY_TAG_RE.fullmatch("v0.27.1-canary.20260801")- stamped = release._CANARY_TAG_RE.fullmatch("v0.27.1-canary.20260801235959")- assert legacy and legacy.group(0).split("-canary.")[1][:8] == "20260801"- assert stamped and stamped.group(0).split("-canary.")[1][:8] == "20260801"---class TestCanaryBuildNumberGuards:- """The MSIX canary build number is minutes-since-the-last-stable.- Two canaries of the same line cut in the same minute would share a- build number → identical MSIX version → App Installer refuses the- second. cmd_canary refuses that; it also refuses a canary whose- stable base is >45 days old (the 16-bit MSIX component would- overflow)."""-- def test_same_minute_same_line_refused(self, monkeypatch, tmp_path):- import subprocess- from types import SimpleNamespace-- calls: list[list[str]] = []-- def fake_run(cmd, *a, **kw):- calls.append(list(cmd))- return subprocess.CompletedProcess(cmd, 0, stdout="url", stderr="")-- def fake_git_result(*args, **kw):- # rev-parse --verify must MISS so we reach the guard, not the- # "tag already exists" short-circuit.- return subprocess.CompletedProcess(args, 1, "", "")-- monkeypatch.setattr(release, "get_last_tag", lambda: "v0.27.1")- monkeypatch.setattr(release, "get_last_canary_tag", lambda: "v0.27.2-canary.20260818103045")- monkeypatch.setattr(release, "git_result", fake_git_result)- monkeypatch.setattr(subprocess, "run", fake_run)- monkeypatch.delenv("GITHUB_OUTPUT", raising=False)-- release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260818103000", publish=True, remote="origin"))- assert calls == [], "same-minute same-line re-cut must not create a release"-- def test_same_minute_new_line_allowed(self, monkeypatch, tmp_path):- """A fresh stable bumps the line; a same-minute cut on the new line- outversions the old line by its patch component, so no collision."""- import subprocess- from types import SimpleNamespace-- captured: list[list[str]] = []-- def fake_run(cmd, *a, **kw):- captured.append(list(cmd))- return subprocess.CompletedProcess(cmd, 0, stdout="url", stderr="")-- def fake_git_result(*args, **kw):- return subprocess.CompletedProcess(args, 1 if "rev-parse" in args else 0, "", "")-- monkeypatch.setattr(release, "get_last_tag", lambda: "v0.28.0")- monkeypatch.setattr(release, "get_last_canary_tag", lambda: "v0.27.2-canary.20260818103045")- monkeypatch.setattr(release, "get_commits", lambda **kw: [{"hash": "a" * 40, "subject": "feat: x", "author": "e"}])- monkeypatch.setattr(release, "generate_changelog", lambda *a, **kw: "notes")- monkeypatch.setattr(release, "resolve_push_remote", lambda r: "origin")- monkeypatch.setattr(release, "remote_github_repo", lambda r: "o/r")- monkeypatch.setattr(release, "git", lambda *a, **kw: "1786017600" if a and a[0] == "log" else "")- monkeypatch.setattr(release, "REPO_ROOT", tmp_path)- monkeypatch.setattr(release.git_result, "__defaults__", ())- monkeypatch.setattr(release, "git_result", fake_git_result)- monkeypatch.setattr(subprocess, "run", fake_run)- monkeypatch.delenv("GITHUB_OUTPUT", raising=False)-- release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260818103000", publish=True, remote="origin"))- create = [c for c in captured if c[:3] == ["gh", "release", "create"]]- assert len(create) == 1, captured-- def test_stable_base_older_than_45_days_refused(self, monkeypatch, tmp_path):- """Minutes-since-stable crosses the 16-bit MSIX component at 45.5- days; a canary cut on an older stable cannot carry a legal build- number — refuse loudly (exit 1), never clamp."""- import subprocess- import sys- from types import SimpleNamespace-- # Stable v0.27.1 committed 2026-07-01; canary cut 2026-08-29.- old_epoch = str(int(datetime(2026, 7, 1, tzinfo=timezone.utc).timestamp()))- monkeypatch.setattr(release, "get_last_tag", lambda: "v0.27.1")- monkeypatch.setattr(release, "get_last_canary_tag", lambda: None)- monkeypatch.setattr(release, "get_commits", lambda **kw: [{"hash": "a" * 40, "subject": "feat: x", "author": "e"}])- monkeypatch.setattr(release, "git", lambda *a, **kw: old_epoch if a and a[0] == "log" else "")- monkeypatch.setattr(release, "REPO_ROOT", tmp_path)- monkeypatch.setattr(release, "git_result", lambda *a, **kw: subprocess.CompletedProcess(a, 1, "", ""))- monkeypatch.delenv("GITHUB_OUTPUT", raising=False)-- with pytest.raises(SystemExit) as exc:- release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260829000000", publish=True, remote="origin"))- assert exc.value.code == 1---class TestCanaryIsDrafted:- """A canary is created as a DRAFT prerelease.-- A published release with no installers staged is one users can- reach and cannot use. The desktop matrix stages the installers to the- R2 bucket (releases/tag/<tag>/), the finalize job publishes the- feeds, and the canary workflow publishes the release only after- that matrix is green.- """-- def _create_argv(self, monkeypatch, tmp_path):- """The argv of the `gh release create` cmd_canary would run."""- import subprocess- from types import SimpleNamespace-- captured: list[list[str]] = []-- def fake_run(cmd, *a, **kw):- captured.append(list(cmd))- return subprocess.CompletedProcess(cmd, 0, stdout="url", stderr="")-- def fake_git_result(*args, **kw):- # `rev-parse --verify --quiet refs/tags/<tag>` must MISS, or- # cmd_canary short-circuits on "tag already exists".- code = 1 if "rev-parse" in args else 0- return subprocess.CompletedProcess(args, code, "", "")-- monkeypatch.setattr(release, "get_last_tag", lambda: "v0.27.0")- monkeypatch.setattr(release, "get_last_canary_tag", lambda: None)- monkeypatch.setattr(release, "get_commits", lambda **kw: [{"hash": "a" * 40, "subject": "feat: x", "author": "e"}])- monkeypatch.setattr(release, "generate_changelog", lambda *a, **kw: "notes")- monkeypatch.setattr(release, "resolve_push_remote", lambda r: "origin")- monkeypatch.setattr(release, "remote_github_repo", lambda r: "o/r")- monkeypatch.setattr(release, "git_result", fake_git_result)- monkeypatch.setattr(release, "git", lambda *a, **kw: "")- monkeypatch.setattr(release, "REPO_ROOT", tmp_path)- monkeypatch.setattr(subprocess, "run", fake_run)- monkeypatch.delenv("GITHUB_OUTPUT", raising=False)-- release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260818103000", publish=True, remote="origin"))- return next(c for c in captured if c[:3] == ["gh", "release", "create"])-- def test_created_as_a_draft_prerelease(self, monkeypatch, tmp_path):- argv = self._create_argv(monkeypatch, tmp_path)- assert "--draft" in argv, argv- assert "--prerelease" in argv, argv-- def test_refuses_to_invent_a_tag(self, monkeypatch, tmp_path):- """Without --verify-tag, gh creates a missing tag from the default- branch tip, which would release a different commit than the one- the canary math tagged."""- assert "--verify-tag" in self._create_argv(monkeypatch, tmp_path)---class TestCanaryStartsItsOwnBuild:- """release.py dispatches the desktop build for the tag it just cut.-- workflow_dispatch is one of only two events GITHUB_TOKEN may raise, so- it is the only trigger that serves the scheduled canary: that run- pushes its tag as github-actions[bot], and a bot-pushed tag starts no- workflow run. Dispatching from release.py gives the scheduled canary,- a hand-cut canary, and a stable release one identical mechanism.- """-- def _calls(self, monkeypatch, tmp_path):- import subprocess- from types import SimpleNamespace-- captured: list[list[str]] = []-- def fake_run(cmd, *a, **kw):- captured.append(list(cmd))- return subprocess.CompletedProcess(cmd, 0, stdout="url", stderr="")-- monkeypatch.setattr(release, "get_last_tag", lambda: "v0.27.0")- monkeypatch.setattr(release, "get_last_canary_tag", lambda: None)- monkeypatch.setattr(release, "get_commits", lambda **kw: [{"hash": "a" * 40, "subject": "feat: x", "author": "e"}])- monkeypatch.setattr(release, "generate_changelog", lambda *a, **kw: "notes")- monkeypatch.setattr(release, "resolve_push_remote", lambda r: "origin")- monkeypatch.setattr(release, "remote_github_repo", lambda r: "o/r")- monkeypatch.setattr(- release, "git_result",- lambda *a, **kw: subprocess.CompletedProcess(a, 1 if "rev-parse" in a else 0, "", ""),- )- monkeypatch.setattr(release, "git", lambda *a, **kw: "")- monkeypatch.setattr(release, "REPO_ROOT", tmp_path)- monkeypatch.setattr(release.shutil, "which", lambda x: "/usr/bin/gh")- monkeypatch.setattr(subprocess, "run", fake_run)- monkeypatch.delenv("GITHUB_OUTPUT", raising=False)-- release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260818103000", publish=True, remote="origin"))- return captured-- def test_dispatches_the_build_for_the_tag_it_cut(self, monkeypatch, tmp_path):- calls = self._calls(monkeypatch, tmp_path)- dispatch = next(c for c in calls if c[:3] == ["gh", "workflow", "run"])- # get_last_tag is patched to v0.27.0 → the authority's patch+1 math- # cuts v0.27.1-canary.20260818103000.- tag = "v0.27.1-canary.20260818103000"-- assert "desktop-bundled-release.yml" in dispatch- # The tag travels as the INPUT the build reads. The workflow FILE- # itself is dispatched from the default branch — a tag-dispatched- # run scopes actions/cache under refs/heads/refs/tags/<tag>, a- # mangled per-tag scope no later canary can restore.- assert f"tag={tag}" in dispatch- assert "--ref" in dispatch and dispatch[dispatch.index("--ref") + 1] != tag- # Without this the build produces artifacts and attaches nothing.- assert "upload_release=true" in dispatch-- def test_the_draft_exists_before_the_build_starts(self, monkeypatch, tmp_path):- """Ordering is the whole point of dispatching rather than relying- on the tag push: the build's upload step fails on a missing- release, so the draft has to be there first."""- calls = self._calls(monkeypatch, tmp_path)- create = next(i for i, c in enumerate(calls) if c[:3] == ["gh", "release", "create"])- dispatch = next(i for i, c in enumerate(calls) if c[:3] == ["gh", "workflow", "run"])- assert create < dispatch-- def test_stable_dispatch_uses_the_tagged_full_release_gate(self, monkeypatch, tmp_path):- import subprocess-- calls = []- monkeypatch.setattr(release, "REPO_ROOT", tmp_path)- monkeypatch.setattr(release.shutil, "which", lambda _: "gh")- monkeypatch.setattr(release, "_default_branch", lambda _: "main")- monkeypatch.setattr(release.subprocess, "run", lambda cmd, **kw: (- calls.append(cmd) or subprocess.CompletedProcess(cmd, 0, "", "")- ))- assert release.dispatch_desktop_build("v1.2.3", "owner/repo")- command = calls[0]- assert command[:4] == ["gh", "workflow", "run", "stable-release.yml"]- assert command[command.index("--ref") + 1] == "v1.2.3"- assert "tag=v1.2.3" in command- assert "upload_release=true" not in command- with pytest.raises(ValueError):- release.dispatch_desktop_build("v1.2.3/other", "owner/repo")- assert len(calls) == 1-- def test_a_failed_dispatch_does_not_sink_the_release(self, monkeypatch, tmp_path):- """The tag and draft are already pushed by then. Report the manual- command and leave them; raising would strand a half-made release."""- assert release.dispatch_desktop_build.__doc__- monkeypatch.setattr(release.shutil, "which", lambda x: None)- assert release.dispatch_desktop_build("v0.28.0-canary.20260818103000", "o/r") is Falsediff --git a/tests/scripts/test_release_canary_git.py b/tests/scripts/test_release_canary_git.pynew file mode 100644index 00000000000..45d736cf151--- /dev/null+++ b/tests/scripts/test_release_canary_git.py@@ -0,0 +1,116 @@+"""Canary policy on real Git refs; GitHub publication stays an inert boundary."""+from datetime import datetime, timezone+from types import SimpleNamespace+import subprocess++import pytest++from tests.scripts.test_release_tags import release, release_repo # noqa: F401+++def canary_repo(tmp_path, monkeypatch, release_repo):+ git = release_repo+ remote = tmp_path / 'remote.git'+ git('init', '--bare', '-q', str(remote))+ git('remote', 'add', 'origin', 'https://github.com/fixture/release')++ calls = []+ actual_run = subprocess.run++ def run(argv, *args, **kwargs):+ if argv[0] != 'gh':+ if argv[:2] == ['git', 'push']:+ argv = ['git', '-c', f'url.{remote.as_uri()}.insteadOf=https://github.com/fixture/release', *argv[1:]]+ return actual_run(argv, *args, **kwargs)+ calls.append(argv)+ if argv[1:3] == ['release', 'create']:+ assert git('--git-dir', str(remote), 'rev-parse', argv[3] + '^{commit}') == git('rev-parse', 'HEAD')+ elif argv[1:3] == ['workflow', 'run']:+ assert any(c[1:3] == ['release', 'create'] for c in calls)+ else:+ assert argv[1:3] == ['repo', 'view']+ return subprocess.CompletedProcess(argv, 0, stdout='main\n', stderr='')++ monkeypatch.setattr(subprocess, 'run', run)+ which = release.shutil.which+ monkeypatch.setattr(release.shutil, 'which', lambda name: 'gh' if name == 'gh' else which(name))+ monkeypatch.setattr(release, 'generate_changelog', lambda *a, **kw: 'fixture notes')+ monkeypatch.delenv('GITHUB_OUTPUT', raising=False)+ return git, remote, calls++[email protected]('previous,stable_date,admitted', [+ ('v1.2.4-canary.20260818103045', '2026-08-01T00:00:00Z', False),+ ('v1.2.3-canary.20260818103045', '2026-08-01T00:00:00Z', True),+ (None, '2026-06-01T00:00:00Z', False),+ (None, '2026-08-01T00:00:00Z', True),+])+def test_canary_cut_binds_pushed_head_before_draft_and_dispatch(canary_repo, monkeypatch, previous, stable_date, admitted):+ git, remote, calls = canary_repo+ monkeypatch.setenv('GIT_COMMITTER_DATE', stable_date)+ git('commit', '--allow-empty', '-qm', 'stable')+ git('tag', 'v1.2.3')+ if previous:+ git('tag', previous)+ git('commit', '--allow-empty', '-qm', 'feat: next')+ tag = 'v1.2.4-canary.20260818103000'+ args = SimpleNamespace(date='20260818103000', publish=True, no_changelog=True, remote='origin')+ if stable_date.startswith('2026-06'):+ with pytest.raises(SystemExit) as error:+ release.cmd_canary(args)+ assert error.value.code == 1+ else:+ release.cmd_canary(args)+ if not admitted:+ assert calls == []+ assert tag not in git('tag', '--list').splitlines()+ return+ create = next(c for c in calls if c[1:3] == ['release', 'create'])+ assert create[3] == tag and {'--draft', '--prerelease', '--verify-tag'} <= set(create)+ dispatch = next(c for c in calls if c[1:3] == ['workflow', 'run'])+ assert dispatch == ['gh', 'workflow', 'run', 'desktop-bundled-release.yml', '--ref', 'main',+ '-f', f'tag={tag}', '-f', 'upload_release=true', '--repo', 'fixture/release']+ assert git('--git-dir', str(remote), 'rev-parse', tag + '^{commit}') == git('rev-parse', 'HEAD')+ calls.clear()+ release.cmd_canary(args) # existing tag+ args.date = '20260818103100'+ release.cmd_canary(args) # unchanged HEAD+ assert calls == []+++def test_tag_shapes_and_real_prune_cutoff(canary_repo, monkeypatch, capsys):+ git, _, calls = canary_repo+ assert release.canary_tag_for_date('0.27.4', '20260818103000') == 'v0.27.5-canary.20260818103000'+ assert release.canary_tag_for_date('v1.4.0', '20261231235959') == 'v1.4.1-canary.20261231235959'+ tags = ['v0.27.1-canary.20260801', 'v0.27.1-canary.20260801235959',+ 'v0.27.1-canary.20260804', 'v0.27.1-canary.20260804235959',+ 'v0.27.1-canary.invalid', 'v0.27.1', 'v2026.7.20']+ for tag in tags:+ git('tag', tag)+ class Clock(datetime):+ @classmethod+ def now(cls, tz=None):+ return cls(2026, 8, 18, tzinfo=timezone.utc)+ monkeypatch.setattr(release, 'datetime', Clock)+ release.prune_old_canaries(SimpleNamespace(remote='origin', publish=False))+ assert {line.removeprefix('Would delete ') for line in capsys.readouterr().out.splitlines()+ if line.startswith('Would delete ')} == set(tags[:2])+ assert calls == [] and set(git('tag', '--list').splitlines()) == set(tags)+++def test_stable_dispatch_and_failure(monkeypatch, tmp_path):+ calls = []+ monkeypatch.setattr(release, 'REPO_ROOT', tmp_path)+ monkeypatch.setattr(release.shutil, 'which', lambda _: 'gh')+ monkeypatch.setattr(release.subprocess, 'run', lambda cmd, **kw: (+ calls.append(cmd) or subprocess.CompletedProcess(cmd, 0, '', '')))+ assert release.dispatch_desktop_build('v1.2.3', 'owner/repo')+ assert calls == [['gh', 'workflow', 'run', 'stable-release.yml', '--ref', 'v1.2.3',+ '-f', 'tag=v1.2.3', '--repo', 'owner/repo']]+ with pytest.raises(ValueError):+ release.dispatch_desktop_build('v1.2.3/other', 'owner/repo')+ monkeypatch.setattr(release.subprocess, 'run', lambda cmd, **kw: subprocess.CompletedProcess(cmd, 1, '', 'refused'))+ assert release.dispatch_desktop_build('v1.2.3', 'owner/repo') is False+ monkeypatch.setattr(release.shutil, 'which', lambda _: None)+ assert release.dispatch_desktop_build('v1.2.4-canary.20260818103000', 'owner/repo') is Falsediff --git a/tests/scripts/test_release_darwin.py b/tests/scripts/test_release_darwin.pyindex 195bd031970..863aee3d53d 100644--- a/tests/scripts/test_release_darwin.py+++ b/tests/scripts/test_release_darwin.py@@ -19,7 +19,6 @@ from scripts.releases.darwin import (mac_feed_references,merge_mac_feeds,parse_mac_feed,- publish_mac_feed,)@@ -54,21 +53,6 @@ def base64_sha512(data: bytes) -> str:return __import__("base64").b64encode(hashlib.sha512(data).digest()).decode("ascii")-def test_never_overwrites_a_published_macos_artifact_on_same_tag_rerun(r2_server):- name = "HermesBundled-0.28.0-mac-arm64.zip"- existing = b"already published artifact"- key = f"releases/tag/v0.28.0/{name}"- r2_server.store[key] = (existing, '"etag-1"')- with tempfile.NamedTemporaryFile(delete=False) as handle:- handle.write(existing)- path = handle.name- try:- r2.put("v0.28.0", name, path, immutable=True)- finally:- os.unlink(path)- # The immutable bytes are untouched and the conflict was verified, not ignored.- assert r2_server.store[key][0] == existing-def test_real_prune_protects_live_macos_artifacts_and_fails_closed(r2_server, monkeypatch):legs, _bytes = _inputs("0.28.0-canary.20200101000000")@@ -152,62 +136,6 @@ def test_semver_grammar_rejects_non_release_versions():compare("nonsense", "0.28.0")-def test_publish_verifies_artifacts_before_conditional_write_and_readback():- plan = merge_mac_feeds(_inputs()[0], "v0.28.0")- live = {"text": merge_mac_feeds(_inputs("0.27.0")[0], "v0.27.0")["text"], "etag": "old"}- events = []-- def read(_key):- return live-- def verify(key, _file=None):- events.append(key)-- def write(key, text, etag):- assert etag == "old"- events.append(key)- live.clear()- live.update({"text": text, "etag": "new"})-- publish_mac_feed(plan, {"read": read, "verify": verify, "write": write})- assert events[-1] == plan["key"]- assert len(events) == 3-- write_calls = []-- def fail_write(key, text, etag):- write_calls.append(key)-- # Downgrade rejection: nothing written.- with pytest.raises(ValueError, match="backward"):- publish_mac_feed(- merge_mac_feeds(_inputs("0.27.0")[0], "v0.27.0"),- {"read": read, "verify": verify, "write": fail_write},- )- assert write_calls == []- # Corrupt bytes abort before the pointer write.- def corrupt_verify(_key, _file=None):- raise ValueError("corrupt bytes")-- with pytest.raises(ValueError, match="corrupt bytes"):- publish_mac_feed(plan, {"read": lambda _k: None, "verify": corrupt_verify, "write": fail_write})- assert write_calls == []---def test_same_version_identical_feed_is_a_noop():- plan = merge_mac_feeds(_inputs()[0], "v0.28.0")- live = {"text": plan["text"], "etag": "same"}- calls = []- publish_mac_feed(- plan,- {- "read": lambda _k: live,- "verify": lambda k: calls.append(k),- "write": lambda k, t, e: calls.append(("write", k)),- },- )- assert calls == [] # identical published version → no writes at all-def test_finalize_uses_the_real_signed_transport_and_publishes_last(r2_server):with tempfile.TemporaryDirectory() as dir_path:@@ -259,3 +187,43 @@ def test_finalize_rejects_a_downgrade_over_the_live_feed(r2_server):def test_finalize_rejects_unknown_variant():with pytest.raises(ValueError, match="variant"):darwin.finalize(tag="v0.28.0", dir=".", variant="dark")++[email protected]('fault', ['identical', 'different', 'corrupt-artifact', 'stale-etag', 'readback', 'upgrade'])+def test_finalize_live_feed_faults(tmp_path, r2_server, fault):+ legs, content = _inputs()+ for name, text in legs.items():+ (tmp_path / name).write_text(text, encoding='utf-8')+ r2_server.store.update({key: (value, '"e"') for key, value in content.items()})+ key = 'releases/darwin/stable/stable-mac.yml'+ live = merge_mac_feeds(_inputs('0.28.0' if fault in {'identical', 'different'} else '0.27.0')[0],+ 'v0.28.0' if fault in {'identical', 'different'} else 'v0.27.0')['text']+ if fault == 'different':+ live = live.replace('two lines', 'other notes')+ r2_server.store[key] = (live.encode(), '"live"')+ if fault == 'corrupt-artifact':+ r2_server.store[next(iter(content))] = (b'corrupt', '"e"')+ if fault == 'stale-etag':+ r2_server.race_key = key+ if fault == 'readback':+ r2_server.corrupt_put = key+ errors = {'different': (ValueError, 'different artifacts'),+ 'corrupt-artifact': (ValueError, 'checksum mismatch'),+ 'stale-etag': (r2.R2RequestError, '412'), 'readback': (ValueError, 'readback differs')}+ if fault in errors:+ error, message = errors[fault]+ with pytest.raises(error, match=message):+ darwin.finalize(tag='v0.28.0', dir=str(tmp_path))+ else:+ darwin.finalize(tag='v0.28.0', dir=str(tmp_path))+ puts = [headers for method, _, headers in r2_server.requests if method == 'PUT']+ if fault in {'identical', 'different', 'corrupt-artifact'}:+ assert puts == [] and r2_server.store[key][0] == live.encode()+ else:+ assert len(puts) == 1 and puts[0]['If-Match'] == '"live"'+ if fault == 'stale-etag':+ assert r2_server.store[key] == (live.encode(), '"raced"')+ elif fault == 'upgrade':+ assert parse_mac_feed(r2_server.store[key][0].decode())['version'] == '0.28.0'+ elif fault == 'readback':+ assert [method for method, path, _ in r2_server.requests if path.endswith(key)] == ['GET', 'PUT', 'HEAD', 'GET']diff --git a/tests/scripts/test_release_docker.py b/tests/scripts/test_release_docker.pydeleted file mode 100644index 14ef9a7b291..00000000000--- a/tests/scripts/test_release_docker.py+++ /dev/null@@ -1,91 +0,0 @@-"""Tests for scripts/releases/docker.py — the staged Docker release contract."""-from __future__ import annotations--import importlib-import json-import subprocess-import sys-from pathlib import Path--import pytest--docker = importlib.import_module("scripts.releases.docker")--TAG = "v1.2.3"-COMMIT = "a" * 40-DIGESTS = {"amd64": "b" * 64, "arm64": "c" * 64}---def module_root() -> Path:- return Path(docker.__file__).resolve().parent.parent.parent---def test_build_manifest_roundtrip_and_identity_rejection() -> None:- manifest = docker.build_manifest(TAG, COMMIT, DIGESTS)- parsed = docker.parse_manifest(json.dumps(manifest).encode())- docker.verify_manifest(parsed, TAG, COMMIT)- with pytest.raises(docker.DockerReleaseError):- docker.verify_manifest(parsed, "v1.2.4", COMMIT)- with pytest.raises(docker.DockerReleaseError):- docker.verify_manifest(parsed, TAG, "b" * 40)---def test_manifest_requires_both_arches() -> None:- with pytest.raises(docker.DockerReleaseError):- docker.build_manifest(TAG, COMMIT, {"amd64": DIGESTS["amd64"]})- bad = dict(DIGESTS)- bad["arm64"] = "z" * 64- with pytest.raises(docker.DockerReleaseError):- docker.build_manifest(TAG, COMMIT, bad)---def test_manifest_archive_hashes_optional_but_covering() -> None:- manifest = docker.build_manifest(TAG, COMMIT, DIGESTS, {"amd64": "d" * 64, "arm64": "e" * 64})- assert manifest["archives"] == {"amd64": "d" * 64, "arm64": "e" * 64}- with pytest.raises(docker.DockerReleaseError):- docker.build_manifest(TAG, COMMIT, DIGESTS, {"amd64": "d" * 64})- with pytest.raises(docker.DockerReleaseError):- docker.build_manifest(TAG, COMMIT, DIGESTS, {"amd64": "d" * 64, "riscv64": "e" * 64})---def test_parse_manifest_rejects_garbage() -> None:- with pytest.raises(docker.DockerReleaseError):- docker.parse_manifest(b"not json")- with pytest.raises(docker.DockerReleaseError):- docker.parse_manifest(json.dumps({"schema": 2}).encode())---def test_sha256_file(tmp_path: Path) -> None:- blob = tmp_path / "image.tar"- blob.write_bytes(b"payload")- assert docker.sha256_file(str(blob)) == __import__("hashlib").sha256(b"payload").hexdigest()---def test_cli_manifest_and_verify(tmp_path: Path, module_root: Path) -> None:- out = tmp_path / "manifest.json"- proc = subprocess.run(- [sys.executable, "-m", "scripts.releases.docker", "manifest",- "--tag", TAG, "--commit", COMMIT,- "--digest-amd64", DIGESTS["amd64"], "--digest-arm64", DIGESTS["arm64"]],- cwd=module_root, capture_output=True, text=True,- )- assert proc.returncode == 0, proc.stderr- out.write_text(proc.stdout)- parsed = json.loads(proc.stdout)- assert parsed["digests"] == DIGESTS-- verify = subprocess.run(- [sys.executable, "-m", "scripts.releases.docker", "verify",- "--tag", TAG, "--commit", COMMIT, str(out)],- cwd=module_root, capture_output=True, text=True,- )- assert verify.returncode == 0, verify.stderr-- bad = subprocess.run(- [sys.executable, "-m", "scripts.releases.docker", "verify",- "--tag", "v9.9.9", "--commit", COMMIT, str(out)],- cwd=module_root, capture_output=True, text=True,- )- assert bad.returncode == 1- assert "::error::" in bad.stderrdiff --git a/tests/scripts/test_release_docker_cli.py b/tests/scripts/test_release_docker_cli.pynew file mode 100644index 00000000000..99516c30941--- /dev/null+++ b/tests/scripts/test_release_docker_cli.py@@ -0,0 +1,51 @@+"""Docker receipt CLI validates identity and hashes actual local archive bytes."""+import copy+import hashlib+import json+from pathlib import Path+import subprocess+import sys+++ROOT = Path(__file__).resolve().parents[2]+++def test_cli_manifest_and_verify(tmp_path):+ identity = ['--tag', 'v1.2.3', '--commit', 'a' * 40]+ digests = ['--digest-amd64', 'b' * 64, '--digest-arm64', 'c' * 64]+ archives = []+ expected = {}+ for arch, data in [('amd64', b'first archive'), ('arm64', b'second archive')]:+ path = tmp_path / f'{arch}.tar'+ path.write_bytes(data)+ archives.extend([f'--archive-{arch}', str(path)])+ expected[arch] = hashlib.sha256(data).hexdigest()++ def cli(*args):+ return subprocess.run([sys.executable, '-m', 'scripts.releases.docker', *args],+ cwd=ROOT, capture_output=True, text=True, encoding='utf-8', timeout=30)++ for extra in ([], archives):+ result = cli('manifest', *identity, *digests, *extra)+ assert result.returncode == 0, result.stderr+ manifest = json.loads(result.stdout)+ assert manifest['digests'] == {'amd64': 'b' * 64, 'arm64': 'c' * 64}+ assert manifest.get('archives') == (expected if extra else None)+ out = tmp_path / 'manifest.json'+ out.write_text(result.stdout, encoding='utf-8')+ assert cli('verify', *identity, str(out)).returncode == 0+ for extra in (archives[:2], ['--digest-arm64', 'z' * 64]):+ result = cli('manifest', *identity, *digests, *extra)+ assert result.returncode == 1 and '::error::' in result.stderr+ for change in [+ {'tag': 'v1.2.4'}, {'commit': 'b' * 40}, {'schema': 2},+ {'digests': {'amd64': 'b' * 64}}, {'digests': {'amd64': 'b' * 64, 'arm64': 'z' * 64}},+ {'archives': {'amd64': 'd' * 64}}, {'archives': {'amd64': 'd' * 64, 'riscv64': 'e' * 64}},+ {'list-digest': 'sha256:wrong'}, None,+ ]:+ bad = copy.deepcopy(manifest)+ if change:+ bad.update(change)+ out.write_text(json.dumps(bad) if change else 'not json', encoding='utf-8')+ result = cli('verify', *identity, str(out))+ assert result.returncode == 1 and '::error::' in result.stderrdiff --git a/tests/scripts/test_release_handoff.py b/tests/scripts/test_release_handoff.pyindex 4991c0673a3..1f03117065e 100644--- a/tests/scripts/test_release_handoff.py+++ b/tests/scripts/test_release_handoff.py@@ -4,81 +4,86 @@ import jsonimport pytest-from scripts.releases import r2+from scripts.releases import handoff, r2from tests.scripts.test_release_r2 import r2_server # noqa: F401[email protected]('tag', ['v1.2.3', 'v1.2.3-canary.20260908232538'])-def test_stage_and_fetch_bind_tag_commit_and_files_without_feed_writes(tmp_path, r2_server, tag):- from scripts.releases import handoff-[email protected]('tag', ['v1.2.3', 'v1.2.3-canary.20260908232538', None])+def test_stage_and_fetch_bind_tag_commit_and_files_without_feed_writes(tmp_path, monkeypatch, r2_server, tag):commit = "a" * 40+ identity = ['--tag', tag, '--commit', commit] if tag else ['--commit-build', commit]+ prefix = f'releases/tag/{tag}/' if tag else f'releases/commit/{commit}/'+ monkeypatch.setenv('GITHUB_SHA', 'c' * 40)root = tmp_path / "built"root.mkdir()data = b"multi-chunk package transport fixture\n" * 90000(root / "app.msix").write_bytes(data)(root / "Store-app.msix").write_bytes(b"store transport fixture")(root / "metadata-windows-x64.json").write_text("{}", encoding="utf-8")- nested = root / "apt" / "dists" / "hermes-stable" / "InRelease"+ nested = root / "apt" / "pool build" / "InRelease"nested.parent.mkdir(parents=True)nested.write_bytes(b"APT index transport fixture")- handoff.main(["stage", "--tag", tag, "--commit", commit, "--name", "win32-x64",+ handoff.main(["stage", *identity, "--name", "win32-x64","--root", str(root), "--include", "*.msix", "--include", "metadata-*.json", "--include", "apt/**/*"])- receipt_key = f"releases/tag/{tag}/handoff-win32-x64.json"+ receipt_key = prefix + 'handoff-win32-x64.json'receipt = json.loads(r2_server.store[receipt_key][0])- assert receipt["tag"] == tag and receipt["commit"] == commit+ assert receipt['schema'] == (1 if tag else 2) and receipt['commit'] == commit+ assert receipt['tag'] == tag if tag else 'tag' not in receiptassert {row["path"] for row in receipt["files"]} == {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}- assert all(key.startswith(f"releases/tag/{tag}/") for key in r2_server.store)+ assert all(key.startswith(prefix) for key in r2_server.store)puts = [path for method, path, _ in r2_server.requests if method == "PUT"]assert puts[-1].endswith(receipt_key)assert all(headers.get("If-None-Match") == "*" for method, _, headers in r2_server.requests if method == "PUT")downloaded = tmp_path / "downloaded"- handoff.main(["fetch", "--tag", tag, "--commit", commit, "--name", "win32-x64",+ handoff.main(["fetch", *identity, "--name", "win32-x64","--root", str(downloaded), "--include", "*.msix"])assert (downloaded / "app.msix").read_bytes() == dataassert (downloaded / "Store-app.msix").read_bytes() == b"store transport fixture"assert not (downloaded / "metadata-windows-x64.json").exists()- handoff.stage(tag, commit, "win32-x64", root, ["*.msix", "metadata-*.json", "apt/**/*"])- handoff.fetch(tag, commit, ["win32-x64"], downloaded, ["apt/*"])+ handoff.main(['stage', *identity, *([] if tag else ['--commit', commit]), '--name', 'win32-x64',+ '--root', str(root), '--include', '*.msix', '--include', 'metadata-*.json', '--include', 'apt/**/*'])+ handoff.main(['fetch', *identity, '--name', 'win32-x64', '--root', str(downloaded), '--include', 'apt/*'])assert (downloaded / nested.relative_to(root)).read_bytes() == nested.read_bytes()- with pytest.raises(ValueError, match="identity"):- handoff.fetch(tag, "b" * 40, ["win32-x64"], tmp_path / "wrong")+ fetch = lambda target: handoff.main(['fetch', *identity, '--name', 'win32-x64', '--root', str(target)])+ for changed in ({'schema': 2 if tag else 1}, {'commit': 'b' * 40}, {'tag': 'v9.9.9'}, {'name': 'wrong'}):+ r2_server.store[receipt_key] = (json.dumps({**receipt, **changed}).encode(), '"e"')+ with pytest.raises(ValueError, match='identity') as error:+ fetch(tmp_path / 'wrong')+ assert not isinstance(error.value, handoff.MissingReceipt)- for bad_path in ("../outside", "C:/outside", "dir\\outside", "a//b", "./a", "a%2fb", "a:b", "a?b", "a#b"):+ for bad_path in ("../outside", "C:/outside", "dir\\outside", "a//b", "./a", "a%2fb", "a:b", "a?b", "a#b", '', '/abs.msix', 'NUL'):bad = copy.deepcopy(receipt)bad["files"][0]["path"] = bad_pathr2_server.store[receipt_key] = (json.dumps(bad).encode(), '"e"')r2_server.requests.clear()with pytest.raises(ValueError, match="path"):- handoff.fetch(tag, commit, ["win32-x64"], tmp_path / "unsafe")+ fetch(tmp_path / 'unsafe')assert len(r2_server.requests) == 1+ bad = copy.deepcopy(receipt)+ bad['files'] += [{**bad['files'][0], 'path': bad['files'][0]['path'].upper()}]+ r2_server.store[receipt_key] = (json.dumps(bad).encode(), '"e"')+ with pytest.raises(ValueError, match='Duplicate'):+ fetch(tmp_path / 'duplicate')r2_server.store[receipt_key] = (json.dumps(receipt).encode(), '"e"')- r2_server.store[f"releases/tag/{tag}/app.msix"] = (b"different bytes", '"e"')+ r2_server.store[prefix + 'app.msix'] = (b"different bytes", '"e"')with pytest.raises(ValueError, match="checksum mismatch"):- handoff.fetch(tag, commit, ["win32-x64"], downloaded)+ fetch(downloaded)assert (downloaded / "app.msix").read_bytes() == data-def test_failed_stage_never_publishes_a_receipt_or_channel(tmp_path, monkeypatch, r2_server):- from scripts.releases import handoff-[email protected]('commit_only', [False, True])+def test_failed_stage_never_publishes_a_receipt_or_channel(tmp_path, r2_server, commit_only):tag, commit = "v1.2.3", "a" * 40(tmp_path / "one.msix").write_bytes(b"first")(tmp_path / "two.msix").write_bytes(b"second")- real_put = r2.put-- def fail_second(**kwargs):- # 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)-- monkeypatch.setattr(r2, "put", fail_second)- with pytest.raises(RuntimeError, match="interrupted"):- handoff.stage(tag, commit, "win32-x64", tmp_path, ["*.msix"])- assert set(r2_server.store) == {f"releases/tag/{tag}/one.msix"}+ prefix = f'releases/commit/{commit}/' if commit_only else f'releases/tag/{tag}/'+ identity = ['--commit-build', commit] if commit_only else ['--tag', tag, '--commit', commit]+ r2_server.fail_put = prefix + 'two.msix'+ with pytest.raises(r2.R2RequestError):+ handoff.main(['stage', *identity, '--name', 'win32-x64', '--root', str(tmp_path), '--include', '*.msix'])+ assert set(r2_server.store) == {prefix + 'one.msix'}r2_server.requests.clear()with pytest.raises(ValueError, match="No files"):handoff.stage(tag, commit, "win32-x64", tmp_path, ["*.zip"])@@ -122,17 +127,28 @@ def test_shared_receipt_files_download_once_and_conflicts_leave_targets_intact(tassert {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"+def test_commit_identity_and_simultaneous_namespaces(tmp_path, r2_server):+ commit = 'a' * 40+ for bad in ('abc', commit[:39], 'g' * 40, '', None, ' ' * 40):+ with pytest.raises(ValueError):+ handoff.validate_commit_identity(bad, 'win32-x64')+ with pytest.raises(ValueError):+ handoff.validate_commit_identity(commit, 'Bad Name')+ (tmp_path / 'app.msix').write_bytes(b'commit bytes')+ args = ['stage', '--commit-build', commit, '--name', 'win32-x64', '--root', str(tmp_path), '--include', '*.msix']+ for conflict in (['--commit', 'b' * 40], ['--tag', 'v1.2.3']):+ with pytest.raises(SystemExit):+ handoff.main([*args, *conflict])+ assert r2_server.requests == []+ handoff.main(args)+ (tmp_path / 'app.msix').write_bytes(b'tag bytes')+ handoff.stage('v1.2.3', commit, 'win32-x64', tmp_path, ['*.msix'])+ for identity, data in ((['--commit-build', commit], b'commit bytes'),+ (['--tag', 'v1.2.3', '--commit', commit], b'tag bytes')):+ handoff.main(['fetch', *identity, '--name', 'win32-x64', '--root', str(tmp_path / 'out')])+ assert (tmp_path / 'out/app.msix').read_bytes() == data+ with pytest.raises(handoff.MissingReceipt):+ handoff.read_commit_receipt('b' * 40, 'win32-x64')+ r2_server.store[f'releases/commit/{commit}/handoff-win32-x64.json'] = (b'not-json', '"e"')+ with pytest.raises(json.JSONDecodeError):+ handoff.read_commit_receipt(commit, 'win32-x64')diff --git a/tests/scripts/test_release_handoff_commit.py b/tests/scripts/test_release_handoff_commit.pydeleted file mode 100644index 482c5764262..00000000000--- a/tests/scripts/test_release_handoff_commit.py+++ /dev/null@@ -1,329 +0,0 @@-"""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; other enabled legs are Not built, and Linux is Disabled.- 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 bundle (MSIXBUNDLE)" in text- assert "Store" not 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_release_promotion.py b/tests/scripts/test_release_promotion.pydeleted file mode 100644index 38005c50ddd..00000000000--- a/tests/scripts/test_release_promotion.py+++ /dev/null@@ -1,73 +0,0 @@-"""Promotion writes pointers only after verified candidate content exists."""-import hashlib-import io-import json-import xml.etree.ElementTree as ET-from pathlib import Path--import pytest--from scripts.bundles import release_artifacts as artifacts-from scripts.releases import r2-from tests.scripts.test_release_r2 import r2_server # noqa: F401---def test_publish_and_promote_use_the_same_content_before_any_channel_write(tmp_path, monkeypatch, r2_server):- tag, commit = 'v1.2.3', 'a' * 40- base = 'https://releases.example'- content = {- 'app.msixbundle': b'windows transport bytes',- 'arm64.zip': b'mac arm transport bytes', 'x64.zip': b'mac x64 transport bytes',- 'apt/pool/package.deb': b'deb transport bytes',- 'apt/dists/hermes-stable/InRelease': b'signed-index transport bytes',- }- files = [{'path': name, 'url': f'{base}/releases/tag/{tag}/{name}', 'sha256': hashlib.sha256(data).hexdigest()} for name, data in content.items()]- by_name = {item['path']: item for item in files}- packages = []- for platform in ('windows', 'macos'):- for arch in ('x64', 'arm64'):- file = by_name['app.msixbundle' if platform == 'windows' else arch + '.zip']- packages.append({'platform': platform, 'arch': arch, 'tag': tag, 'commit': commit, 'identity': 'App',- 'version': '1.2.3.0' if platform == 'windows' else '1.2.3',- **({'publisher': 'CN=Test', 'applicationId': 'App'} if platform == 'windows' else {'teamId': 'ABCDEFGHIJ'}),- 'artifact': {'url': file['url'], 'sha256': file['sha256']}})- manifest = {'schema': 1, 'tag': tag, 'commit': commit, 'files': files, 'packages': packages}-- class Response(io.BytesIO):- def geturl(self):- return base-- def fetch(url, **kwargs):- if '/releases/tag/' in url:- return Response(content[url.split(f'/releases/tag/{tag}/')[1]])- return Response(r2_server.store[url.split(base + '/')[1]][0])-- monkeypatch.setattr('urllib.request.urlopen', fetch)- artifacts.publish(manifest, tmp_path / 'publish', base)- assert 'releases/termux/stable/pool/package.deb' in r2_server.store- assert not any(key.endswith(('.appinstaller', 'InRelease')) for key in r2_server.store)-- events = []- real_put = r2.put- def put(**kwargs):- events.append(kwargs['key'])- real_put(**kwargs)- monkeypatch.setattr(r2, 'put', put)- monkeypatch.setattr(r2, 'finalize', lambda **kwargs: events.append('mac-feed'))- artifacts.promote(manifest, tmp_path / 'promote', base)- assert events[0] == 'mac-feed'- assert events[-1] == 'releases/termux/stable/dists/hermes-stable/InRelease'- assert 'releases/win32/stable/stable.appinstaller' in r2_server.store- descriptor = ET.fromstring(r2_server.store['releases/win32/stable/stable.appinstaller'][0])- windows = next(row for row in packages if row['platform'] == 'windows')- assert descriptor.attrib == {'Uri': f'{base}/releases/win32/stable/stable.appinstaller', 'Version': windows['version']}- assert descriptor.find('{*}MainBundle').attrib == {- 'Name': windows['identity'], 'Publisher': windows['publisher'],- 'Version': windows['version'], 'Uri': windows['artifact']['url'],- }-- events.clear()- content['app.msixbundle'] = b'changed artifact'- with pytest.raises(ValueError, match='digest mismatch'):- artifacts.promote(manifest, tmp_path / 'broken', base)- assert events == []diff --git a/tests/scripts/test_release_r2.py b/tests/scripts/test_release_r2.pyindex b4cde7358e2..f6d75c2bdd3 100644--- a/tests/scripts/test_release_r2.py+++ b/tests/scripts/test_release_r2.py@@ -17,11 +17,9 @@ from __future__ import annotationsimport base64import hashlib-import io-import json+import html+import http.clientimport os-import re-import socketimport subprocessimport sysimport threading@@ -36,25 +34,17 @@ import pytestfrom scripts.releases import r2from scripts.releases.r2 import (auth_header,- cache_control_for,- canary_doomed_keys,canonical_query,canonical_request,- channel_for_tag,channel_page_key_for,commit_page_key_for,commit_prefix_for,- content_type_for,encode_key_path,- feed_dir_for,feed_referenced_keys,- parse_list_xml,public_base_url,public_url_for,- publish_feed_uploads,referenced_feed_bundle_filenames,rfc3986_encode,- staging_key_for,stale_feed_bundle_keys,)@@ -73,78 +63,32 @@ def _auth(**kwargs):# ── SigV4 vectors ───────────────────────────────────────────────────────────-def test_get_vanilla_matches_the_aws_test_suite_vector():- authz = _auth(- method="GET",- host="example.com",- path="/",- query="",- headers={"host": "example.com", "x-amz-date": NOW},- payload_hash=EMPTY_SHA,- region="us-east-1",- service="service",- )- assert authz == (- "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, "- "SignedHeaders=host;x-amz-date, "- "Signature=33399fd3d4a9d6104710c7c04005f7c959f8b1f8bf41b823587ed36b079e453f"- )---def test_r2_put_payload_matches_botocore():- body_hash = "44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072" # sha256("Welcome to Amazon S3.")- host = "abc123.r2.cloudflarestorage.com"- authz = _auth(- method="PUT",- host=host,- path="/hermes-releases/HermesBundled-0.28.0-win-x64.msix",- query="",- headers={"host": host, "x-amz-date": NOW, "x-amz-content-sha256": body_hash},- payload_hash=body_hash,- )- assert authz == (- "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/auto/s3/aws4_request, "- "SignedHeaders=host;x-amz-content-sha256;x-amz-date, "- "Signature=05ba50acfb54042fac330848af50877e5fb477c4f2063c2f77f9cc80855eb1e9"- )---def test_r2_list_matches_botocore():- query = canonical_query(- {"list-type": "2", "prefix": "HermesBundled-0.28.0-", "max-keys": "1000"}- )- assert query == "list-type=2&max-keys=1000&prefix=HermesBundled-0.28.0-"- host = "abc123.r2.cloudflarestorage.com"- authz = _auth(- method="GET",- host=host,- path="/hermes-releases",- query=query,- headers={"host": host, "x-amz-date": NOW, "x-amz-content-sha256": EMPTY_SHA},- payload_hash=EMPTY_SHA,- )- assert authz == (- "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/auto/s3/aws4_request, "- "SignedHeaders=host;x-amz-content-sha256;x-amz-date, "- "Signature=3ec423c452a318664c85fbcc25667ad07201aedce688e3bb6b345b4baaa39d90"- )---def test_r2_delete_matches_botocore():- host = "abc123.r2.cloudflarestorage.com"- authz = _auth(- method="DELETE",- host=host,- path="/hermes-releases/HermesBundled-0.28.0-canary.20260818-win-arm64.msix",- query="",- headers={"host": host, "x-amz-date": NOW, "x-amz-content-sha256": EMPTY_SHA},- payload_hash=EMPTY_SHA,- )- assert authz == (- "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/auto/s3/aws4_request, "- "SignedHeaders=host;x-amz-content-sha256;x-amz-date, "- "Signature=ec5ccb76f701193b28aaca052cabbf2f084e9c71ffc64b872fa51d4e70dc6e55"- )[email protected]('method,path,query,payload,scope,signature', [+ ('GET', '/', {}, EMPTY_SHA, 'us-east-1/service',+ '33399fd3d4a9d6104710c7c04005f7c959f8b1f8bf41b823587ed36b079e453f'),+ ('PUT', '/hermes-releases/HermesBundled-0.28.0-win-x64.msix', {},+ '44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072', 'auto/s3',+ '05ba50acfb54042fac330848af50877e5fb477c4f2063c2f77f9cc80855eb1e9'),+ ('GET', '/hermes-releases', {'list-type': '2', 'prefix': 'HermesBundled-0.28.0-', 'max-keys': '1000'},+ EMPTY_SHA, 'auto/s3', '3ec423c452a318664c85fbcc25667ad07201aedce688e3bb6b345b4baaa39d90'),+ ('DELETE', '/hermes-releases/HermesBundled-0.28.0-canary.20260818-win-arm64.msix', {},+ EMPTY_SHA, 'auto/s3', 'ec5ccb76f701193b28aaca052cabbf2f084e9c71ffc64b872fa51d4e70dc6e55'),+])+def test_independent_sigv4_vectors(method, path, query, payload, scope, signature):+ host = 'example.com' if scope == 'us-east-1/service' else 'abc123.r2.cloudflarestorage.com'+ headers = {'host': host, 'x-amz-date': NOW}+ signed = 'host;x-amz-date'+ if scope == 'auto/s3':+ headers['x-amz-content-sha256'] = payload+ signed = 'host;x-amz-content-sha256;x-amz-date'+ encoded = canonical_query(query)+ if query:+ assert encoded == 'list-type=2&max-keys=1000&prefix=HermesBundled-0.28.0-'+ region, service = scope.split('/')+ assert _auth(method=method, host=host, path=path, query=encoded, headers=headers,+ payload_hash=payload, region=region, service=service) == (+ f'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/{scope}/aws4_request, '+ f'SignedHeaders={signed}, Signature={signature}')# ── Encoding / layout helpers ───────────────────────────────────────────────@@ -159,48 +103,6 @@ def test_encode_key_path_encodes_segment_wise_preserves_separators():assert encode_key_path("a b/c d") == "a%20b/c%20d"-def test_parse_list_xml_extracts_keys_truncation_token_entities():- xml = (- '<?xml version="1.0" encoding="UTF-8"?>\n'- '<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n'- " <Name>hermes-releases</Name>\n <Prefix></Prefix>\n"- " <KeyCount>3</KeyCount>\n <MaxKeys>1000</MaxKeys>\n"- " <IsTruncated>true</IsTruncated>\n"- " <Contents><Key>HermesBundled-0.28.0-win-x64.msix</Key>"- "<LastModified>2026-08-18T00:00:00Z</LastModified><Size>123</Size></Contents>\n"- " <Contents><Key>a&b.msix</Key>"- "<LastModified>2026-08-18T00:00:00Z</LastModified><Size>1</Size></Contents>\n"- " <Contents><Key>latest.yml</Key>"- "<LastModified>2026-08-18T00:00:00Z</LastModified><Size>2</Size></Contents>\n"- " <NextContinuationToken>abc+def/=</NextContinuationToken>\n"- "</ListBucketResult>"- )- parsed = parse_list_xml(xml)- assert parsed["keys"] == ["HermesBundled-0.28.0-win-x64.msix", "a&b.msix", "latest.yml"]- assert parsed["truncated"] is True- assert parsed["nextToken"] == "abc+def/="---def test_canary_doomed_keys_dates_by_the_key_suffix():- keys = [- "releases/tag/v0.28.0/HermesBundled-0.28.0-win-x64.msix", # stable — never doomed- "releases/tag/v0.28.0-canary.20260801/HermesBundled-0.28.0-canary.20260801-win-x64.msix",- "releases/tag/v0.28.0-canary.20260818/HermesBundled-0.28.0-canary.20260818-win-x64.msix", # today — kept- "releases/tag/v0.28.0-canary.20260801/HermesBundled-0.28.0-canary.20260801-win-x64.msix.blockmap",- "latest.yml",- "canary.yml",- ]- assert canary_doomed_keys(keys, "20260814") == [- "releases/tag/v0.28.0-canary.20260801/HermesBundled-0.28.0-canary.20260801-win-x64.msix",- "releases/tag/v0.28.0-canary.20260801/HermesBundled-0.28.0-canary.20260801-win-x64.msix.blockmap",- ]---def test_channel_for_tag_maps_stable_vs_canary():- assert channel_for_tag("v0.28.0") == "stable"- assert channel_for_tag("v0.28.0-canary.20260818101010") == "canary"- assert channel_for_tag("v0.28.0-canary.20260818") == "canary"-def test_relative_artifact_path_rejects_windows_reserved_names_without_ntpath(monkeypatch):"""Windows-reserved names must be rejected even when ntpath.isreserved@@ -231,13 +133,6 @@ def test_relative_artifact_path_rejects_windows_reserved_names_without_ntpath(moassert r2.relative_artifact_path(good) == good-def test_staging_key_and_feed_dir_layout_keys():- assert staging_key_for("v0.28.0", "HermesBundled-0.28.0-win-x64.msix") == (- "releases/tag/v0.28.0/HermesBundled-0.28.0-win-x64.msix"- )- assert feed_dir_for("win32", "stable") == "releases/win32/stable"- assert feed_dir_for("darwin", "canary") == "releases/darwin/canary"-def test_download_page_keys_and_public_urls():assert channel_page_key_for("stable") == "releases/stable/index.html"@@ -264,38 +159,31 @@ def test_public_base_url_precedence(monkeypatch):assert public_base_url("https://explicit.example.com/") == "https://explicit.example.com"-def test_content_type_for_maps_msix_and_appinstaller():- assert content_type_for("HermesBundled-0.28.0-win-x64.msix") == "application/msix"- assert content_type_for("HermesBundled-0.28.0-win.msixbundle") == "application/msixbundle"- assert content_type_for("stable.appinstaller") == "application/appinstaller"- assert content_type_for("releases/stable/index.html") == "text/html; charset=utf-8"- assert content_type_for("HermesBundled-0.28.0-mac-x64.dmg") is None- assert content_type_for("latest-mac.yml") is None- # Case-insensitive on the suffix.- assert content_type_for("X.APPINSTALLER") == "application/appinstaller"- assert content_type_for("INDEX.HTML") == "text/html; charset=utf-8"---def test_apt_mutable_metadata_revalidates_immutable_bytes_cache():- feed = "releases/termux/canary"- for name in [- "key.asc",- "dists/hermes-canary/InRelease",- "dists/hermes-canary/Release",- "dists/hermes-canary/main/binary-aarch64/Packages.gz",- ]:- assert cache_control_for(f"{feed}/{name}") == "no-store"- assert cache_control_for(f"{feed}/dists/hermes-canary/main/binary-aarch64/by-hash/SHA256/abcd") == (- "public, max-age=31536000, immutable"- )- assert cache_control_for(f"{feed}/pool/h/hermes-agent_1.2.3_aarch64.deb") == (- "public, max-age=31536000, immutable"- )- assert cache_control_for("releases/win32/stable/stable.appinstaller") == "no-store"- # Downloads pages are mutable pointers, like feed manifests.- assert cache_control_for("releases/stable/index.html") == "no-store"- assert cache_control_for("releases/canary/index.html") == "no-store"- assert cache_control_for(f"releases/commit/{'a' * 40}/index.html") == "no-store"[email protected]('key,content_type,immutable', [+ ('releases/tag/v1.2.3/app.msix', 'application/msix', None),+ ('releases/tag/v1.2.3/app.msixbundle', 'application/msixbundle', None),+ ('releases/win32/stable/X.APPINSTALLER', 'application/appinstaller', None),+ ('releases/win32/stable/stable.appinstaller', 'application/appinstaller', False),+ ('releases/stable/INDEX.HTML', 'text/html; charset=utf-8', False),+ ('releases/canary/index.html', 'text/html; charset=utf-8', False),+ (f'releases/commit/{"a" * 40}/index.html', 'text/html; charset=utf-8', False),+ ('releases/tag/v1.2.3/app.dmg', None, None),+ ('releases/tag/v1.2.3/latest-mac.yml', None, None),+ ('releases/termux/canary/key.asc', 'text/plain', False),+ ('releases/termux/canary/dists/hermes-canary/InRelease', 'text/plain', False),+ ('releases/termux/canary/dists/hermes-canary/Release', 'text/plain', False),+ ('releases/termux/canary/dists/hermes-canary/main/binary-aarch64/Packages.gz', 'application/gzip', False),+ ('releases/termux/canary/dists/hermes-canary/main/binary-aarch64/by-hash/SHA256/abcd', None, True),+ ('releases/termux/canary/pool/h/package.deb', 'application/vnd.debian.binary-package', True),+])+def test_object_headers_on_real_upload(tmp_path, r2_server, key, content_type, immutable):+ file = tmp_path / 'content'+ file.write_bytes(b'header transport fixture')+ r2.put(tag='', key=key, file=file, key_is_full=True)+ assert r2_server.store[key][0] == file.read_bytes()+ headers = next(headers for method, _, headers in r2_server.requests if method == 'PUT')+ assert headers.get('Content-Type') == content_type+ assert headers.get('Cache-Control') == {None: None, False: 'no-store', True: 'public, max-age=31536000, immutable'}[immutable]def test_canonical_request_reads_mixed_case_header_values():@@ -317,47 +205,6 @@ def test_canonical_request_reads_mixed_case_header_values():assert "content-type;host;x-amz-content-sha256;x-amz-date" in canon-# ── C22: artifact first, feed pointer last ──────────────────────────────────--def test_publish_feed_uploads_bundle_before_pointer():- calls = []- publish_feed_uploads(- {- "channelDir": "releases/win32/canary",- "appinstallerName": "canary.appinstaller",- "bundleFilename": "HermesBundled-0.27.2.9-win.msixbundle",- "bundleFile": "C:/rel/HermesBundled-0.27.2.9-win.msixbundle",- "appinstallerFile": "C:/rel/canary.appinstaller",- },- lambda key, file: calls.append([key, file]),- )- assert calls == [- ["releases/win32/canary/HermesBundled-0.27.2.9-win.msixbundle", "C:/rel/HermesBundled-0.27.2.9-win.msixbundle"],- ["releases/win32/canary/canary.appinstaller", "C:/rel/canary.appinstaller"],- ]---def test_publish_feed_uploads_never_writes_pointer_when_bundle_fails():- calls = []-- def upload(key, _file):- calls.append(key)- raise RuntimeError("R2 PUT -> 503")-- with pytest.raises(RuntimeError):- publish_feed_uploads(- {- "channelDir": "releases/win32/stable",- "appinstallerName": "stable.appinstaller",- "bundleFilename": "HermesBundled-0.28.0.0-win.msixbundle",- "bundleFile": "bundle",- "appinstallerFile": "feed",- },- upload,- )- assert calls == ["releases/win32/stable/HermesBundled-0.28.0.0-win.msixbundle"]--# ── C22: canary feed-dir retention (fail-closed, keep-days grace) ───────────CANARY_FEED_XML = (@@ -392,86 +239,16 @@ def test_feed_referenced_keys_protects_bundle_and_absolute_tag_uris():CANARY_DIR = "releases/win32/canary"-OLD_MS = 1785542400 # 2026-08-01T00:00:00Z-FRESH_MS = 1788480000 # 2026-09-03T00:00:00ZCUTOFF_MS = 1787356800 # 2026-08-21T00:00:00Z-def _canary_keys(extra=()):- return [- f"{CANARY_DIR}/canary.appinstaller",- f"{CANARY_DIR}/HermesBundled-0.27.2.9-win.msixbundle", # referenced- f"{CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle", # stale- f"{CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle", # uploaded, not yet pointed- "releases/win32/stable/stable.appinstaller",- "releases/win32/stable/HermesBundled-0.28.0.0-win.msixbundle", # referenced- "releases/win32/stable/HermesBundled-0.27.0.0-win.msixbundle", # stale stable- *extra,- ]---def _last_modified_for(keys, overrides=None):- lm = {k: OLD_MS for k in keys}- lm.update(overrides or {})- return lm---def test_stale_feed_bundle_keys_old_unreferenced_doomed_referenced_and_fresh_kept():- keys = _canary_keys()- lm = _last_modified_for(keys, {f"{CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle": FRESH_MS})- doomed = stale_feed_bundle_keys(keys, {CANARY_DIR: [CANARY_FEED_XML]}, lm, CUTOFF_MS)- assert doomed == [f"{CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle"]---def test_stale_feed_bundle_keys_stable_dirs_never_pruned():- keys = _canary_keys()- lm = _last_modified_for(keys, {f"{CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle": FRESH_MS})- stable_feed = CANARY_FEED_XML.replace("0.27.2.9", "0.28.0.0").replace(- "HermesBundled-0.27.2.9-win", "HermesBundled-0.28.0.0-win"- )- feeds = {CANARY_DIR: [CANARY_FEED_XML], "releases/win32/stable": [stable_feed]}- doomed = stale_feed_bundle_keys(keys, feeds, lm, CUTOFF_MS)- assert doomed == [f"{CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle"]--- "bad",- [- "",- "<html>boom</html>",- None,- '<Foo Uri="https://x/HermesBundled-1-win.msixbundle" />',- '<MainPackage Uri="https://x/old.msixbundle" />',- "<AppInstaller><MainBundle Uri=\"https://x/old.msixbundle\" />",- ],-)-def test_stale_feed_bundle_keys_malformed_manifest_blocks_dir(bad):- keys = _canary_keys()- assert stale_feed_bundle_keys(keys, {CANARY_DIR: [bad]}, _last_modified_for(keys), CUTOFF_MS) == []---def test_stale_feed_bundle_keys_union_protected_one_bad_blocks_all():- second = CANARY_FEED_XML.replace("0.27.2.9", "0.27.3.0").replace(- "HermesBundled-0.27.2.9-win", "HermesBundled-0.27.3.0-win"- )- extra = [f"{CANARY_DIR}/second.appinstaller", f"{CANARY_DIR}/HermesBundled-0.27.3.0-win.msixbundle"]- keys = _canary_keys(extra)- lm = _last_modified_for(keys, {f"{CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle": FRESH_MS})- # Union of both feeds: both referenced bundles kept, the rest pruned.- assert stale_feed_bundle_keys(keys, {CANARY_DIR: [CANARY_FEED_XML, second]}, lm, CUTOFF_MS) == [- f"{CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle"- ]- # ONE unreadable/unrecognized manifest in the dir blocks feed retention.- assert stale_feed_bundle_keys(keys, {CANARY_DIR: [CANARY_FEED_XML, None]}, lm, CUTOFF_MS) == []- assert stale_feed_bundle_keys(keys, {CANARY_DIR: [CANARY_FEED_XML, ""]}, lm, CUTOFF_MS) == []--@pytest.mark.parametrize("unknown", [None, float("nan"), float("inf")])def test_stale_feed_bundle_keys_missing_lastmodified_keeps_object(unknown):- keys = _canary_keys()+ keys = [f'{CANARY_DIR}/unreferenced.msixbundle']metadata = {key: unknown for key in keys}doomed = stale_feed_bundle_keys(keys, {CANARY_DIR: [CANARY_FEED_XML]}, metadata, CUTOFF_MS)assert doomed == []+ assert stale_feed_bundle_keys(keys, {CANARY_DIR: [None]}, {keys[0]: 0}, CUTOFF_MS) == []# ── Real loopback HTTP protocol tests ───────────────────────────────────────@@ -494,13 +271,13 @@ class _R2StubHandler(BaseHTTPRequestHandler):store = self.server.store # type: ignore[attr-defined]self.server.requests.append(("GET", self.path, dict(self.headers))) # type: ignore[attr-defined]if "list-type=2" in self.path:- body = self.server.listing_xml() # type: ignore[attr-defined]+ body = self.server.listing_xml(parse_qs(urlsplit(self.path).query)) # type: ignore[attr-defined]self._send(200, body, {"content-type": "application/xml"})returnkey = self._key()if key in store:- body, ctype = store[key]- headers = {"etag": '"abc"'}+ body, etag = store[key]+ headers = {"etag": etag}if self.headers.get("Range"):headers["content-range"] = f"bytes 0-0/{len(body)}"self._send(206, body[:1], headers)@@ -532,6 +309,8 @@ class _R2StubHandler(BaseHTTPRequestHandler):data = self._read_chunked()key = self._key()query = parse_qs(urlsplit(self.path).query)+ if key == getattr(server, 'fail_put', None):+ return self._send(400, b'Interrupted upload')if "partNumber" in query:state = server.multipartassert query["uploadId"] == ["a+/="]@@ -548,10 +327,15 @@ class _R2StubHandler(BaseHTTPRequestHandler):if self.headers.get("If-None-Match") == "*" and key in server.store:self._send(412, b"Precondition Failed")return- if self.headers.get("If-Match") and self.headers["If-Match"] != server.store.get(key, (b"",))[1]:+ if self.headers.get('If-Match') and key == getattr(server, 'race_key', None):+ server.store[key] = (server.store[key][0], '"raced"')+ if self.headers.get("If-Match") and self.headers["If-Match"] != server.store.get(key, (b"", None))[1]:self._send(412, b"Precondition Failed")returnserver.store[key] = (data, self.headers.get("If-Match", '"new"'))+ if key == getattr(server, 'corrupt_put', None):+ # Keep HEAD size verification valid; only the readback content lies.+ server.store[key] = (b'x' * len(data), '"corrupt"')self._send(200, b"")def do_POST(self):@@ -624,14 +408,24 @@ def r2_server(monkeypatch):server = ThreadingHTTPServer(("127.0.0.1", 0), _R2StubHandler)server.store = {}server.requests = []+ server.page_size = 1000+ server.last_modified = {}server.multipart = SimpleNamespace(parts={}, attempts={}, failure=None, created=0,completed=0, aborted=0, reject_existing=False)- def listing_xml():- parts = ["<?xml version='1.0'?><ListBucketResult><IsTruncated>false</IsTruncated>"]- for key, (body, _etag) in server.store.items():- lm = "2026-08-01T00:00:00Z"- parts.append(f"<Contents><Key>{key}</Key><LastModified>{lm}</LastModified></Contents>")+ def listing_xml(query):+ keys = sorted(key for key in server.store if key.startswith(query.get('prefix', [''])[0]))+ token = query.get('continuation-token', ['0'])[0]+ start = int(token.removeprefix('page+/='))+ end = start + server.page_size+ truncated = end < len(keys)+ parts = [f"<ListBucketResult><IsTruncated>{str(truncated).lower()}</IsTruncated>"]+ for key in keys[start:end]:+ lm = server.last_modified.get(key, '2026-08-01T00:00:00Z')+ modified = f'<LastModified>{lm}</LastModified>' if lm is not None else ''+ parts.append(f'<Contents><Key>{html.escape(key)}</Key>{modified}</Contents>')+ if truncated:+ parts.append(f'<NextContinuationToken>page+/={end}</NextContinuationToken>')parts.append("</ListBucketResult>")return "".join(parts)@@ -647,6 +441,7 @@ def r2_server(monkeypatch):yield serverserver.shutdown()server.server_close()+ thread.join(timeout=5)@pytest.mark.parametrize("failure", [None, "part", "complete", "transient", "disconnect", "lost-response"])@@ -788,57 +583,50 @@ def test_put_immutable_conflict_with_corrupt_remote_fails(r2_server):assert r2_server.store[key][0] == b"corrupt different bytes"-def test_list_prints_keys_and_paginates(r2_server, capsys):- r2_server.store["releases/tag/v0.28.0/a.msix"] = (b"x", '"e"')- r2_server.store["releases/tag/v0.28.0/b.yml"] = (b"y", '"e"')- r2.list_objects(prefix="releases/tag/v0.28.0/")- # (list_objects returns; the CLI prints)- from scripts.releases.r2 import list_objects as _lo-- result = _lo(prefix="releases/tag/v0.28.0/")- assert sorted(result["keys"]) == ["releases/tag/v0.28.0/a.msix", "releases/tag/v0.28.0/b.yml"]- assert "list-type=2" in [r for r in r2_server.requests if r[0] == "GET"][0][1]---def test_prune_canaries_dry_run_issues_no_delete(r2_server, capsys, monkeypatch):- old_bundle = f"{CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle"- referenced = f"{CANARY_DIR}/HermesBundled-0.27.2.9-win.msixbundle"- r2_server.store[f"{CANARY_DIR}/canary.appinstaller"] = (CANARY_FEED_XML.encode(), '"e"')- r2_server.store[referenced] = (b"bundle", '"e"')- r2_server.store[old_bundle] = (b"stale", '"e"')- r2_server.store["releases/tag/v0.27.2-canary.20260801000000/old.zip"] = (b"z", '"e"')-- monkeypatch.setattr(r2.time, "time", lambda: 1788547200.0) # 2026-09-04- r2.prune(keep_days=14, dry_run=True)- out = capsys.readouterr().out- assert f"would delete r2:{old_bundle}" in out- assert "would delete r2:releases/tag/v0.27.2-canary.20260801000000/old.zip" in out- assert f"would delete r2:{referenced}" not in out- assert "would delete" not in out.split("appinstaller")[0] if ".appinstaller" in out else True- assert not any(r[0] == "DELETE" for r in r2_server.requests)---def test_prune_canaries_real_delete_only_the_doomed(r2_server, capsys, monkeypatch):- old_bundle = f"{CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle"- referenced = f"{CANARY_DIR}/HermesBundled-0.27.2.9-win.msixbundle"- r2_server.store[f"{CANARY_DIR}/canary.appinstaller"] = (CANARY_FEED_XML.encode(), '"e"')- r2_server.store[referenced] = (b"bundle", '"e"')- r2_server.store[old_bundle] = (b"stale", '"e"')- monkeypatch.setattr(r2.time, "time", lambda: 1788547200.0) # 2026-09-04- r2.prune(keep_days=14, dry_run=False)- assert old_bundle not in r2_server.store- assert referenced in r2_server.store- assert f"{CANARY_DIR}/canary.appinstaller" in r2_server.store---def test_prune_fails_closed_when_manifest_unreadable(r2_server, monkeypatch):- r2_server.store[f"{CANARY_DIR}/canary.appinstaller"] = (b"<html>ServiceUnavailable</html>", '"e"')- r2_server.store[f"{CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle"] = (b"stale", '"e"')- monkeypatch.setattr(r2.time, "time", lambda: 1788547200.0) # 2026-09-04- with pytest.raises(RuntimeError, match="refusing to prune"):- r2.prune(keep_days=14, dry_run=False)- # Nothing was deleted.- assert f"{CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle" in r2_server.store+def test_list_cli_paginates_and_decodes_keys(r2_server, capsys):+ r2_server.page_size = 1+ keys = ['releases/tag/v1.2.3/a&b.msix', 'releases/tag/v1.2.3/nested space/b.yml']+ r2_server.store.update({key: (b'x', '"e"') for key in keys})+ r2_server.store['outside.bin'] = (b'outside', '"e"')+ r2_server.last_modified[keys[0]] = '2026-08-18T00:00:00.123Z'+ result = r2.list_objects(prefix='releases/tag/v1.2.3/')+ assert result == {'keys': keys, 'lastModified': {keys[0]: 1787011200, keys[1]: 1785542400}}+ queries = [parse_qs(urlsplit(path).query) for method, path, _ in r2_server.requests if method == 'GET']+ assert len(queries) == 2 and queries[1]['continuation-token'] == ['page+/=1']+ r2.main(['list', '--prefix', 'releases/tag/v1.2.3/'])+ assert capsys.readouterr().out.splitlines() == keys++[email protected]('bad_feed', [None, b'', b'<html>boom</html>',+ b'<Foo Uri="https://x/old.msixbundle" />', b'<MainPackage Uri="https://x/old.msixbundle" />',+ b'<AppInstaller><MainBundle Uri="https://x/old.msixbundle" />'])+def test_real_prune_retention_and_second_feed_failure(r2_server, capsys, bad_feed):+ tag_reference = 'releases/tag/v0.27.2-canary.20260801/live.msixbundle'+ second = f'<AppInstaller><MainBundle Uri="https://cdn.example/{tag_reference}" /></AppInstaller>'+ doomed = {f'{CANARY_DIR}/old.msixbundle', 'releases/tag/v0.27.2-canary.20260801000000/old.zip'}+ kept = {f'{CANARY_DIR}/HermesBundled-0.27.2.9-win.msixbundle', f'{CANARY_DIR}/live.msixbundle',+ f'{CANARY_DIR}/fresh.msixbundle', f'{CANARY_DIR}/unknown.msixbundle', tag_reference,+ 'releases/win32/stable/old.msixbundle', 'releases/unknown/old.msixbundle',+ 'releases/tag/v0.28.0/old.zip', 'releases/tag/v0.28.0-canary.20260904/today.zip'}+ r2_server.store.update({key: (b'artifact', '"e"') for key in doomed | kept})+ r2_server.store[f'{CANARY_DIR}/canary.appinstaller'] = (CANARY_FEED_XML.encode(), '"e"')+ r2_server.store[f'{CANARY_DIR}/second.appinstaller'] = (second.encode() if bad_feed is None else bad_feed, '"e"')+ r2_server.store['releases/win32/stable/stable.appinstaller'] = (CANARY_FEED_XML.encode(), '"e"')+ r2_server.last_modified[f'{CANARY_DIR}/fresh.msixbundle'] = '2026-09-03T00:00:00Z'+ r2_server.last_modified[f'{CANARY_DIR}/unknown.msixbundle'] = None+ r2_server.page_size = 3+ before = dict(r2_server.store)+ if bad_feed is not None:+ with pytest.raises(RuntimeError, match='refusing to prune'):+ r2.prune(keep_days=14, now_epoch=1788547200)+ assert r2_server.store == before+ assert not any(method == 'DELETE' for method, _, _ in r2_server.requests)+ return+ r2.prune(keep_days=14, dry_run=True, now_epoch=1788547200)+ assert {line.removeprefix('(dry-run) would delete r2:') for line in capsys.readouterr().out.splitlines()} == doomed+ assert r2_server.store == before and not any(method == 'DELETE' for method, _, _ in r2_server.requests)+ r2.prune(keep_days=14, now_epoch=1788547200)+ assert set(r2_server.store) == set(before) - doomeddef test_cli_usage_rejects_unknown_flags(capsys):@@ -848,7 +636,21 @@ def test_cli_usage_rejects_unknown_flags(capsys):r2.main(["put", "--wat", "x"])-def test_verify_remote_artifact_streams_without_buffering(r2_server):+def bounded_reads(monkeypatch):+ real_read = http.client.HTTPResponse.read+ reads = []++ def bounded_read(response, amount=None):+ assert amount is not None and 0 < amount <= 1024 * 1024+ reads.append(amount)+ return real_read(response, amount)++ monkeypatch.setattr(http.client.HTTPResponse, 'read', bounded_read)+ return reads+++def test_verify_remote_artifact_streams_without_buffering(r2_server, bounded_reads):"""REAL streaming proof: the hash is computed over socket-sized chunksagainst the live loopback server — the artifact is never materializedwhole (a 2GiB artifact would OOM the buffered path)."""@@ -866,6 +668,7 @@ def test_verify_remote_artifact_streams_without_buffering(r2_server):expected_size=len(payload),digest=base64.b64encode(hashlib.sha512(payload).digest()).decode("ascii"),)+ assert len(bounded_reads) > 1# Mismatched digest is rejected.with pytest.raises(ValueError, match="checksum mismatch"):r2.verify_remote_artifact(@@ -877,7 +680,7 @@ def test_verify_remote_artifact_streams_without_buffering(r2_server):)-def test_download_streams_verified_bytes_and_preserves_destination_on_failure(r2_server, tmp_path, monkeypatch):+def test_download_streams_verified_bytes_and_preserves_destination_on_failure(r2_server, tmp_path, monkeypatch, bounded_reads):import hashlibimport http.client@@ -887,22 +690,14 @@ def test_download_streams_verified_bytes_and_preserves_destination_on_failure(r2target = tmp_path / "downloads" / "package.msix"target.parent.mkdir()target.write_bytes(b"previous complete file")- real_read = http.client.HTTPResponse.read- reads = []-- def bounded_read(response, amount=None):- assert amount is not None and amount <= 1024 * 1024- reads.append(amount)- return real_read(response, amount)- monkeypatch.setattr(http.client.HTTPResponse, "read", bounded_read)args = dict(creds={"access_key_id": AKID, "secret_key": SECRET},base=f"http://127.0.0.1:{r2_server.server_port}", bucket="hermes-releases",key=key, file=target, now=NOW, expected_size=len(payload),expected_sha256=hashlib.sha256(payload).hexdigest())r2.download_object(**args)assert target.read_bytes() == payload- assert len(reads) > 1+ assert len(bounded_reads) > 1assert all("authorization" in headers for _, _, headers in r2_server.requests)original_get = _R2StubHandler.do_GET@@ -935,37 +730,6 @@ def test_download_streams_verified_bytes_and_preserves_destination_on_failure(r2assert list(target.parent.iterdir()) == [target]-def test_put_accepts_pathlib_paths(r2_server):- import pathlib- import tempfile-- payload = b"pathlib input"- with tempfile.NamedTemporaryFile(delete=False) as handle:- handle.write(payload)- path = pathlib.Path(handle.name)- try:- r2.put("v0.28.0", "pathlib.bin", path)- finally:- os.unlink(path)- assert r2_server.store["releases/tag/v0.28.0/pathlib.bin"][0] == payload---def test_parse_list_xml_handles_fractional_and_plain_timestamps():- parsed = parse_list_xml(- "<ListBucketResult>"- "<Contents><Key>a</Key><LastModified>2026-08-18T00:00:00.123Z</LastModified></Contents>"- "<Contents><Key>b</Key><LastModified>2026-08-18T00:00:00Z</LastModified></Contents>"- "</ListBucketResult>"- )- from datetime import datetime, timezone-- assert parsed["lastModified"]["a"] == int(- datetime(2026, 8, 18, 0, 0, 0, 123000, tzinfo=timezone.utc).timestamp()- )- assert parsed["lastModified"]["b"] == int(- datetime(2026, 8, 18, tzinfo=timezone.utc).timestamp()- )-def test_canonical_header_whitespace_is_collapsed():canon = canonical_request(diff --git a/tests/scripts/test_release_tags.py b/tests/scripts/test_release_tags.pyindex 08ddabccb06..3ddad8d322b 100644--- a/tests/scripts/test_release_tags.py+++ b/tests/scripts/test_release_tags.py@@ -18,71 +18,44 @@ def test_release_tag_uses_the_semver_version():assert release.release_tag_for_version("0.20.0") == "v0.20.0"-def test_last_tag_prefers_semver_over_newer_looking_legacy_calver(monkeypatch):- monkeypatch.setattr(- release,- "git",- lambda *_args: "v2026.7.20\nv0.20.0\nv0.19.0",- )-- assert release.get_last_tag() == "v0.20.0"---def test_last_tag_falls_back_to_legacy_calver_history(monkeypatch):- monkeypatch.setattr(release, "git", lambda *_args: "v2026.7.20\nv2026.7.7")-- assert release.get_last_tag() == "v2026.7.20"---class _FakeResult:- def __init__(self, stdout: str = "", returncode: int = 0):- self.stdout = stdout- self.returncode = returncode- self.stderr = ""---def _remotes(monkeypatch, names: list[str]):- monkeypatch.setattr(- release, "git_result", lambda *_args, **_kw: _FakeResult("\n".join(names))- )---def test_single_remote_is_used_without_a_flag(monkeypatch):- _remotes(monkeypatch, ["origin"])-- assert release.resolve_push_remote(None) == "origin"---def test_multiple_remotes_require_an_explicit_flag(monkeypatch):- _remotes(monkeypatch, ["fork", "origin"])-- with pytest.raises(SystemExit, match="pass --remote"):+def release_repo(tmp_path, monkeypatch):+ from tests.scripts.test_release_build_commit import git++ monkeypatch.setenv('GIT_CONFIG_GLOBAL', str(tmp_path / 'absent-config'))+ monkeypatch.setenv('GIT_CONFIG_NOSYSTEM', '1')+ git(tmp_path, 'init', '-q', '-b', 'main')+ git(tmp_path, 'config', 'user.name', 'Fixture')+ git(tmp_path, 'config', 'user.email', '[email protected]')+ git(tmp_path, 'commit', '--allow-empty', '-qm', 'fixture')+ monkeypatch.setattr(release, 'REPO_ROOT', tmp_path)+ return lambda *args: git(tmp_path, *args)+++def test_real_tag_order_and_remote_selection(release_repo):+ git = release_repo+ assert release.get_last_tag() is None and release.get_last_canary_tag() is None+ for tag in ('v2026.7.7', 'v2026.7.20'):+ git('tag', tag)+ assert release.get_last_tag() == 'v2026.7.20'+ for tag in ('v0.9.0', 'v0.20.0', 'v0.19.0', 'v0.21.0-canary.20260818090000',+ 'v0.21.0-canary.20260818171500', 'v0.21.0-canary.20260818'):+ git('tag', tag)+ assert release.get_last_tag() == 'v0.20.0'+ assert release.get_last_canary_tag() == 'v0.21.0-canary.20260818171500'+ with pytest.raises(SystemExit, match='no git remotes'):release.resolve_push_remote(None)---def test_explicit_remote_is_honored_among_many(monkeypatch):- _remotes(monkeypatch, ["fork", "origin"])-- assert release.resolve_push_remote("fork") == "fork"---def test_unknown_remote_is_rejected(monkeypatch):- _remotes(monkeypatch, ["fork", "origin"])-- with pytest.raises(SystemExit, match="not configured"):- release.resolve_push_remote("upstream")---def test_no_remotes_is_rejected(monkeypatch):- _remotes(monkeypatch, [])-- with pytest.raises(SystemExit, match="no git remotes"):+ git('remote', 'add', 'origin', 'https://github.com/o/r')+ assert release.resolve_push_remote(None) == 'origin'+ git('remote', 'add', 'fork', 'https://github.com/f/r')+ with pytest.raises(SystemExit, match='pass --remote'):release.resolve_push_remote(None)+ assert release.resolve_push_remote('fork') == 'fork'+ with pytest.raises(SystemExit, match='not configured'):+ release.resolve_push_remote('upstream')-def test_github_repo_parsed_from_ssh_and_https_urls(tmp_path, monkeypatch):- subprocess.run(['git', 'init', '-q', str(tmp_path)], check=True)- monkeypatch.setattr(release, 'REPO_ROOT', tmp_path)+def test_github_repo_parsed_from_ssh_and_https_urls(tmp_path, release_repo):urls = {"fork": "[email protected]:ethernet8023/hermes-agent.git","origin": "https://github.com/NousResearch/hermes-agent",diff --git a/tests/scripts/test_render_builds_binding.py b/tests/scripts/test_render_builds_binding.pynew file mode 100644index 00000000000..cbfbd798a46--- /dev/null+++ b/tests/scripts/test_render_builds_binding.py@@ -0,0 +1,47 @@+"""Commit rows bind a literal producer's receipt, not merely object names."""+import pytest++from tests.scripts.test_render_builds_publication import rbt++SHA = 'a' * 40+PACKAGE = 'HermesBundled-1.2.3-win-x64.msix'+OTHER = 'HermesBundled-1.2.4-win-x64.msix'+PREFIX = f'releases/commit/{SHA}/'++[email protected]('listed,objects,state,diagnostic', [+ (None, [PACKAGE], 'receipt-missing', 'leg incomplete or upload interrupted'),+ (['metadata-windows-x64.json'], [PACKAGE], 'receipt-omits', 'artifact absent from receipt'),+ ([PACKAGE], [], 'object-missing', 'receipt present but object missing'),+ ([PACKAGE, OTHER], [PACKAGE, OTHER], 'ambiguous', 'ambiguous: multiple objects match'),+ ([PACKAGE], [PACKAGE, OTHER], 'built', '✅ Built'),+])+def test_commit_row_binding_faults(listed, objects, state, diagnostic):+ receipt = None if listed is None else {+ 'schema': 2, 'commit': SHA, 'name': 'win32-x64',+ 'files': [{'path': path, 'size': 1, 'sha256': '0' * 64} for path in listed],+ }+ receipts = {'win32-x64': receipt}+ keys = [PREFIX + path for path in objects]+ row = next(row for row in rbt.commit_expected_rows(keys, receipts)+ if row['label'] == 'Windows x64 (MSIX)')+ assert row == {'label': 'Windows x64 (MSIX)', 'leg': 'win32-x64',+ 'state': state, 'key': PREFIX + PACKAGE if state == 'built' else None}+ summary = rbt.render_commit_summary(keys, 'https://cdn.example', SHA, receipts)+ page = rbt.render_commit_page(SHA, keys, 'https://cdn.example', receipts)+ for output in (summary, page):+ assert diagnostic in output+ assert ('https://cdn.example/' + PREFIX + PACKAGE in output) == (state == 'built')+ assert 'Store' not in output+ assert rbt.recorded_build(page) == SHA+ assert 'Bundle environment' not in page++[email protected]('needs,expected', [+ (None, []), ('', []), ('not json', []),+ ('{"build-win32":{"result":"success"},"build-darwin":{"result":"failure"},'+ '"termux-deb":{"result":"skipped"},"build-linux":{"result":"failure"}}',+ ['build-darwin', 'build-linux']),+])+def test_failed_legs_from_release_needs(needs, expected):+ assert rbt.failed_legs_from_release_needs(needs) == expecteddiff --git a/tests/scripts/test_render_builds_publication.py b/tests/scripts/test_render_builds_publication.pynew file mode 100644index 00000000000..17f6ae55428--- /dev/null+++ b/tests/scripts/test_render_builds_publication.py@@ -0,0 +1,137 @@+"""Tag pages and release bodies publish the same independently named objects."""+import importlib.util+import json+from pathlib import Path+import re+import subprocess+import sys+from urllib.request import urlopen++import pytest++from tests.scripts.test_release_r2 import r2_server # noqa: F401++_SPEC = importlib.util.spec_from_file_location(+ 'render_builds_table', Path(__file__).resolve().parents[2] / 'scripts/render-builds-table.py')+assert _SPEC and _SPEC.loader+rbt = importlib.util.module_from_spec(_SPEC)+_SPEC.loader.exec_module(rbt)+++def release_body(monkeypatch):+ state = {'body': '# Notes\n\n<!-- HERMES_BUILDS_TABLE -->\n\n## Changes\n- x\n', 'edits': []}++ def gh(argv, **kwargs):+ if argv[:3] == ['gh', 'release', 'view']:+ return subprocess.CompletedProcess(argv, 0, json.dumps({'body': state['body']}), '')+ assert argv[:3] == ['gh', 'release', 'edit']+ state['body'] = kwargs['input']+ state['edits'].append(state['body'])+ return subprocess.CompletedProcess(argv, 0, '', '')++ monkeypatch.setattr(rbt.subprocess, 'run', gh)+ return state++[email protected]('tag', ['v1.2.3', 'v1.2.3-canary.20260818101010'])+def test_tag_publication_pending_rerun_stale_and_dry_run(monkeypatch, r2_server, release_body, tag):+ base = f'http://127.0.0.1:{r2_server.server_port}/hermes-releases'+ version = tag[1:]+ prefix = f'releases/tag/{tag}/'+ visible = [f'HermesBundled-{version}-mac-arm64.dmg', f'HermesBundled-{version}-win-x64.msix',+ f'HermesBundled-{version}-win-arm64.msix', f'HermesBundled-{version}-linux-x64.AppImage',+ f'HermesLight-{version}-win-x64.msix']+ hidden = [f'HermesBundled-{version}-mac-arm64.zip', f'HermesBundled-{version}-win.msixbundle',+ f'HermesBundled-{version}-win-x64.msix.blockmap', 'latest.yml',+ 'HermesBundled-9.9.9-win-x64.msix']+ for name in visible + hidden:+ r2_server.store[prefix + name] = (name.encode(), '"e"')+ r2_server.store['releases/tag/v9.9.9/HermesBundled-9.9.9-win-x64.msix'] = (b'neighbor', '"e"')+ monkeypatch.setenv('RELEASE_NEEDS', '{"build-win32":{"result":"success"}}')+ args = ['render-builds-table.py', '--tag', tag, '--repo', 'o/r', '--r2-base-url', base + '/']++ def render(*extra):+ monkeypatch.setattr(sys, 'argv', [*args, *extra])+ assert rbt.main() == 0++ for run in ('1', '2'):+ render('--pending-run-url', f'https://github.example/runs/{run}')+ assert 'runs/1' not in release_body['body'] and release_body['body'].count('runs/2') == 1+ assert not any(method == 'PUT' for method, _, _ in r2_server.requests)+ render()+ body = release_body['body']+ assert 'runs/2' not in body and body.count('## Downloads') == 1+ assert body.count(rbt.MARKER) == body.count(rbt.END_MARKER) == 1+ expected = {f'{base}/{prefix}{name}' for name in visible}+ assert set(re.findall(r'\]\((http[^)]+)\)', body)) == expected+ with urlopen(f'{base}/{prefix}index.html', timeout=5) as response:+ page = response.read().decode()+ assert set(re.findall(r'href="(http[^"]+)"', page)) == expected | {f'https://github.com/o/r/releases/tag/{tag}'}+ assert rbt.recorded_build(page) == tag and 'Bundle environment' not in page+ assert all(name not in page and name not in body for name in hidden)+ assert 'linux-arm64' not in page+ for url in expected:+ with urlopen(url, timeout=5) as response:+ assert response.read() == url.rsplit('/', 1)[1].encode()+ channel_key = 'releases/canary/index.html' if '-canary.' in tag else 'releases/stable/index.html'+ assert r2_server.store[channel_key][0].decode() == page+ render()+ assert release_body['body'] == body++ # Use the real page writer's marker format, independent of asset selection.+ newer = rbt.render_page('v9.9.9', {}, base).encode()+ r2_server.store[channel_key] = (newer, '"e"')+ render()+ assert r2_server.store[channel_key][0] == newer+ assert r2_server.store[prefix + 'index.html'][0].decode() == page+ before, edits = dict(r2_server.store), list(release_body['edits'])+ render('--dry-run')+ assert r2_server.store == before and release_body['edits'] == edits+ release_body['body'] = 'no marker here'+ render()+ assert release_body['body'] == 'no marker here' and release_body['edits'] == edits++[email protected]('asset_present', [False, True])[email protected]('result', ['failure', 'cancelled', 'skipped'])+def test_incomplete_tag_keeps_channel_and_links_diagnostics(monkeypatch, r2_server, release_body, asset_present, result):+ tag = 'v1.2.3-canary.20260818101010'+ base = f'http://127.0.0.1:{r2_server.server_port}/hermes-releases'+ key = f'releases/tag/{tag}/HermesBundled-{tag[1:]}-win-x64.msix'+ r2_server.store['releases/canary/index.html'] = (b'previous good page', '"e"')+ if asset_present:+ r2_server.store[key] = (b'transport fixture', '"e"')+ run = 'https://github.example/runs/123'+ monkeypatch.setenv('RELEASE_NEEDS', json.dumps({'publish-win32-updater': {'result': result}}))+ monkeypatch.setattr(sys, 'argv', ['renderer', '--tag', tag, '--r2-base-url', base, '--run-url', run])+ assert rbt.main() == 0+ with urlopen(f'{base}/releases/tag/{tag}/index.html', timeout=5) as response:+ page = response.read().decode()+ for output in (page, release_body['body']):+ assert 'Build incomplete' in output and f'publish-win32-updater ({result})' in output+ assert run in output+ assert (base + '/' + key in output) == asset_present+ assert ('No downloadable artifacts' in page) == (not asset_present)+ assert r2_server.store['releases/canary/index.html'][0] == b'previous good page'++[email protected]('version,name', [+ ('1.2.3', 'HermesBundled-1.2.3-win-x64.msix'),+ ('1.2.3-canary.20260818', 'HermesBundled-1.2.3-canary.20260818-win-x64.msix'),+])+def test_exact_version_and_flat_name_boundaries(version, name):+ names = [name, 'HermesBundled-1.2.3-canary.20260817-win-x64.msix', 'HermesBundled-1.2.4-win-x64.msix', name + '.blockmap']+ assert rbt.filter_names_for_version(names, version) == [name]+ assert rbt.parse_assets([name])['HermesBundled'][('win', 'x64')] == (name, 'msix')++[email protected]('current,tag,allowed', [+ (None, 'v1.2.3', True), ('garbage', 'v1.2.3', True),+ ('v1.2.3', 'v1.2.3-canary.20260818101010', False),+ ('v1.2.3-canary.20260818101010', 'v1.2.3-canary.20260818101009', False),+ ('v1.2.3-canary.20260818101010', 'v1.2.3-canary.20260818101011', True),+])+def test_channel_order_boundaries(current, tag, allowed):+ page = rbt.render_page(current, {}, 'https://cdn.example') if current and current != 'garbage' else current+ assert rbt.supersedes(page, tag) is alloweddiff --git a/tests/scripts/test_render_builds_table.py b/tests/scripts/test_render_builds_table.pydeleted file mode 100644index 7de13f51cf2..00000000000--- a/tests/scripts/test_render_builds_table.py+++ /dev/null@@ -1,342 +0,0 @@-"""render-builds-table.py: tables from REAL bucket object names, spliced idempotently.--The contract: table rows exist only for objects that are actually in the-R2 bucket for the tag's exact version (missing artifact = missing row,-never a dead link), links point at the R2 public URL, msixbundle / zip /-feed manifests stay out, and re-rendering replaces the previous block-instead of stacking a second one.--Adapted from the restack suite for this branch's artifact shapes: the-Windows per-arch artifact here is .msix (the msixbundle folds both arches-and stays out of the tables), not the NSIS .exe.-"""--import importlib.util-import json-import re-import subprocess-import sys-from pathlib import Path-from urllib.request import urlopen--import pytest--from tests.scripts.test_release_r2 import r2_server # noqa: F401--_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)---ASSETS = [- "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg",- "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.zip", # updater delta target — no row- "releases/tag/v0.28.0/HermesBundled-0.28.0-win-x64.msix",- "releases/tag/v0.28.0/HermesBundled-0.28.0-win-arm64.msix",- "releases/tag/v0.28.0/HermesBundled-0.28.0-win.msixbundle", # store/sideload channel — no row- "releases/tag/v0.28.0/HermesBundled-0.28.0-linux-x64.AppImage",- "releases/tag/v0.28.0/HermesLight-0.28.0-win-x64.msix",- "latest.yml", # feed manifest — no row- "light.yml",- "releases/tag/v0.28.0/HermesBundled-0.28.0-win-x64.msix.blockmap", # no row-]--BASE_URL = "https://releases.example.com"---class TestParseAssets:- def test_only_table_shaped_assets_parse(self):- parsed = rbt.parse_assets(ASSETS)- assert ("mac", "arm64") in parsed["HermesBundled"]- assert ("win", "x64") in parsed["HermesBundled"]- assert ("win", "arm64") in parsed["HermesBundled"]- assert ("linux", "x64") in parsed["HermesBundled"]- assert len(parsed["HermesBundled"]) == 4 # zip/msixbundle/blockmap/yml excluded- assert parsed["HermesLight"] == {("win", "x64"): ("releases/tag/v0.28.0/HermesLight-0.28.0-win-x64.msix", "msix")}-- def test_canary_versions_parse(self):- parsed = rbt.parse_assets(["releases/tag/v0.28.0-canary.20260818/HermesBundled-0.28.0-canary.20260818-win-x64.msix"])- assert ("win", "x64") in parsed["HermesBundled"]-- def test_flat_names_still_parse(self):- # Names without the releases/tag/ prefix (e.g. from a plain list) are- # handled too — the shape match runs on the basename either way.- parsed = rbt.parse_assets(["HermesBundled-0.28.0-win-x64.msix"])- assert parsed["HermesBundled"][("win", "x64")] == ("HermesBundled-0.28.0-win-x64.msix", "msix")---class TestFilterNamesForVersion:- def test_stable_tag_does_not_match_canary_objects(self):- # '0.28.0' is a prefix of '0.28.0-canary...' — the filter must be- # exact, or a stable table would list canary binaries.- names = [- "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg",- "releases/tag/v0.28.0-canary.20260818/HermesBundled-0.28.0-canary.20260818-win-x64.msix",- "releases/tag/v0.29.0/HermesBundled-0.29.0-win-x64.msix",- "latest.yml",- ]- assert rbt.filter_names_for_version(names, "0.28.0") == [- "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg",- ]-- def test_canary_tag_matches_its_objects(self):- names = [- "releases/tag/v0.28.0-canary.20260818/HermesBundled-0.28.0-canary.20260818-win-x64.msix",- "releases/tag/v0.28.0-canary.20260818/HermesBundled-0.28.0-canary.20260818-win-x64.msix.blockmap",- "releases/tag/v0.28.0-canary.20260817/HermesBundled-0.28.0-canary.20260817-win-arm64.msix",- "releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg",- ]- assert rbt.filter_names_for_version(names, "0.28.0-canary.20260818") == [- "releases/tag/v0.28.0-canary.20260818/HermesBundled-0.28.0-canary.20260818-win-x64.msix",- ]---class TestRenderAndSplice:- def test_rows_only_for_present_assets(self):- block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)- assert f"{BASE_URL}/releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg" in block- assert "HermesBundled-0.28.0-win.msixbundle" not in block- assert ".zip" not in block- assert ".blockmap" not in block- # A leg that never uploaded leaves no row at all.- assert "linux-arm64" not in block-- def test_links_point_at_the_r2_base_url(self):- block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)- assert "github.com" not in block- assert f"{BASE_URL}/releases/tag/v0.28.0/HermesLight-0.28.0-win-x64.msix" in block-- def test_base_url_trailing_slash_is_stripped(self):- block = rbt.render_tables(rbt.parse_assets(ASSETS), f"{BASE_URL}/")- assert f"{BASE_URL}/releases/tag/v0.28.0/HermesBundled-0.28.0-mac-arm64.dmg" in block- assert f"{BASE_URL}//releases" not in block-- def test_splice_replaces_marker_and_is_idempotent(self):- body = f"# Notes\n\n{rbt.MARKER}\n\n## Changes"- block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)- once = rbt.splice(body, block)- assert "## Downloads" in once- assert once.count(rbt.MARKER) == 1- # Second render (e.g. a re-run with more assets) replaces, not stacks.- twice = rbt.splice(once, block)- assert twice.count("## Downloads") == 1- assert twice.count(rbt.END_MARKER) == 1-- def test_no_marker_leaves_body_alone(self):- block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)- assert rbt.splice("no marker here", block) == "no marker here"---class TestPendingPlaceholder:- def test_final_render_replaces_the_pending_link(self):- # The lifecycle: marker → pending link (builds-pending job) →- # tables (builds-table job). The link must not survive step 3.- body = f"# Notes\n\n{rbt.MARKER}\n\n## Changes"- pending = rbt.render_pending("https://github.com/o/r/actions/runs/123")- with_pending = rbt.splice(body, pending)- assert "actions/runs/123" in with_pending- assert with_pending.count(rbt.MARKER) == 1 # wrapper survives for step 3- tables = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)- final = rbt.splice(with_pending, tables)- assert "actions/runs/123" not in final- assert "## Downloads" in final- assert final.count(rbt.END_MARKER) == 1-- def test_pending_rerender_replaces_not_stacks(self):- once = rbt.splice(rbt.MARKER, rbt.render_pending("https://x/runs/1"))- twice = rbt.splice(once, rbt.render_pending("https://x/runs/2"))- assert "https://x/runs/1" not in twice- assert twice.count("https://x/runs/2") == 1- assert twice.count(rbt.END_MARKER) == 1---class TestBucketPage:- """The page is the same row set as the release-body table.-- Every download link in the markdown table exists in the page, and the- artifacts the table deliberately hides (zip/msixbundle/blockmap) stay- out of the page too — a page that outlives the release body must not- advertise a delta target as a download.- """-- def test_page_carries_exactly_the_table_rows(self):- block = rbt.render_tables(rbt.parse_assets(ASSETS), BASE_URL)- page = rbt.render_page("v0.28.0", rbt.parse_assets(ASSETS), BASE_URL)- links = re.findall(r"\]\((https?://[^)]+)\)", block)- assert links # the table is non-empty, so the comparison means something- for url in links:- assert f'href="{url}"' in page- # One row per table row, plus one header row per section.- assert page.count("<tr>") == len(links) + page.count("<table>")- assert ".zip" not in page and ".blockmap" not in page and ".msixbundle" not in page- # A leg that never uploaded has no row in either sink, while a leg- # that did (linux-x64) is listed.- assert BASE_URL + "/releases/tag/v0.28.0/HermesBundled-0.28.0-linux-x64.AppImage" in page- assert "linux-arm64" not in page-- @pytest.mark.parametrize("has_download", [True, False])- def test_failed_tag_rows_link_diagnostics_not_downloads(self, has_download):- run_url = "https://github.example/o/r/actions/runs/12345"- names = [ASSETS[2]] if has_download else []- assets = rbt.parse_assets(names)- failed = ["build-win32 (failure)", "build-darwin (failure)", "termux-deb (failure)"]- block = rbt.render_tables(assets, BASE_URL, failed, run_url=run_url)- page = rbt.render_page("v0.28.0", assets, BASE_URL, failed, run_url=run_url)- for job in failed:- md = next(line for line in block.splitlines() if line.startswith(f"| {job} |"))- html_row = next(row for row in re.findall(r"<tr><td>(.*?)</tr>", page) if job in row)- assert f"[View build run]({run_url})" in md- assert f'<a href="{run_url}">View build run</a>' in html_row- assert BASE_URL not in md and BASE_URL not in html_row- downloads = [url for url in re.findall(r"href=\"([^\"]+)\"", page) if url.startswith(BASE_URL)]- assert downloads == [f"{BASE_URL}/{name}" for name in names]- assert ("No downloadable artifacts" in page) is (not has_download)- for url in downloads:- assert f"]({url})" in block-- def test_page_names_the_build_it_describes(self):- page = rbt.render_page("v0.28.0", rbt.parse_assets(ASSETS), BASE_URL)- assert rbt.recorded_build(page) == "v0.28.0"- canary = rbt.render_page("v0.28.0-canary.20260818101010", rbt.parse_assets(ASSETS), BASE_URL)- assert rbt.recorded_build(canary) == "v0.28.0-canary.20260818101010"- assert "canary" in canary-- def test_older_tag_never_regresses_the_channel_page(self):- """A re-run of an old tag must not overwrite the page a newer release- published; the recorded tag is compared with the feed's own authority."""- current = rbt.render_page("v0.29.0", rbt.parse_assets(ASSETS), BASE_URL)- assert not rbt.supersedes(current, "v0.28.0")- assert not rbt.supersedes(current, "v0.28.0-canary.20260818101010")- assert rbt.supersedes(current, "v0.29.0") # same tag re-run rewrites- assert rbt.supersedes(current, "v0.30.0")- newer_canary = rbt.render_page("v0.29.0-canary.20260901090000", rbt.parse_assets(ASSETS), BASE_URL)- assert not rbt.supersedes(newer_canary, "v0.29.0-canary.20260801090000")- assert rbt.supersedes(newer_canary, "v0.29.0-canary.20260901090001")- # Nothing published yet, or an unreadable record: the new page wins.- assert rbt.supersedes(None, "v0.28.0")- assert rbt.supersedes("<html>garbage</html>", "v0.28.0")-- def test_channel_page_key_follows_the_tag(self):- assert rbt.r2.channel_page_key_for(rbt.r2.channel_for_tag("v0.28.0")) == "releases/stable/index.html"- assert rbt.r2.channel_page_key_for(- rbt.r2.channel_for_tag("v0.28.0-canary.20260818101010")) == "releases/canary/index.html"---class TestTagRunPublishesThePage:- """The real CLI path: the page is uploaded for the tag's own channel."""-- TAG = "v0.28.0-canary.20260818101010"- KEYS = [- f"releases/tag/{TAG}/HermesBundled-0.28.0-canary.20260818101010-win-x64.msix",- f"releases/tag/{TAG}/HermesBundled-0.28.0-canary.20260818101010-mac-arm64.dmg",- f"releases/tag/{TAG}/HermesBundled-0.28.0-canary.20260818101010-win.msixbundle",- f"releases/tag/{TAG}/HermesLight-0.28.0-canary.20260818101010-win-x64.msix",- "releases/tag/v0.27.0/HermesBundled-0.27.0-win-x64.msix", # neighbor release- ]-- @staticmethod- def _gh(argv, **kwargs):- if argv[:3] == ["gh", "release", "view"]:- body = f"# Notes\n\n{rbt.MARKER}\n\n## Changes\n- x\n"- return subprocess.CompletedProcess(argv, 0, stdout=json.dumps({"body": body}), stderr="")- if argv[:3] == ["gh", "release", "edit"]:- return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")- raise AssertionError(argv)-- def test_page_upload_key_and_bytes(self, monkeypatch, capsys, tmp_path):- monkeypatch.setenv("RELEASE_NEEDS", json.dumps({- "validate": {"result": "success"}, "build-win32": {"result": "success"},- "publish-win32-updater": {"result": "success"},- }))- uploads: list[tuple[str, str, bool]] = []- monkeypatch.setattr(rbt.r2, "list_objects", lambda prefix="": {"keys": self.KEYS})- monkeypatch.setattr(rbt, "existing_page", lambda key: None)- monkeypatch.setattr(rbt.r2, "put", lambda tag, key, file, key_is_full=False, immutable=False:- uploads.append((key, Path(file).read_text(encoding="utf-8"), key_is_full)))- monkeypatch.setattr(rbt.subprocess, "run", self._gh)- monkeypatch.setattr(sys, "argv", [- "render-builds-table.py", "--tag", self.TAG, "--repo", "o/r", "--r2-base-url", BASE_URL,- ])- assert rbt.main() == 0- assert len(uploads) == 2- assert uploads[0][0] == f"releases/tag/{self.TAG}/index.html"- key, page, key_is_full = uploads[1]- assert uploads[0][1] == page- # Canary tag → the canary channel page, as a full key (not a tag name).- assert key == "releases/canary/index.html" and key_is_full- assert rbt.recorded_build(page) == self.TAG- assert f'href="https://github.com/o/r/releases/tag/{self.TAG}"' in page- assert 'Bundle environment' not in page- for name in ("HermesBundled-0.28.0-canary.20260818101010-win-x64.msix",- "HermesBundled-0.28.0-canary.20260818101010-mac-arm64.dmg",- "HermesLight-0.28.0-canary.20260818101010-win-x64.msix"):- assert f"{BASE_URL}/releases/tag/{self.TAG}/{name}" in page- # The neighbor release and the hidden artifact shapes stay out.- assert "v0.27.0" not in page and ".msixbundle" not in page- assert f"✓ Page {BASE_URL}/releases/canary/index.html" in capsys.readouterr().out-- def test_stale_tags_keep_their_own_page_and_dry_runs_write_nothing(self, monkeypatch, tmp_path):- uploads: list[str] = []- monkeypatch.setattr(rbt.r2, "list_objects", lambda prefix="": {"keys": self.KEYS})- monkeypatch.setattr(rbt.r2, "put", lambda **kwargs: uploads.append(kwargs["key"]))- monkeypatch.setattr(rbt.subprocess, "run", self._gh)- stale = rbt.render_page("v0.29.0", rbt.parse_assets(ASSETS), BASE_URL)- monkeypatch.setattr(rbt, "existing_page", lambda key: stale)- monkeypatch.setattr(sys, "argv", [- "render-builds-table.py", "--tag", self.TAG, "--repo", "o/r", "--r2-base-url", BASE_URL,- ])- assert rbt.main() == 0 # stale tag: channel untouched- assert uploads == [f"releases/tag/{self.TAG}/index.html"]- uploads.clear()- monkeypatch.setattr(rbt, "existing_page", lambda key: None)- monkeypatch.setattr(sys, "argv", [- "render-builds-table.py", "--tag", self.TAG, "--repo", "o/r",- "--r2-base-url", BASE_URL, "--dry-run",- ])- assert rbt.main() == 0 # dry run: nothing published- assert uploads == []-- @pytest.mark.parametrize("asset_present", [False, True])- @pytest.mark.parametrize("result", ["failure", "cancelled", "skipped"])- def test_incomplete_tag_is_readable_without_replacing_last_good_channel(- self, monkeypatch, r2_server, asset_present, result,- ):- base = f"http://127.0.0.1:{r2_server.server_port}/hermes-releases"- channel_key = "releases/canary/index.html"- previous = rbt.render_page("v0.27.0-canary.20260817101010", {}, base).encode()- r2_server.store[channel_key] = (previous, "text/html")- if asset_present:- r2_server.store[self.KEYS[0]] = (b"transport fixture", "application/octet-stream")- edits = []-- def gh(argv, **kwargs):- if argv[:3] == ["gh", "release", "edit"]:- edits.append(kwargs["input"])- return self._gh(argv, **kwargs)-- monkeypatch.setattr(rbt.subprocess, "run", gh)- monkeypatch.setenv("RELEASE_NEEDS", json.dumps({- "validate": {"result": "success"},- "build-win32": {"result": "success"},- "publish-win32-updater": {"result": result},- }))- monkeypatch.setattr(sys, "argv", [- "render-builds-table.py", "--tag", self.TAG, "--r2-base-url", base,- ])- assert rbt.main() == 0- tag_key = f"releases/tag/{self.TAG}/index.html"- assert tag_key in r2_server.store- with urlopen(f"{base}/{tag_key}", timeout=5) as response:- page = response.read().decode()- assert rbt.recorded_build(page) == self.TAG- assert "Build incomplete" in page and "Build incomplete" in edits[0]- assert f"publish-win32-updater ({result})" in page- assert f"publish-win32-updater ({result})" in edits[0]- links = re.findall(r'href="([^"]+)"', page)- assert links[0] == f"https://github.com/NousResearch/hermes-agent/releases/tag/{self.TAG}"- assert links[1:] == ([f"{base}/{self.KEYS[0]}"] if asset_present else [])- assert r2_server.store[channel_key][0] == previous- if not asset_present:- assert "No downloadable artifacts" in pagediff --git a/tests/scripts/test_render_builds_table_commit.py b/tests/scripts/test_render_builds_table_commit.pydeleted file mode 100644index cc7fb380b38..00000000000--- a/tests/scripts/test_render_builds_table_commit.py+++ /dev/null@@ -1,304 +0,0 @@-"""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-import re-import sys-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",- "HermesBundled-0.28.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 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 not any("Store" in row["label"] for row in rows)- assert any("MSIXBUNDLE" in row["label"] for row in rows)- # The universal sideload bundle 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_the_sideload_bundle():- from scripts.releases import handoff-- paths = {- "windows-universal": [- "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 not any("Store" in line for line in built)- assert "Linux x64" in summary and "Linux ARM64" in summary--[email protected]("has_download", [True, False])-def test_incomplete_commit_rows_link_run_not_missing_downloads(has_download):- run_url = "https://github.example/o/r/actions/runs/12345"- receipts = _receipts_all_built() if has_download else {}- names = _names("HermesBundled-0.28.0-win-x64.msix") if has_download else []- # The uploaded x64 binary stays downloadable even when that job fails- # after staging, or a sibling fails before staging its own artifact.- failed = ["build-win32", "build-darwin", "publish-win32-updater", "termux-deb"]- summary = rbt.render_commit_summary(names, BASE, COMMIT, receipts, failed, run_url=run_url)- page = rbt.render_commit_page(COMMIT, names, BASE, receipts, failed, run_url=run_url)- markdown_rows = [line for line in summary.splitlines() if line.startswith("| ")][1:]- html_rows = re.findall(r"<tr><td>(.*?)</tr>", page)- assert len(markdown_rows) == len(html_rows) == len(rbt._COMMIT_EXPECTED) + len(rbt._COMMIT_DISABLED)- for md, html_row in zip(markdown_rows, html_rows):- if "Linux" in md:- assert "Disabled" in md and "Disabled" in html_row- assert "](" not in md and "href=" not in html_row- elif has_download and "Windows x64" in md:- url = f"{BASE}/{names[0]}"- assert "✅ Built" in md and "✅ Built" in html_row- assert f"]({url})" in md and f'href="{url}"' in html_row- assert run_url not in md and run_url not in html_row- else:- assert "❌ Not built" in md and "❌ Not built" in html_row- assert f"[View build run]({run_url})" in md- assert f'<a href="{run_url}">View build run</a>' in html_row- assert BASE not in md and BASE not in html_row- assert summary.count("✅ Built") == page.count("✅ Built") == int(has_download)---def test_commit_page_matches_the_summary_rows():- """Two sinks, ONE row set: every link and every status in the step- summary appears on the page, and neither sink drops a missing binary."""- receipts = _receipts_all_built()- names = _all_built_names()- summary = rbt.render_commit_summary(names, BASE, COMMIT, receipts)- page = rbt.render_commit_page(COMMIT, names, BASE, receipts)- links = re.findall(r"\]\((https?://[^)]+)\)", summary)- assert len(links) == len(rbt._COMMIT_EXPECTED)- for url in links:- assert f'href="{url}"' in page- assert page.count("✅ Built") == summary.count("✅ Built") == len(rbt._COMMIT_EXPECTED)- assert page.count("Disabled") == summary.count("Disabled") == len(rbt._COMMIT_DISABLED)- assert "❌ Not built" not in page and "❌ Not built" not in summary- assert rbt.recorded_build(page) == COMMIT---def test_commit_page_lists_a_missing_binary_without_a_link():- receipts = _receipts_all_built()- receipts["darwin-arm64"] = None- names = _names("HermesBundled-0.28.0-win-x64.msix")- page = rbt.render_commit_page(COMMIT, names, BASE, receipts, failed_legs=["build-darwin"])- assert page.count("<tr>") == len(rbt._COMMIT_EXPECTED) + len(rbt._COMMIT_DISABLED) + 1- assert "failed: build-darwin" in page- # Source navigation is separate from receipt-backed downloads.- assert re.findall(r'href="([^"]+)"', page) == [- f"https://github.com/NousResearch/hermes-agent/commit/{COMMIT}", f"{BASE}/{names[0]}",- ]- assert "Bundle environment" not in page---def test_commit_run_publishes_the_commit_page(tmp_path, monkeypatch, capsys):- """The real CLI path: commit mode writes the summary AND the page."""- summary = tmp_path / "summary.md"- uploads: list[tuple[str, str, bool]] = []- receipts = _receipts_all_built()- monkeypatch.setattr(rbt.r2, "list_objects", lambda prefix="": {"keys": _all_built_names()})- monkeypatch.setattr(rbt.handoff, "read_commit_receipt", lambda commit, name: receipts[name])- monkeypatch.setattr(rbt.r2, "put", lambda tag, key, file, key_is_full=False, immutable=False:- uploads.append((key, Path(file).read_text(encoding="utf-8"), key_is_full)))- monkeypatch.setattr(sys, "argv", ["render-builds-table.py", "--summary-commit", COMMIT,- "--summary-out", str(summary), "--r2-base-url", BASE])- assert rbt.main() == 0- assert len(uploads) == 1- key, page, key_is_full = uploads[0]- assert key == f"releases/commit/{COMMIT}/index.html" and key_is_full- assert f"✓ Page {BASE}/releases/commit/{COMMIT}/index.html" in capsys.readouterr().out- written = summary.read_text(encoding="utf-8")- for url in re.findall(r"\]\((https?://[^)]+)\)", written):- assert f'href="{url}"' in page- assert written.count("✅ Built") == page.count("✅ Built") == len(rbt._COMMIT_EXPECTED)diff --git a/tests/scripts/test_stable_release.py b/tests/scripts/test_stable_release.pyindex 472b7f24198..64df30081db 100644--- a/tests/scripts/test_stable_release.py+++ b/tests/scripts/test_stable_release.py@@ -1,7 +1,6 @@"""Release gates and package transitions bind the intended immutable artifacts."""import copyimport hashlib-import ioimport jsonimport osimport subprocess@@ -96,7 +95,8 @@ def test_transitions_bind_all_arches_identity_version_and_archive():plan_transitions(new, old, BASE)-def test_manifest_origin_checks_with_real_https(tmp_path):+def https_origin(tmp_path, monkeypatch):import datetimeimport ipaddressimport ssl@@ -123,7 +123,6 @@ def test_manifest_origin_checks_with_real_https(tmp_path):key_file.write_bytes(key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))requests = []- data = b'{"schema":1}'class Handler(BaseHTTPRequestHandler):def do_GET(self):@@ -134,7 +133,9 @@ def test_manifest_origin_checks_with_real_https(tmp_path):self.send_header("Location", f"https://{host}:{self.server.server_port}/manifest")self.end_headers()else:- self.send_response(200)+ item = self.server.store.get(self.path.lstrip('/'))+ data = item[0] if item else b'not found'+ self.send_response(200 if item else 404)self.send_header("Content-Length", str(len(data)))self.end_headers()self.wfile.write(data)@@ -143,6 +144,8 @@ def test_manifest_origin_checks_with_real_https(tmp_path):passserver = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.store = {'manifest': (b'{"schema":1}', '"e"')}+ server.requests = requestsserver_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)server_context.load_cert_chain(cert_file, key_file)server.socket = server_context.wrap_socket(server.socket, server_side=True)@@ -150,36 +153,34 @@ def test_manifest_origin_checks_with_real_https(tmp_path):opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=client_context)).openbase = f"https://127.0.0.1:{server.server_port}"+ server.base, server.opener = base, opener+ monkeypatch.setenv('SSL_CERT_FILE', str(cert_file))thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()try:- digest = hashlib.sha256(data).hexdigest()- assert read_manifest(f"{base}/same", digest, expected_origin=base, opener=opener) == {"schema": 1}- with pytest.raises(ValueError, match="origin"):- read_manifest(f"{base}/cross", opener=opener)- requests.clear()- with pytest.raises(ValueError, match="origin"):- read_manifest(f"https://localhost:{server.server_port}/manifest", expected_origin=base, opener=opener)- assert requests == []+ yield serverfinally:server.shutdown()server.server_close()thread.join(timeout=5)-def test_manifest_digest_and_tag_movement_fail_closed(tmp_path, monkeypatch):- data = b'{"schema":1}'+def test_manifest_origin_checks_with_real_https(https_origin):+ server = https_origin+ base, opener = server.base, server.opener+ digest = hashlib.sha256(b'{"schema":1}').hexdigest()+ assert read_manifest(f'{base}/same', digest, expected_origin=base, opener=opener) == {'schema': 1}+ with pytest.raises(ValueError, match='digest'):+ read_manifest(f'{base}/manifest', 'f' * 64, opener=opener)+ with pytest.raises(ValueError, match='origin'):+ read_manifest(f'{base}/cross', opener=opener)+ server.requests.clear()+ with pytest.raises(ValueError, match='origin'):+ read_manifest(f'https://localhost:{server.server_port}/manifest', expected_origin=base, opener=opener)+ assert server.requests == []- class Response(io.BytesIO):- def geturl(self):- return BASE + "/manifest.json"- def opener(url, timeout):- return Response(data)-- assert read_manifest(BASE, hashlib.sha256(data).hexdigest(), opener=opener) == {"schema": 1}- with pytest.raises(ValueError, match="digest"):- read_manifest(BASE, "f" * 64, opener=opener)+def test_tag_movement_fails_closed(tmp_path, monkeypatch):commit = "a" * 40env = {"RELEASE_TAG": "v1.2.3", "GITHUB_SHA": commit, "GITHUB_REF": "refs/tags/v1.2.3"}