The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(ci): look up desktop release jobs by role, not by id
ethernet37d3e32bbe77
diff --git a/tests/ci/desktop_release_roles.py b/tests/ci/desktop_release_roles.pynew file mode 100644index 00000000000..85feb19b0c4--- /dev/null+++ b/tests/ci/desktop_release_roles.py@@ -0,0 +1,220 @@+"""Find desktop release workflow jobs by what they do, not by their ids.++Job ids in desktop-bundled-release.yml change whenever the build graph is+reshaped (one ``build-win32-commit`` job became four per-arch legs). Tests that+index ``jobs['build-win32-x64-commit']`` break on every such rename while the+property they protect still holds. These lookups key each role on a stable+structural fact: the action a job uses, the receipt it stages, the jobs it+needs. A lookup that finds no match or more than one fails loudly, so a real+graph change cannot silently empty a test.+"""+from __future__ import annotations++import re+from pathlib import Path++import hermes_yaml++from scripts.releases.job_groups import JOB_GROUPS++ROOT = Path(__file__).resolve().parents[2]+WORKFLOW = ROOT / ".github" / "workflows" / "desktop-bundled-release.yml"+SMOKE_WORKFLOW = "./.github/workflows/desktop-bundle-smoke.yml"+BUILD_CACHE_ACTION = "./.github/actions/desktop-build-cache"+SHA = "a" * 40+CANARY_TAG = "v0.28.0+canary.20260818T101010Z"+PLATFORMS = ("darwin", "win32")+ARCHES = ("arm64", "x64")+NATIVE_TARGETS = tuple(f"{platform}-{arch}" for platform in PLATFORMS for arch in ARCHES)+# The release branch may write the shared dependency cache; commit and channel+# builds run unreviewed inputs and may only read it.+_MODE_BY_CACHE = {"write": "release", "read": "commit"}+++def load(path: Path = WORKFLOW) -> dict:+ return hermes_yaml.safe_load(path.read_text(encoding="utf-8-sig"))+++def needs_of(job: dict) -> list[str]:+ needs = job.get("needs") or []+ return [needs] if isinstance(needs, str) else list(needs)+++def _only(matches: list[str], role: str) -> str:+ assert len(matches) == 1, f"expected exactly one {role} job, found {matches}"+ return matches[0]+++def native_builds(jobs: dict) -> dict[tuple[str, str], str]:+ """``(target, "release" | "commit")`` -> id of that native build leg."""+ legs: dict[tuple[str, str], str] = {}+ for name, job in jobs.items():+ if not any(step.get("uses") == BUILD_CACHE_ACTION for step in job.get("steps", [])):+ continue+ (target,) = [row["label"] for row in job["strategy"]["matrix"]["target"]]+ key = (target, _MODE_BY_CACHE[job["cache-mode"]])+ assert key not in legs, f"{name} and {legs[key]} both build {key}"+ legs[key] = name+ assert {target for target, _ in legs} == set(NATIVE_TARGETS), legs+ assert len(legs) == 2 * len(NATIVE_TARGETS), legs+ return legs+++def selection_gates(jobs: dict) -> dict[str, str]:+ """target -> the job that turns "one trust branch ran" into one result."""+ legs = native_builds(jobs)+ gates = {}+ for target in NATIVE_TARGETS:+ pair = {legs[(target, "release")], legs[(target, "commit")]}+ gates[target] = _only([name for name, job in jobs.items() if pair <= set(needs_of(job))],+ f"{target} selection gate")+ return gates+++def smoke_callers(jobs: dict) -> dict[str, str]:+ """target -> the job that calls the reusable native smoke for it."""+ callers: dict[str, str] = {}+ for name, job in jobs.items():+ if job.get("uses") == SMOKE_WORKFLOW:+ target = f"{job['with']['platform']}-{job['with']['arch']}"+ assert target not in callers, f"{name} and {callers[target]} both smoke {target}"+ callers[target] = name+ assert set(callers) == set(NATIVE_TARGETS), callers+ return callers+++def _stages(job: dict, receipt: str) -> bool:+ return any("scripts.releases.handoff stage" in step.get("run", "")+ and re.search(rf"--name\s+{re.escape(receipt)}\b", step["run"])+ for step in job.get("steps", []))+++def universal_assembler(jobs: dict) -> str:+ return _only([name for name, job in jobs.items() if _stages(job, "windows-universal")],+ "universal bundle assembly")+++def termux_builder(jobs: dict) -> str:+ return _only([name for name, job in jobs.items() if _stages(job, "termux")], "termux deb")+++def updater_publishers(jobs: dict) -> dict[str, str]:+ """platform -> the job that publishes that platform's updater feed.++ It is the job gated on exactly that platform's smokes; channel publication+ and summaries need every platform's smoke.+ """+ smokes = smoke_callers(jobs)+ publishers = {}+ for platform in PLATFORMS:+ own = {smokes[f"{platform}-{arch}"] for arch in ARCHES}+ publishers[platform] = _only(+ [name for name, job in jobs.items() if set(needs_of(job)) & set(smokes.values()) == own],+ f"{platform} updater publisher")+ return publishers+++def _renders(job: dict, flag: str) -> bool:+ return any("render-builds-table.py" in step.get("run", "") and flag in step["run"]+ for step in job.get("steps", []))+++def channel_publisher(jobs: dict) -> str:+ return _only([name for name, job in jobs.items() if _renders(job, "--channel-build")],+ "channel publisher")+++def commit_summary(jobs: dict) -> str:+ return _only([name for name, job in jobs.items() if _renders(job, "--summary-commit")],+ "commit build summary")+++def canary_publisher(jobs: dict) -> str:+ return _only([name for name, job in jobs.items()+ if any("scripts.releases.channel_releases canary" in step.get("run", "")+ for step in job.get("steps", []))], "canary publisher")+++def phase_result(jobs: dict) -> str:+ """The stable-phase verdict: the job that judges every phase job's result."""+ return _only([name for name, job in jobs.items()+ if any({"RELEASE_NEEDS", "SKIP_TESTS"} <= set(step.get("env") or {})+ for step in job.get("steps", []))], "stable phase result")+++def stage_step(job: dict, *, channel: bool = False) -> dict:+ """The step that stages this job's receipt, for a channel or tag/commit build."""+ flag = "--channel-request" if channel else "--commit-build"+ (step,) = [step for step in job["steps"]+ if "scripts.releases.handoff stage" in step.get("run", "") and flag in step["run"]]+ return step+++def credential_gate(job: dict) -> dict:+ """The step that refuses to build when signing credentials are missing."""+ (step,) = [step for step in job["steps"]+ if step.get("env") and re.search(r"::error::required .*missing", step.get("run", ""))]+ return step+++# Dispatch shapes that produce downloadable artifacts, keyed by trust branch.+DOWNLOADABLE_DISPATCHES = {+ "tag": {"tag": CANARY_TAG, "upload_release": True, "build_commit": "", "channel": "",+ "release-phase": "", "jobs": ",".join(JOB_GROUPS)},+ "candidate": {"tag": "v0.28.0", "upload_release": False, "build_commit": "", "channel": "",+ "release-phase": "candidate", "jobs": ",".join(JOB_GROUPS)},+ "commit": {"tag": "", "upload_release": False, "build_commit": SHA, "channel": "",+ "release-phase": "", "jobs": ",".join(JOB_GROUPS)},+ "channel": {"tag": "", "upload_release": False, "build_commit": SHA, "channel": "preview",+ "release-phase": "", "jobs": ",".join(JOB_GROUPS)},+}+# A dry build: nothing leaves the runner.+DRY_DISPATCH = {"tag": "v0.28.0", "upload_release": False, "build_commit": "", "channel": "",+ "release-phase": "", "jobs": ",".join(JOB_GROUPS)}+++def admitted(names, *, channel=False):+ """Needs rows for jobs that all succeeded after validate admitted every group."""+ outputs = {"sha": SHA, **{group: "true" for group in JOB_GROUPS}}+ if channel:+ outputs["channel-build"] = "b" * 32+ return {name: {"result": "success", "outputs": dict(outputs)} for name in names}+++def evaluate(expression, inputs, needs, *, cancelled=False, failed=False, job_if=True, github=None):+ """Evaluate the workflow expression subset, including Actions' implicit success.++ This is not a scheduler simulation; native Actions still owns cancellation+ and skipped-ancestor propagation. Requiring a status function prevents an+ implicit success() from suppressing consumers of the skipped trust branch.+ ``job_if`` judges implicit success by the needs' results; a step ``if``+ (``job_if=False``) judges it by whether an earlier step ``failed``.+ """+ expression = str(expression).strip().removeprefix('${{').removesuffix('}}').strip()+ if not re.search(r'\b(always|cancelled|success|failure)\(', expression):+ if cancelled or failed:+ return False+ if job_if and any(row.get('result') != 'success' for row in needs.values()):+ return False++ def value(match):+ bits = match[0].split('.')+ result = {'inputs': inputs, 'needs': needs, 'github': github or {}}+ for bit in bits:+ result = result.get(bit, '') if isinstance(result, dict) else ''+ return repr(result)++ expression = re.sub(r'\b(?:inputs|needs|github)(?:\.[\w-]+)+', value, expression)+ expression = expression.replace('&&', ' and ').replace('||', ' or ')+ expression = re.sub(r'!(?!=)', ' not ', expression)+ expression = re.sub(r'\btrue\b', 'True', expression)+ expression = re.sub(r'\bfalse\b', 'False', expression)+ return eval('(' + expression.strip() + ')', {'__builtins__': {}}, {+ 'always': lambda: True, 'cancelled': lambda: cancelled,+ 'success': lambda: not (cancelled or failed), 'failure': lambda: failed,+ 'contains': lambda value, needle: needle in value,+ })+++def gate(expression, inputs, needs, **options) -> bool:+ return bool(evaluate(expression, inputs, needs, **options))diff --git a/tests/ci/test_desktop_bundle_smoke.py b/tests/ci/test_desktop_bundle_smoke.pyindex 814c7bba0d6..84a798e89c8 100644--- a/tests/ci/test_desktop_bundle_smoke.py+++ b/tests/ci/test_desktop_bundle_smoke.py@@ -3,7 +3,6 @@ import copyimport hashlibimport itertoolsimport json-import reimport shutilimport subprocessimport xml.etree.ElementTree as ET@@ -13,13 +12,16 @@ from pathlib import Pathimport hermes_yamlimport pytest+from tests.ci.desktop_release_roles import (+ CANARY_TAG as TAG, DOWNLOADABLE_DISPATCHES, NATIVE_TARGETS, SHA, admitted, canary_publisher,+ gate, native_builds, needs_of, phase_result, selection_gates, smoke_callers, stage_step,+ termux_builder, universal_assembler, updater_publishers,+)from tests.ci.test_commit_build_staging import ROOT, shell_stepfrom tests.ci.test_desktop_release_tag_admission import _BASH, _child_env, _workflowfrom tests.scripts.test_release_r2 import r2_server # noqa: F401from scripts.releases.job_groups import JOB_GROUPS-SHA = 'a' * 40-TAG = 'v0.28.0+canary.20260818T101010Z'ALL_JOBS = ','.join(JOB_GROUPS)@@ -27,74 +29,66 @@ def smoke_workflow():return hermes_yaml.safe_load((ROOT / '.github/workflows/desktop-bundle-smoke.yml').read_text(encoding='utf-8-sig'))-def gate(expression, inputs, needs, *, cancelled=False, job_if=True):- """Evaluate the workflow's boolean subset, including Actions' implicit success.-- This is not a scheduler simulation; native Actions still owns cancellation- and skipped-ancestor propagation. Requiring a status function prevents an- implicit success() from suppressing consumers of the skipped trust branch.- """- expression = expression.strip().removeprefix('${{').removesuffix('}}').strip()- if job_if and not re.search(r'\b(always|cancelled|success|failure)\(', expression):- if any(row.get('result') != 'success' for row in needs.values()):- return False-- def value(match):- bits = match[0].split('.')- result = {'inputs': inputs, 'needs': needs}- for bit in bits:- result = result.get(bit, '') if isinstance(result, dict) else ''- return repr(result)-- expression = re.sub(r'\b(?:inputs|needs)(?:\.[\w-]+)+', value, expression)- expression = expression.replace('&&', ' and ').replace('||', ' or ')- expression = re.sub(r'!(?!=)', ' not ', expression)- expression = re.sub(r'\btrue\b', 'True', expression)- expression = re.sub(r'\bfalse\b', 'False', expression)- return bool(eval('(' + expression.strip() + ')', {'__builtins__': {}}, {- 'always': lambda: True, 'cancelled': lambda: cancelled,- 'contains': lambda value, needle: needle in value,- }))---def admitted(jobs):- return {name: {'result': 'success',- 'outputs': {'sha': SHA, **{group: 'true' for group in JOB_GROUPS}}}- for name in jobs}+def smoke_fetch_script():+ """The public artifact fetch every smoke runner shares."""+ scripts = {step['run'] for job in smoke_workflow()['jobs'].values()+ for step in job.get('steps', []) if step.get('id') == 'artifact'}+ (script,) = scripts+ return scriptdef selected_needs(jobs, name, selected):"""Admitted needs whose validate outputs select only `selected` groups."""- needs = admitted(jobs[name]['needs'])+ needs = admitted(needs_of(jobs[name]))needs['validate']['outputs'] = {group: ('true' if group in selected else 'false')for group in JOB_GROUPS}return needs+def native_consumers(jobs):+ """Jobs that act on a native build's result rather than observe it.++ Every job that directly needs a selection gate or a smoke and does not+ opt into always() (observers such as summaries must survive failures).+ """+ producers = set(selection_gates(jobs).values()) | set(smoke_callers(jobs).values())+ return [name for name, job in jobs.items()+ if producers & set(needs_of(job)) and 'always()' not in str(job.get('if', ''))]++def test_native_consumers_and_publication_fail_closed_across_trust_skips(tmp_path):jobs = _workflow()['jobs']- base_inputs = {'build_commit': '', 'upload_release': True, 'release-phase': '', 'jobs': ALL_JOBS, 'tag': TAG}- consumers = ['smoke-darwin-arm64', 'smoke-darwin-x64', 'smoke-win32-arm64', 'smoke-win32-x64',- 'assemble-win32-bundle', 'publish-win32-updater', 'publish-darwin-updater']+ legs = native_builds(jobs)+ base_inputs = DOWNLOADABLE_DISPATCHES['tag']+ consumers = native_consumers(jobs)+ assert set(smoke_callers(jobs).values()) | {universal_assembler(jobs)} \+ | set(updater_publishers(jobs).values()) <= set(consumers), consumersfor name in consumers:job = jobs[name]- inputs = {**base_inputs, 'release-phase': ''}- needs = admitted(job['needs'])- # A skipped execution exists in the ancestry of every native result.- needs['build-win32-commit'] = {'result': 'skipped'}- assert gate(job['if'], inputs, needs), name- assert not gate(job['if'], inputs, needs, cancelled=True), name- for dependency in job['needs']:- for result in ('failure', 'skipped', 'cancelled'):- faulty = copy.deepcopy(needs)- faulty[dependency]['result'] = result- assert not gate(job['if'], inputs, faulty), (name, dependency, result)- needs['validate']['outputs'] = {}- assert not gate(job['if'], inputs, needs), name-- scope_jobs = consumers[:5]+ admitting = []+ for dispatch, inputs in DOWNLOADABLE_DISPATCHES.items():+ needs = admitted(needs_of(job), channel=dispatch == 'channel')+ # A skipped trust branch exists in the ancestry of every native result.+ needs.update({leg: {'result': 'skipped'} for leg in legs.values() if leg not in needs})+ if gate(job['if'], inputs, needs):+ admitting.append((dispatch, inputs, needs))+ assert admitting, f'{name} never runs for a downloadable build'+ for dispatch, inputs, needs in admitting:+ assert not gate(job['if'], inputs, needs, cancelled=True), (name, dispatch)+ for dependency in needs_of(job):+ for result in ('failure', 'skipped', 'cancelled'):+ faulty = copy.deepcopy(needs)+ faulty[dependency]['result'] = result+ assert not gate(job['if'], inputs, faulty), (name, dispatch, dependency, result)+ emptied = copy.deepcopy(needs)+ emptied['validate']['outputs'] = {}+ assert not gate(job['if'], inputs, emptied), (name, dispatch)++ # Smokes and the universal assembly run for every downloadable build of+ # the build phase, and never for dry runs or later stable phases.+ scope_jobs = list(smoke_callers(jobs).values()) + [universal_assembler(jobs)]for name in scope_jobs:- needs = admitted(jobs[name]['needs'])+ needs = admitted(needs_of(jobs[name]))for phase, commit, upload, allowed in [('', SHA, False, True), ('candidate', '', False, True),('', '', True, True), ('', '', False, False),@@ -104,43 +98,56 @@ def test_native_consumers_and_publication_fail_closed_across_trust_skips(tmp_pat'upload_release': upload}assert gate(jobs[name]['if'], inputs, needs) is allowed, (name, inputs)# A group the caller did not select stays skipped; its consumers refuse.- for name in ('smoke-darwin-arm64', 'smoke-darwin-x64', 'smoke-win32-arm64', 'smoke-win32-x64',- 'assemble-win32-bundle'):+ for name in scope_jobs:assert not gate(jobs[name]['if'], base_inputs,selected_needs(jobs, name, {'termux'})), name- for name in ('publish-win32-updater', 'publish-darwin-updater'):+ for platform, name in updater_publishers(jobs).items():for key, value in [('build_commit', SHA), ('upload_release', False),('release-phase', 'candidate'), ('release-phase', 'promote')]:- assert not gate(jobs[name]['if'], {**base_inputs, key: value}, admitted(jobs[name]['needs']))- groups = ['darwin-arm64', 'darwin-x64'] if name == 'publish-darwin-updater' \- else ['win32-arm64', 'win32-x64', 'win32-bundle']+ assert not gate(jobs[name]['if'], {**base_inputs, key: value}, admitted(needs_of(jobs[name])))+ groups = [target for target in NATIVE_TARGETS if target.startswith(f'{platform}-')]+ if platform == 'win32':+ groups.append('win32-bundle')for group in groups:assert not gate(jobs[name]['if'], base_inputs,selected_needs(jobs, name, {group})), (name, group)- for platform in ('win32', 'darwin'):- for arch in ('x64', 'arm64'):- job = jobs[f'build-{platform}-{arch}']- outcomes = ('success', 'failure', 'skipped', 'cancelled')- for commit, release, commit_result in itertools.product(- ('', SHA), outcomes, outcomes):- needs = admitted(job['needs'])- needs[f'build-{platform}-{arch}-release'] = {'result': release}- needs[f'build-{platform}-{arch}-commit'] = {'result': commit_result}- selected = gate(job['env']['SELECTED_BUILD_SUCCEEDED'], {'build_commit': commit}, needs, job_if=False)- expected = (commit == '' and release == 'success' and commit_result == 'skipped') or (- commit != '' and commit_result == 'success' and release == 'skipped')- assert selected is expected- result = subprocess.run([_BASH, '-e', '-c', job['steps'][0]['run']], cwd=tmp_path,- env=_child_env(SELECTED_BUILD_SUCCEEDED=str(selected).lower()),- capture_output=True, text=True, timeout=5)- assert (result.returncode == 0) is expected+ for target, name in selection_gates(jobs).items():+ job = jobs[name]+ release, commit_leg = legs[(target, 'release')], legs[(target, 'commit')]+ outcomes = ('success', 'failure', 'skipped', 'cancelled')+ for commit, release_result, commit_result in itertools.product(('', SHA), outcomes, outcomes):+ needs = admitted(needs_of(job))+ needs[release] = {'result': release_result}+ needs[commit_leg] = {'result': commit_result}+ selected = gate(job['env']['SELECTED_BUILD_SUCCEEDED'], {'build_commit': commit}, needs, job_if=False)+ expected = (commit == '' and release_result == 'success' and commit_result == 'skipped') or (+ commit != '' and commit_result == 'success' and release_result == 'skipped')+ assert selected is expected+ (check,) = [step for step in job['steps'] if 'run' in step]+ result = subprocess.run([_BASH, '-e', '-c', check['run']], cwd=tmp_path,+ env=_child_env(SELECTED_BUILD_SUCCEEDED=str(selected).lower()),+ capture_output=True, text=True, timeout=5)+ assert (result.returncode == 0) is expected+++def test_only_selection_gates_consume_native_build_legs():+ """Every consumer sees a build through its selection gate, which requires+ the chosen trust branch to succeed; a direct need would accept a skip."""+ jobs = _workflow()['jobs']+ legs = set(native_builds(jobs).values())+ gates = set(selection_gates(jobs).values())+ for name, job in jobs.items():+ assert not (legs & set(needs_of(job))) or name in gates, f'{name} needs a native build leg directly'def test_signature_cache_saves_only_in_the_writable_build():jobs = _workflow()['jobs']- for branch, commit in [('release', ''), ('commit', SHA)]:- job = jobs[f'build-win32-x64-{branch}']+ windows = [(name, mode) for (target, mode), name in native_builds(jobs).items() if target.startswith('win32-')]+ assert {mode for _, mode in windows} == {'release', 'commit'}+ for name, mode in windows:+ commit = SHA if mode == 'commit' else ''+ job = jobs[name]steps = job['steps']cache_steps = [step for step in stepsif 'payload-signatures' in step.get('with', {}).get('path', '')]@@ -152,14 +159,17 @@ def test_signature_cache_saves_only_in_the_writable_build():assert gate(save['if'], {'build_commit': commit}, {}, job_if=False) is (job['cache-mode'] == 'write')verify = next(step for step in steps if step.get('name') == 'Verify native signature cache contracts')assert steps.index(restore) < steps.index(verify) < steps.index(save)- assembly = jobs['assemble-win32-bundle']+ assembly = jobs[universal_assembler(jobs)]assert assembly['cache-mode'] == 'read'setup = next(step for step in assembly['steps'] if step.get('uses') == './.github/actions/setup-pm')assert setup['with']['cache-python'] is Falseassert setup['with']['save-tools-cache'] is False and setup['with']['save-node-cache'] is Falseaction = hermes_yaml.safe_load((ROOT / '.github/actions/setup-pm/action.yml').read_text())tools = next(step for step in action['runs']['steps'] if step.get('id') == 'tools-cache')- assert "inputs.save-tools-cache == 'true'" in tools['if']+ # The assembly's save-tools-cache: false must turn the tool cache save off.+ enabled = {'cache': 'true', 'save-tools-cache': 'true'}+ assert gate(tools['if'], enabled, {}, job_if=False)+ assert not gate(tools['if'], {**enabled, 'save-tools-cache': 'false'}, {}, job_if=False)assert all(not step.get('uses', '').startswith('actions/cache@') for step in assembly['steps'])@@ -167,7 +177,7 @@ def test_smoke_matrix_native_routes_and_driver_only_dependencies():workflow = smoke_workflow()jobs = _workflow()['jobs']executions = []- for name in ('smoke-darwin-arm64', 'smoke-darwin-x64', 'smoke-win32-arm64', 'smoke-win32-x64'):+ for name in smoke_callers(jobs).values():caller = jobs[name]assert caller['permissions'] == {'contents': 'read'} and 'secrets' not in callerformats = caller.get('strategy', {}).get('matrix', {}).get('format', [caller['with']['format']])@@ -176,12 +186,12 @@ def test_smoke_matrix_native_routes_and_driver_only_dependencies():assert set(executions) == {(platform, arch, fmt) for arch in ('arm64', 'x64')for platform, formats in [('darwin', ('dmg', 'zip')), ('win32', ('msix',))]for fmt in formats}- for name, job in workflow['jobs'].items():- # validate is the admission job (rejects unsupported targets before any- # runner spawns, no checkout, no runner resources); every other job is a- # read-only smoke runner.- if name == 'validate':- continue+ runners = {name: job for name, job in workflow['jobs'].items()+ if any('actions/checkout@' in step.get('uses', '') for step in job.get('steps', []))}+ # The admission job rejects unsupported targets before any runner spawns+ # and needs no source; every job that checks out is a read-only smoke runner.+ assert runners and len(runners) < len(workflow['jobs'])+ for name, job in runners.items():assert job['cache-mode'] == 'read' and 'environment' not in jobcheckout = next(step for step in job['steps'] if 'actions/checkout@' in step.get('uses', ''))assert checkout['with']['persist-credentials'] is False@@ -193,14 +203,16 @@ def test_smoke_matrix_native_routes_and_driver_only_dependencies():recording = next(step for step in job['steps'] if step.get('id') == 'recording')assert 'save-cache' not in recording['with']upload = next(step for step in job['steps'] if 'actions/upload-artifact@' in step.get('uses', ''))- assert upload['if'] == 'always()' and upload['with']['path'].endswith('/out')+ # Evidence of a failed verdict is the evidence that matters.+ assert gate(upload['if'], {}, {}, job_if=False, failed=True)+ assert upload['with']['path'].endswith('/out')# The chat steps are the smoke verdict. Recording stop and artifact# upload run after that and are evidence; a 403 there must not fail# the job or skip channel publication.stop = next(step for step in job['steps'] if step.get('name') == 'Stop screen recording')assert stop['continue-on-error'] is True and upload['continue-on-error'] is True- for verdict in ('Install and chat on macOS', 'Install and chat on Windows'):- chat = next(step for step in job['steps'] if step.get('name') == verdict)+ for verdict in ('macos-chat', 'windows-chat'):+ chat = next(step for step in job['steps'] if step.get('id') == verdict)assert 'continue-on-error' not in chatrecorder = hermes_yaml.safe_load((ROOT / '.github/actions/e2e-screen-record/action.yml').read_text())@@ -208,7 +220,8 @@ def test_smoke_matrix_native_routes_and_driver_only_dependencies():assert 'save-cache' not in recorder['inputs']# ffmpeg comes from the PM toolchain: the action must verify, not install.verify = next(step for step in recorder['runs']['steps'] if step.get('name') == 'Verify ffmpeg from the PM toolchain')- assert verify['if'] == "inputs.mode == 'start'"+ assert gate(verify['if'], {'mode': 'start'}, {}, job_if=False)+ assert not gate(verify['if'], {'mode': 'stop'}, {}, job_if=False)for step in recorder['runs']['steps']:run = step.get('run', '')assert 'ffmpeg' not in run or 'winget' not in run and 'brew install' not in run and 'apt-get' not in run, \@@ -217,11 +230,12 @@ def test_smoke_matrix_native_routes_and_driver_only_dependencies():workflows = [workflow] + [hermes_yaml.safe_load((ROOT / '.github/workflows' / name).read_text(encoding='utf-8-sig'))for name in ('install-e2e-run.yml', 'install-e2e-macos-run.yml', 'install-e2e-windows-run.yml')]for document in workflows:- for name, job in document['jobs'].items():- if 'steps' not in job or name == 'validate':- # the smoke workflow's validate job rejects unsupported targets- # with a bare case statement; it needs no toolchain setup.- continue+ # A job that never checks out (the smoke admission job's bare case+ # statement) needs no toolchain.+ drivers = [job for job in document['jobs'].values()+ if any('actions/checkout@' in step.get('uses', '') for step in job.get('steps', []))]+ assert drivers+ for job in drivers:steps = job['steps']setup = next(step for step in steps if step.get('uses') == './.github/actions/setup-pm')assert setup['with']['toolchain'] == 'all' and not setup['with'].get('extras')@@ -257,19 +271,18 @@ def test_public_smoke_fetches_the_receipt_bound_native_format(tmp_path, r2_serve(release / filename).write_bytes(payload)(release / ('Store-' + filename)).write_bytes(b'not eligible')universal = fmt == 'msixbundle'- job = 'assemble-win32-bundle' if universal else f'build-{platform}-{arch}-commit'- stage = 'Stage universal bundles to R2' if universal else (- 'Stage Windows packages to R2' if platform == 'win32' else 'Stage macOS packages and feed inputs to R2')+ jobs = _workflow()['jobs']+ producer = universal_assembler(jobs) if universal else native_builds(jobs)[(f'{platform}-{arch}', 'commit')]if platform == 'darwin':# The producer stages all of its formats together; smoke selects one.for ext in ('dmg', 'zip', 'zip.blockmap'):(release / f'HermesBundled-0.28.0-mac-{arch}.{ext}').write_bytes(payload)(release / f'{arch}-canary-mac.yml').write_bytes(payload)- staged = shell_step(tmp_path, r2_server, job, stage, {**env, 'TARGET': f'{platform}-{arch}'})+ staged = shell_step(tmp_path, r2_server, '', '', {**env, 'TARGET': f'{platform}-{arch}'},+ script=stage_step(jobs[producer])['run'])assert staged.returncode == 0, staged.stdout + staged.stderrassert all('/canary/' not in key for key in r2_server.store)- script = next(step['run'] for step in smoke_workflow()['jobs']['macos']['steps']- if step.get('id') == 'artifact')+ script = smoke_fetch_script()# Deliberately remove every storage credential before executing public fetch.public_env = {key: '' if key.startswith('CLOUDFLARE_') else value for key, value in env.items()}public_env.update(PLATFORM=platform, ARCH=arch, FORMAT=fmt)@@ -301,7 +314,7 @@ def test_download_faults_never_export_an_accepted_artifact(tmp_path, r2_server,receipt['files'].append({**row, 'path': second})r2_server.store[prefix + second] = (payload, '"e"')r2_server.store[prefix + 'handoff-win32-x64.json'] = (json.dumps(receipt).encode(), '"e"')- script = next(step['run'] for step in smoke_workflow()['jobs']['macos']['steps'] if step.get('id') == 'artifact')+ script = smoke_fetch_script()result = shell_step(tmp_path, r2_server, '', '', {**env, 'PLATFORM': 'win32', 'ARCH': 'x64', 'FORMAT': 'msix'}, script=script)assert result.returncode != 0assert not (tmp_path / 'output').exists()@@ -310,61 +323,71 @@ def test_download_faults_never_export_an_accepted_artifact(tmp_path, r2_server,def test_stable_phase_and_canary_gates_require_smoke_but_preserve_other_phases(tmp_path, r2_server):jobs = _workflow()['jobs']- group_jobs = {- 'darwin-arm64': ['build-darwin-arm64', 'smoke-darwin-arm64'],- 'darwin-x64': ['build-darwin-x64', 'smoke-darwin-x64'],- 'win32-arm64': ['build-win32-arm64', 'smoke-win32-arm64'],- 'win32-x64': ['build-win32-x64', 'smoke-win32-x64'],- 'win32-bundle': ['assemble-win32-bundle'],- 'termux': ['termux-deb'],- }+ gates, smokes = selection_gates(jobs), smoke_callers(jobs)+ group_jobs = {target: [gates[target], smokes[target]] for target in NATIVE_TARGETS}+ group_jobs['win32-bundle'] = [universal_assembler(jobs)]+ group_jobs['termux'] = [termux_builder(jobs)]+ verdict = phase_result(jobs)+ members = {member for group in group_jobs.values() for member in group}+ # What the verdict needs beyond admission and the build groups is the+ # publication itself; the Store submission follows the file publication.+ (publish,) = [name for name in needs_of(jobs[verdict]) if name not in members | {'validate'}+ and not set(needs_of(jobs[name])) - {'validate'}]+ (store,) = [name for name in needs_of(jobs[verdict]) if publish in needs_of(jobs[name])]def run_phase(phase, selected, failed=None, skip_tests=False):- needs = {name: {'result': 'success'} for name in jobs['stable-phase-result']['needs']}+ needs = {name: {'result': 'success'} for name in needs_of(jobs[verdict])}needs['validate']['outputs'] = {group: ('true' if group in selected else 'false')for group in group_jobs}- for group, members in group_jobs.items():+ for group, group_members in group_jobs.items():if group not in selected:- for member in members:+ for member in group_members:needs[member]['result'] = 'skipped'if skip_tests:- for members in group_jobs.values():- for member in members:- if member.startswith('smoke-'):- needs[member]['result'] = 'skipped'+ for smoke in smokes.values():+ needs[smoke]['result'] = 'skipped'if failed:needs[failed]['result'] = 'cancelled'- return shell_step(tmp_path, r2_server, 'stable-phase-result', 'Require every phase job',+ (step,) = [step for step in jobs[verdict]['steps'] if 'SKIP_TESTS' in (step.get('env') or {})]+ return shell_step(tmp_path, r2_server, '', '',{'RELEASE_NEEDS': json.dumps(needs), 'RELEASE_PHASE': phase,- 'SKIP_TESTS': 'true' if skip_tests else 'false'})+ 'SKIP_TESTS': 'true' if skip_tests else 'false'}, script=step['run'])every = set(group_jobs)assert run_phase('candidate', every).returncode == 0# A claim that skipped tests runs no smoke, and every build still counts.assert run_phase('candidate', every, skip_tests=True).returncode == 0- assert run_phase('candidate', every, failed='build-win32-x64', skip_tests=True).returncode != 0+ assert run_phase('candidate', every, failed=gates['win32-x64'], skip_tests=True).returncode != 0assert run_phase('publish', every).returncode == 0assert run_phase('publish', every - {'termux'}).returncode == 0for group in group_jobs:# A group that was not selected is not a failure of the phase.assert run_phase('candidate', every - {group}).returncode == 0, group- for failed in ('smoke-darwin-arm64', 'build-win32-x64', 'termux-deb'):+ for failed in (smokes['darwin-arm64'], gates['win32-x64'], termux_builder(jobs)):assert run_phase('candidate', every, failed=failed).returncode != 0, failed- assert run_phase('candidate', every, failed='stable-publish').returncode == 0+ assert run_phase('candidate', every, failed=publish).returncode == 0# A partial selection still judges the groups it selected.assert run_phase('candidate', {'darwin-arm64'}).returncode == 0- assert run_phase('candidate', {'darwin-arm64'}, failed='smoke-darwin-arm64').returncode != 0- assert run_phase('publish', set(), failed='stable-store').returncode != 0+ assert run_phase('candidate', {'darwin-arm64'}, failed=smokes['darwin-arm64']).returncode != 0+ assert run_phase('publish', set(), failed=store).returncode != 0+ canary = jobs[canary_publisher(jobs)]inputs = {'build_commit': '', 'upload_release': True, 'tag': TAG}- needs = admitted(jobs['publish-canary']['needs'])- assert gate(jobs['publish-canary']['if'], inputs, needs)- for name in ('smoke-darwin-arm64', 'smoke-darwin-x64', 'smoke-win32-arm64', 'smoke-win32-x64',- 'build-linux-x64', 'build-linux-arm64'):+ needs = admitted(needs_of(canary))+ assert gate(canary['if'], inputs, needs)+ # The publisher runs always() to report, so it must itself refuse any+ # prerequisite that did not succeed: builds, smokes, updaters, the table.+ for name in needs_of(canary):+ if name == 'validate':+ continuefor state in ('failure', 'skipped', 'cancelled'):faulty = copy.deepcopy(needs)faulty[name]['result'] = state- assert not gate(jobs['publish-canary']['if'], inputs, faulty)+ assert not gate(canary['if'], inputs, faulty), (name, state)+ emptied = copy.deepcopy(needs)+ emptied['validate']['outputs'] = {}+ assert not gate(canary['if'], inputs, emptied)+ assert not gate(canary['if'], {**inputs, 'tag': 'v0.28.0'}, needs), 'a stable tag is not a canary'def test_canary_publisher_consumes_staged_bytes_and_writes_pointer_last(tmp_path, r2_server):@@ -407,7 +430,9 @@ def test_canary_publisher_consumes_staged_bytes_and_writes_pointer_last(tmp_path'Publisher="CN=Nous Research Inc., O=Nous Research Inc., L=Austin, S=Texas, C=US" 'f'Version="{version}"/></Bundle>')tested_bytes = bundle.read_bytes()- staged = shell_step(tmp_path, r2_server, 'assemble-win32-bundle', 'Stage universal bundles to R2', env)+ jobs = _workflow()['jobs']+ publisher = updater_publishers(jobs)['win32']+ staged = shell_step(tmp_path, r2_server, '', '', env, script=stage_step(jobs[universal_assembler(jobs)])['run'])assert staged.returncode == 0, staged.stdout + staged.stderrassert all(key.startswith(f'releases/tag/{tag}/') for key in r2_server.store)# A newer stable becomes visible after assembly but cannot alter the@@ -416,7 +441,7 @@ def test_canary_publisher_consumes_staged_bytes_and_writes_pointer_last(tmp_pathgit('tag', 'v0.28.1')assert assembly_identity()['version'] == versionfor name in ('Retrieve the tested universal bundle', 'Publish identical tested bytes without rebuilding'):- result = shell_step(tmp_path, r2_server, 'publish-win32-updater', name, env)+ result = shell_step(tmp_path, r2_server, publisher, name, env)assert result.returncode == 0, result.stdout + result.stderrassert (tmp_path / 'staged' / filename).read_bytes() == tested_bytesassert r2_server.store[f'releases/win32/canary/{filename}'][0] == tested_bytes@@ -431,7 +456,7 @@ def test_canary_publisher_consumes_staged_bytes_and_writes_pointer_last(tmp_path# caller accidentally broadens the receipt selector in future.(tmp_path / 'staged/HermesBundled-0.29.0.0-win.msixbundle').write_bytes(tested_bytes)before = len(writes)- refused = shell_step(tmp_path, r2_server, 'publish-win32-updater',+ refused = shell_step(tmp_path, r2_server, publisher,'Publish identical tested bytes without rebuilding', env)assert refused.returncode != 0assert len([row for row in r2_server.requests if row[0] == 'PUT']) == before@@ -448,7 +473,7 @@ def test_canary_publisher_consumes_staged_bytes_and_writes_pointer_last(tmp_pathnative.set(field, wrong)with zipfile.ZipFile(staged_bundle, 'w') as archive:archive.writestr('AppxMetadata/AppxBundleManifest.xml', ET.tostring(manifest))- refused = shell_step(tmp_path, r2_server, 'publish-win32-updater',+ refused = shell_step(tmp_path, r2_server, publisher,'Publish identical tested bytes without rebuilding', env)assert refused.returncode != 0, fieldassert len([row for row in r2_server.requests if row[0] == 'PUT']) == before@@ -456,7 +481,7 @@ def test_canary_publisher_consumes_staged_bytes_and_writes_pointer_last(tmp_pathfor wrong in ['HermesBundled-0.29.0.0-win.msixbundle', 'HermesBundled-0.28.1.65536-win.msixbundle','HermesBundled-0.28.1-canary.20260818101010-win.msixbundle']:renamed = staged_bundle.rename(staged_bundle.with_name(wrong))- refused = shell_step(tmp_path, r2_server, 'publish-win32-updater',+ refused = shell_step(tmp_path, r2_server, publisher,'Publish identical tested bytes without rebuilding', env)assert refused.returncode != 0, wrongassert len([row for row in r2_server.requests if row[0] == 'PUT']) == beforediff --git a/tests/ci/test_desktop_release_tag_admission.py b/tests/ci/test_desktop_release_tag_admission.pyindex 3fa09560767..22cf1b88dac 100644--- a/tests/ci/test_desktop_release_tag_admission.py+++ b/tests/ci/test_desktop_release_tag_admission.py@@ -22,9 +22,15 @@ from pathlib import Pathimport pytest+from tests.ci.desktop_release_roles import (+ DOWNLOADABLE_DISPATCHES, DRY_DISPATCH, SHA, admitted, credential_gate, evaluate, gate,+ native_builds, needs_of,+)+_REPO = Path(__file__).resolve().parents[2]_WORKFLOW = _REPO / ".github" / "workflows" / "desktop-bundled-release.yml"_SIGNING_ENV = "release-signing"+_CONTROLLER = "c" * 40def _workflow() -> dict:@@ -32,7 +38,6 @@ def _workflow() -> dict:return yaml.safe_load(_WORKFLOW.read_text(encoding="utf-8"))-# ---------------------------------------------------------------------------# Structure: the admitted SHA is the only build input privileged jobs see.# ---------------------------------------------------------------------------@@ -45,42 +50,49 @@ def test_validate_exports_the_admitted_sha_as_a_job_output():assert "steps.admission.outputs.sha" in outputs["sha"]+def _checkout_refs(job: dict, inputs: dict, needs: dict) -> list:+ """The revision each checkout that runs under *inputs* resolves to, in order."""+ refs = []+ for step in job.get("steps", []):+ if "checkout" not in step.get("uses", ""):+ continue+ if "if" in step and not gate(step["if"], inputs, needs, job_if=False):+ continue+ refs.append(evaluate(step.get("with", {}).get("ref", ""), inputs, needs,+ job_if=False, github={"sha": _CONTROLLER}))+ return refs++def test_signing_jobs_pin_source_and_controller_revisions_not_mutable_tags():- wf = _workflow()- privileged = {- name: job- for name, job in wf["jobs"].items()- if (isinstance(job, dict) and job.get("environment") == _SIGNING_ENV)- }+ jobs = _workflow()["jobs"]+ privileged = {name: job for name, job in jobs.items()+ if isinstance(job, dict) and job.get("environment") == _SIGNING_ENV}assert privileged, "walk broken: no release-signing jobs found"-- for name, job in privileged.items():- for step in job.get("steps", []):- if "checkout" not in step.get("uses", ""):- continue- ref = step.get("with", {}).get("ref")- expected = "${{ needs.validate.outputs.sha }}"- if (name in {"publish-channel"}- or step.get("if") == "needs.validate.outputs.channel-build != ''"- or step.get("name") == "Return to the trusted receipt controller"):- expected = "${{ github.sha }}"- elif name == "validate":- expected = "${{ (inputs.build_commit != '' || inputs.channel != '' || inputs.release-phase != '') && github.sha || inputs.tag }}"- elif name == "assemble-win32-bundle":- expected = "${{ needs.validate.outputs.channel-build != '' && github.sha || needs.validate.outputs.sha }}"- assert ref == expected, (- f"signing job {name!r} checks out {ref!r} — it must check out "- "the admitted source or explicitly selected trusted controller, never a mutable tag"- )- # The merged validate job owns allocation and admission; it consumes no- # prior admission (the one-dispatch design).+ # The admission job has nothing admitted yet; it resolves the revision+ # every other signing job consumes (the one-dispatch design).+ admission = [name for name, job in privileged.items() if not needs_of(job)]+ assert admission == ["validate"], admission+ exercised = set()for name, job in privileged.items():if name == "validate":- assert job.get("needs") in ([], None)continue- needs = job.get("needs") or []- needs = [needs] if isinstance(needs, str) else needs- assert "validate" in needs, f"signing job {name!r} reads needs.validate.outputs.sha but does not need validate"+ assert "validate" in needs_of(job), f"signing job {name!r} reads needs.validate.outputs.sha but does not need validate"+ for dispatch, inputs in DOWNLOADABLE_DISPATCHES.items():+ channel = dispatch == "channel"+ needs = admitted(needs_of(job), channel=channel)+ if "if" in job and not gate(job["if"], inputs, needs):+ continue+ refs = _checkout_refs(job, inputs, needs)+ exercised.add(name)+ # Only the admitted source or this run's own trusted controller+ # may be checked out; a tag can be moved after admission.+ assert set(refs) <= {SHA, _CONTROLLER}, (name, dispatch, refs)+ if refs and not channel:+ assert refs[0] == SHA, (+ f"signing job {name!r} builds from {refs[0]!r} for a {dispatch} build; "+ "outside a pinned channel build it must build the admitted source")+ assert set(native_builds(jobs).values()) <= exercised, "walk broken: a native build leg never ran"+ assert exercised, "walk broken: no signing job runs for a downloadable build"# ---------------------------------------------------------------------------@@ -235,32 +247,43 @@ def test_malformed_claim_is_refused(tmp_path: Path):assert "is not a claim tag" in proc.stdout + proc.stderr-def _require_step(job: str, name_prefix: str) -> dict:- steps = _workflow()["jobs"][job]["steps"]- (step,) = [s for s in steps if isinstance(s, dict) and s.get("name", "").startswith(name_prefix)]- return step+def _builds(step: dict) -> bool:+ run = step.get("run", "")+ return "scripts/bundles/desktop.py" in run and "--prepared " in run@pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash")-def test_downloadable_windows_builds_refuse_to_ship_unsigned(tmp_path: Path):- """The Windows signer only warns without AZURE_SIGN_*; every lane whose- artifacts are downloadable must therefore fail before building, under- the same gate the macOS leg uses for its signing credentials."""- step = _require_step("build-win32-x64-release", "Require Azure signing")- assert step["if"] == _require_step("build-darwin-arm64-release", "Require signing credentials")["if"]- assert "build-commit" not in step["if"] and "release-phase == 'candidate'" in step["if"]- names = list(step["env"])- assert {"AZURE_SIGN_ENDPOINT", "AZURE_SIGN_ACCOUNT", "AZURE_SIGN_PROFILE", "AZURE_CLIENT_ID"} <= set(names)-- def run(**values: str) -> subprocess.CompletedProcess:- env = {"PATH": os.environ["PATH"], "RUNNER_TEMP": str(tmp_path)}- env.update({name: "" for name in names})- env.update(values)- return subprocess.run(["bash", "-euo", "pipefail", "-c", step["run"]], env=env,- capture_output=True, text=True, timeout=60)-- proc = run()- assert proc.returncode != 0 and "::error::" in proc.stdout and "AZURE_SIGN_ENDPOINT" in proc.stdout- assert run(**{name: "x" for name in names}).returncode == 0- partial = run(**{name: "x" for name in names if name != "AZURE_CLIENT_ID"})- assert partial.returncode != 0 and "AZURE_CLIENT_ID" in partial.stdout+def test_downloadable_native_builds_refuse_to_ship_unsigned(tmp_path: Path):+ """The Windows signer only warns without AZURE_SIGN_*; every native build+ leg whose artifacts are downloadable must therefore fail before building,+ under one gate shared with the macOS signing-credential check."""+ jobs = _workflow()["jobs"]+ legs = native_builds(jobs)+ for name in legs.values():+ steps = jobs[name]["steps"]+ step = credential_gate(jobs[name])+ builds = [index for index, candidate in enumerate(steps) if _builds(candidate)]+ assert builds and steps.index(step) < builds[0], f"{name} checks credentials after building"+ for dispatch, inputs in DOWNLOADABLE_DISPATCHES.items():+ assert gate(step["if"], inputs, {}, job_if=False), (name, dispatch)+ assert not gate(step["if"], DRY_DISPATCH, {}, job_if=False), name++ windows = {credential_gate(jobs[name])["run"]: credential_gate(jobs[name])+ for (target, _), name in legs.items() if target.startswith("win32-")}+ assert windows, "walk broken: no Windows build legs"+ for step in windows.values():+ names = list(step["env"])+ assert {"AZURE_SIGN_ENDPOINT", "AZURE_SIGN_ACCOUNT", "AZURE_SIGN_PROFILE", "AZURE_CLIENT_ID"} <= set(names)++ def run(**values: str) -> subprocess.CompletedProcess:+ env = {"PATH": os.environ["PATH"], "RUNNER_TEMP": str(tmp_path)}+ env.update({name: "" for name in names})+ env.update(values)+ return subprocess.run(["bash", "-euo", "pipefail", "-c", step["run"]], env=env,+ capture_output=True, text=True, timeout=60)++ proc = run()+ assert proc.returncode != 0 and "::error::" in proc.stdout and "AZURE_SIGN_ENDPOINT" in proc.stdout+ assert run(**{name: "x" for name in names}).returncode == 0+ partial = run(**{name: "x" for name in names if name != "AZURE_CLIENT_ID"})+ assert partial.returncode != 0 and "AZURE_CLIENT_ID" in partial.stdout