The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
ci: route update owners by the import graph and dispatch every set lane
Teknium5a36d5ac3493
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yamlindex 055e6c398cd..308b9982463 100644--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@ -122,7 +122,9 @@ jobs:tests:name: Python testsneeds: detect- if: needs.detect.outputs.python == 'true'+ # Its E2E jobs are lanes of their own: a lane the classifier sets must reach+ # its job whatever `python` says (tests/ci/test_update_ci_routing.py).+ if: needs.detect.outputs.python == 'true' || needs.detect.outputs.e2e == 'true' || needs.detect.outputs.e2e_upgrade == 'true'uses: ./.github/workflows/tests.ymlwith:e2e: ${{ needs.detect.outputs.e2e == 'true' }}@@ -131,11 +133,13 @@ jobs:# macOS + Windows lanes. The main `tests` lane above is Linux-only, and# the OS-marked tests it collects are skipped there by design (see the# `_OS_MARKS` comment in tests/conftest.py) — this is where they run.- # Same `python` lane gate: if no Python changed, neither runs.+ # Gated on `python` and on each lane it consumes: desktop_updater is set by+ # TypeScript-only changes too (the Electron marker / result readers), and with+ # `python` alone those never reached the Windows hand-off tests below.tests-os:name: OS-specific testsneeds: detect- if: needs.detect.outputs.python == 'true'+ if: needs.detect.outputs.python == 'true' || needs.detect.outputs.desktop_updater == 'true' || needs.detect.outputs.e2e == 'true' || needs.detect.outputs.e2e_upgrade == 'true'uses: ./.github/workflows/tests-os.ymlwith:# The Windows lane spawns the real desktop-update hand-off scriptdiff --git a/scripts/ci/classify_changes.py b/scripts/ci/classify_changes.pyindex 7315c0f00da..9e3141a8e8d 100644--- a/scripts/ci/classify_changes.py+++ b/scripts/ci/classify_changes.py@@ -219,6 +219,99 @@ _UPDATE_PIPELINE = ("gateway/restart.py","scripts/desktop-update/", # the hand-off scripts run `hermes update`)+# Selectors are owned by the import graph, not remembered. The update+# transaction's own modules (what `hermes update` and the launch-time completion+# run between the lock and the receipt) are the entry points;+# tests/ci/test_update_ci_routing.py reads every repo module they import (AST,+# module level and lazy) and every build script they run, and fails until each+# one is routed to the suite below or is a _SHARED_HUBS entry.+_UPDATE_ENTRY_POINTS = (+ "hermes_cli/update_",+ "hermes_cli/_update_",+ "hermes_cli/source_",+ "hermes_cli/old_updater",+ "hermes_cli/_old_updater",+ "hermes_cli/post_update",+ "hermes_cli/venv_sync.py",+ "hermes_cli/_early_recovery.py",+ "hermes_cli/main_desktop.py",+ "hermes_cli/desktop_update_verify.py",+ "hermes_cli/desktop_build_lock.py",+ "hermes_cli/subcommands/update",+)+# The entry points that build or verify the Desktop app inside an update+# (`hermes desktop --build-only`, the source build/completion that feeds it).+_DESKTOP_BUILD_ENTRY_POINTS = (+ "hermes_cli/source_build.py",+ "hermes_cli/source_completion.py",+ "hermes_cli/main_desktop.py",+ "hermes_cli/desktop_update_verify.py",+ "hermes_cli/desktop_build_lock.py",+)+# What the entry points import, outside the update_* family and the pipeline above.+_UPDATE_DEPENDENCIES = (+ "hermes_cli/_subprocess_compat.py", # update git env, process-tree kill, PM git exposure+ "hermes_cli/desktop_build_lock.py",+ "hermes_cli/memory_provider_migration.py",+ "hermes_cli/desktop_console.py",+ "hermes_cli/bundled_app.py",+ "hermes_cli/gui_uninstall.py",+ "hermes_cli/linux_desktop_entry.py",+ "hermes_cli/github_api.py", # source_check's release lookup+ "hermes_cli/build_info.py",+ "hermes_cli/image_provenance.py",+ "hermes_cli/backup.py", # pre-update backup+ "hermes_cli/backup_restore.py",+ "hermes_cli/relay_plugin_migrate.py",+ "hermes_cli/macos_tcc_anchor.py",+ "hermes_cli/model_catalog.py",+ "hermes_cli/sqlite_runtime.py",+ "hermes_cli/sqlite_safe_read.py",+ "hermes_cli/sizefmt.py",+ "hermes_cli/tools_config_cua.py",+ "hermes_cli/_startup_fast.py",+ "hermes_cli/_parser.py",+ "hermes_cli/gateway_multiplex_mode.py",+ "hermes_cli/plugin_catalog.py",+ "hermes_cli/steward.py",+ "hermes_cli/observability/shared_metrics_update.py",+ "hermes_cli/main_install_repair.py",+ "hermes_logging.py",+ "hermes_platform/host/__init__.py",+ "hermes_platform/host/facts.py",+ "agent/curator.py",+ "plugins/memory/__init__.py",+ "tools/checkpoint_maintenance.py",+ "tools/skills_sync.py",+ "tools/environments/local_env_policy.py",+ "pm/progress.py",+ # The compilers source_build / the Desktop build run (freshness, node-deps,+ # tui, web, desktop and their shared frontend-common).+ "scripts/build/",+)+# General-purpose modules an entry point imports but that half the product+# imports too (>= HUB_MIN_IMPORTERS product modules, checked by the test). The+# unit lanes cover them on every PR and the update suites on every push to main;+# routing each config.py / utils.py edit through the update suites would make+# them run on most PRs. Never an update-specific module: own those above.+HUB_MIN_IMPORTERS = 25+_SHARED_HUBS = frozenset({+ "hermes_cli/__init__.py",+ "hermes_cli/config.py",+ "hermes_cli/profiles.py",+ "hermes_cli/version_info.py",+ "utils.py",+ "hermes_state.py",+ "agent/__init__.py",+ "cron/jobs.py",+ "tools/environments/local.py",+ # Desktop lane only (the upgrade lane owns these outright):+ "hermes_constants.py",+ "gateway/status.py",+ "pm/__init__.py",+ "pm/paths.py",+ "pm/environments.py",+})_E2E_LANES: dict[str, tuple[str, ...]] = {"e2e": (*_PY_TEST_HARNESS,@@ -247,6 +340,8 @@ _E2E_LANES: dict[str, tuple[str, ...]] = {"hermes_cli/_install_","hermes_cli/main_install",*_UPDATE_PIPELINE,+ *_UPDATE_ENTRY_POINTS,+ *_UPDATE_DEPENDENCIES,),"e2e_desktop_core": (*_DESKTOP_E2E_SHARED,@@ -285,9 +380,16 @@ _E2E_LANES: dict[str, tuple[str, ...]] = {"apps/desktop/electron/app-installer-file","scripts/desktop-update/","scripts/install.sh",- "hermes_cli/desktop_update",- "hermes_cli/main_desktop.py","hermes_cli/update_",+ *_DESKTOP_BUILD_ENTRY_POINTS,+ *_UPDATE_DEPENDENCIES,+ # Pipeline modules the Desktop build entry points import directly.+ "hermes_cli/main.py", # `hermes desktop --build-only`+ "hermes_cli/venv_sync.py",+ "hermes_cli/source_stamp.py",+ # Imported by the Desktop build's scripts (scripts/build/desktop.mjs closure).+ "apps/desktop/product-identity.cjs",+ "scripts/msix-shared.mjs",),}# The upgrade journeys are their own lane; editing one does not start ``e2e``.diff --git a/tests/ci/_gha_expr.py b/tests/ci/_gha_expr.pynew file mode 100644index 00000000000..343ead7a348--- /dev/null+++ b/tests/ci/_gha_expr.py@@ -0,0 +1,224 @@+"""A small evaluator for the GitHub Actions expression subset our workflows gate on.++Enough to replay ``detect`` -> ``ci.yaml`` job ``if:``/``with:`` -> a called+workflow's job ``if:`` and its ``${{ }}``-rendered step text, so a test can feed+the real classifier's output through the real workflow files instead of+asserting booleans in isolation. Anything outside the subset raises+:class:`Unsupported`: a new construct must be modelled here, never ignored.++Semantics follow the Actions docs: ``&&``/``||`` return an operand, ``!``+negates truthiness, ``==``/``!=`` compare strings case-insensitively and coerce+mismatched types to numbers (so ``'true' == true`` is false), and a missing+property is ``null``.+"""++from __future__ import annotations++import json+import math+import re+from typing import Any, Mapping++_TOKEN = re.compile(r"""\s*(?:+ (?P<str>'(?:[^']|'')*')+ | (?P<num>-?\d+(?:\.\d+)?)+ | (?P<op>==|!=|&&|\|\||<=|>=|[!()<>,])+ | (?P<path>[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_*][A-Za-z0-9_-]*)*)+)""", re.X)+_TEMPLATE = re.compile(r"\$\{\{(.*?)\}\}", re.S)+++class Unsupported(ValueError):+ """An expression construct this evaluator does not model."""+++def _tokens(text: str) -> list[tuple[str, str]]:+ out, pos = [], 0+ text = text.strip()+ while pos < len(text):+ match = _TOKEN.match(text, pos)+ if not match or match.end() == pos:+ raise Unsupported(f"cannot tokenize {text[pos:]!r} in {text!r}")+ kind = match.lastgroup or ""+ out.append((kind, match.group(kind)))+ pos = match.end()+ return out+++def truthy(value: Any) -> bool:+ if value is None or value is False:+ return False+ if isinstance(value, (int, float)) and not isinstance(value, bool):+ return value != 0 and not math.isnan(value)+ if isinstance(value, str):+ return value != ""+ return True+++def _number(value: Any) -> float:+ if value is None:+ return 0.0+ if isinstance(value, bool):+ return 1.0 if value else 0.0+ if isinstance(value, (int, float)):+ return float(value)+ if isinstance(value, str):+ try:+ return float(value.strip()) if value.strip() else 0.0+ except ValueError:+ return math.nan+ return math.nan+++def _equal(a: Any, b: Any) -> bool:+ if type(a) is type(b) or (a is None and b is None):+ if isinstance(a, str) and isinstance(b, str):+ return a.lower() == b.lower()+ return a == b+ return _number(a) == _number(b)+++def to_string(value: Any) -> str:+ """How ``${{ }}`` renders a value into text (``true``/``false``, ``''`` for null)."""+ if value is None:+ return ""+ if isinstance(value, bool):+ return "true" if value else "false"+ if isinstance(value, float) and value.is_integer():+ return str(int(value))+ if isinstance(value, (dict, list)):+ return json.dumps(value)+ return str(value)+++class _Parser:+ def __init__(self, text: str, context: Mapping[str, Any]):+ self.text, self.toks, self.i, self.ctx = text, _tokens(text), 0, context++ def peek(self) -> tuple[str, str] | None:+ return self.toks[self.i] if self.i < len(self.toks) else None++ def take(self, value: str | None = None) -> tuple[str, str]:+ tok = self.peek()+ if tok is None or (value is not None and tok[1] != value):+ raise Unsupported(f"expected {value or 'a token'} in {self.text!r}")+ self.i += 1+ return tok++ def parse(self) -> Any:+ value = self.or_()+ tok = self.peek()+ if tok is not None:+ raise Unsupported(f"trailing {tok[1]!r} in {self.text!r}")+ return value++ def or_(self) -> Any:+ value = self.and_()+ while self.peek() == ("op", "||"):+ self.take()+ right = self.and_()+ value = value if truthy(value) else right+ return value++ def and_(self) -> Any:+ value = self.cmp()+ while self.peek() == ("op", "&&"):+ self.take()+ right = self.cmp()+ value = right if truthy(value) else value+ return value++ def cmp(self) -> Any:+ value = self.unary()+ while self.peek() in (("op", "=="), ("op", "!=")):+ op = self.take()[1]+ right = self.unary()+ value = _equal(value, right) if op == "==" else not _equal(value, right)+ tok = self.peek()+ if tok is not None and tok[1] in ("<", ">", "<=", ">="):+ raise Unsupported(f"ordering comparison in {self.text!r}")+ return value++ def unary(self) -> Any:+ if self.peek() == ("op", "!"):+ self.take()+ return not truthy(self.unary())+ return self.atom()++ def atom(self) -> Any:+ kind, text = self.take()+ if kind == "op" and text == "(":+ value = self.or_()+ self.take(")")+ return value+ if kind == "str":+ return text[1:-1].replace("''", "'")+ if kind == "num":+ return float(text)+ if kind != "path":+ raise Unsupported(f"unexpected {text!r} in {self.text!r}")+ if text in ("true", "false"):+ return text == "true"+ if text == "null":+ return None+ if self.peek() == ("op", "("):+ return self.call(text)+ return self.lookup(text)++ def call(self, name: str) -> Any:+ self.take("(")+ args = []+ while self.peek() != ("op", ")"):+ args.append(self.or_())+ if self.peek() == ("op", ","):+ self.take()+ self.take(")")+ if name in ("always", "success", "failure", "cancelled"):+ fn = self.ctx.get("__status__", {}).get(name)+ if fn is None:+ raise Unsupported(f"{name}() outside a modelled job status in {self.text!r}")+ return fn+ if name == "toJSON":+ return json.dumps(args[0])+ if name == "fromJSON":+ return json.loads(args[0])+ if name == "contains":+ hay, needle = args+ if isinstance(hay, list):+ return any(_equal(h, needle) for h in hay)+ return to_string(needle).lower() in to_string(hay).lower()+ raise Unsupported(f"function {name}() in {self.text!r}")++ def lookup(self, path: str) -> Any:+ node: Any = self.ctx+ for part in path.split("."):+ if part == "*":+ raise Unsupported(f"object filter in {self.text!r}")+ node = node.get(part) if isinstance(node, Mapping) else None+ return node+++def evaluate(expr: str, context: Mapping[str, Any]) -> Any:+ """Value of a bare expression or a single ``${{ expr }}``."""+ text = expr.strip()+ whole = _TEMPLATE.fullmatch(text)+ return _Parser(whole.group(1) if whole else text, context).parse()+++def condition(expr: Any, context: Mapping[str, Any]) -> bool:+ """A job/step ``if:`` (absent means ``success()``, which the caller models)."""+ if expr is None:+ return True+ if isinstance(expr, bool):+ return expr+ return truthy(evaluate(str(expr), context))+++def render(text: Any, context: Mapping[str, Any]) -> Any:+ """``with:``/``env:``/``run:`` value: a lone ``${{ x }}`` keeps its type, embedded ones stringify."""+ if not isinstance(text, str):+ return text+ whole = _TEMPLATE.fullmatch(text.strip())+ if whole:+ return evaluate(whole.group(1), context)+ return _TEMPLATE.sub(lambda m: to_string(evaluate(m.group(1), context)), text)diff --git a/tests/ci/test_classify_changes.py b/tests/ci/test_classify_changes.pyindex 715726fef06..ebe8d833c1b 100644--- a/tests/ci/test_classify_changes.py+++ b/tests/ci/test_classify_changes.py@@ -84,7 +84,12 @@ def _lanes(python=False, frontend=False, site=False, scan=False, deps=False, uv_CASES = {- "shared JS builder → frontend": (["scripts/build/web.mjs"], _lanes(python=True, frontend=True)),+ # source_build runs it on every source update, and the Desktop build steps+ # through the same compilers (tests/ci/test_update_ci_routing.py).+ "shared JS builder → frontend + both update suites": (+ ["scripts/build/web.mjs"],+ _lanes(python=True, frontend=True, e2e_upgrade=True, e2e_desktop_update=True),+ ),"root JS tests → frontend": (["tests-js/product-builders.test.mjs"], _lanes(python=True, frontend=True)),"docs-only → nothing heavy": (["README.md", "docs/guide.md"], _lanes()),"python source → python": (["run_agent.py"], _lanes(python=True, scan=True)),@@ -336,7 +341,10 @@ CASES = {"PM → e2e_upgrade + docker": (["pm/environments.py"], _lanes(python=True, scan=True, e2e_upgrade=True, docker=True)),# The update pipeline lives beyond the update_* family too: the entry# point, launch-time recovery, the gateway restart/pause surface.- "cmd_update entry → e2e_upgrade": (["hermes_cli/main.py"], _lanes(python=True, scan=True, e2e_upgrade=True)),+ # main.py is also `hermes desktop --build-only`, the update's Desktop rebuild.+ "cmd_update entry → both update suites": (+ ["hermes_cli/main.py"], _lanes(python=True, scan=True, e2e_upgrade=True, e2e_desktop_update=True),+ ),"gateway status stamp → e2e_upgrade": (["gateway/status.py"], _lanes(python=True, scan=True, e2e_upgrade=True)),"desktop verify → desktop_updater + both update suites": (["hermes_cli/desktop_update_verify.py"],@@ -493,7 +501,7 @@ _REPO = Path(__file__).resolve().parents[2]def _yaml(rel: str) -> dict:yaml = pytest.importorskip("hermes_yaml")- return yaml.safe_load((_REPO / rel).read_text(encoding="utf-8"))+ return yaml.safe_load((_REPO / rel).read_text(encoding="utf-8-sig"))def test_every_lane_reaches_the_composite_action():@@ -574,7 +582,7 @@ def test_real_update_suites_gate_the_merge_when_their_lane_fires(caller, job, cadef test_windows_venv_e2e_runs_only_test_files_that_exist():"""``run_tests.sh`` drops a missing path (or a ``::node`` selector) withouta word, so a stale entry silently stops running on every wine2e push."""- text = (_REPO / ".github/workflows/windows-venv-e2e.yml").read_text(encoding="utf-8")+ text = (_REPO / ".github/workflows/windows-venv-e2e.yml").read_text(encoding="utf-8-sig")paths = re.findall(r"(tests/[\w/.:-]+)", text)assert pathsassert [p for p in paths if "::" in p or not (_REPO / p).is_file()] == []diff --git a/tests/ci/test_update_ci_routing.py b/tests/ci/test_update_ci_routing.pynew file mode 100644index 00000000000..9e293cdd2b9--- /dev/null+++ b/tests/ci/test_update_ci_routing.py@@ -0,0 +1,418 @@+"""Update-path CI routing: ownership-derived selectors and the full dispatch chain.++Two failure modes this file pins (independent review R15):++* **Selector drift.** A hand list of "update files" misses whatever the update+ modules import next (``_subprocess_compat``, ``desktop_build_lock``,+ ``memory_provider_migration``, the ``scripts/build`` compilers). Here the+ update entry points' real imports are read from the source (Python AST, ESM+ ``import``/``step()`` literals) and every module they reach must start the+ suite that runs it, or be one of the classifier's declared shared hubs.+* **Dead dispatch.** A lane the classifier sets can still never reach its job:+ ``desktop_updater=true`` with ``python=false`` used to skip ``tests-os``+ entirely. Here the REAL classifier's output is replayed through the REAL+ workflow files (composite action -> ``ci.yaml`` detect outputs -> job+ ``if:``/``with:`` -> the called workflow's job ``if:`` -> the rendered step),+ so a gate that does not consume a lane fails here, not on a PR.+"""++from __future__ import annotations++import ast+import importlib.util+import itertools+import json+import os+import re+import subprocess+import sys+from functools import lru_cache+from pathlib import Path+from typing import Any++import pytest++from tests.ci import _gha_expr as gha++_REPO = Path(__file__).resolve().parents[2]+_CLASSIFIER = _REPO / "scripts" / "ci" / "classify_changes.py"+_spec = importlib.util.spec_from_file_location("classify_changes_routing", _CLASSIFIER)+assert _spec is not None and _spec.loader is not None+cc = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(cc)+++# -- the real classifier, as CI runs it ---------------------------------------------+++def _real_classifier(paths: list[str]) -> dict[str, bool]:+ """``scripts/ci/classify_changes.py`` as a process, stdin -> ``key=value`` lines."""+ env = {k: v for k, v in os.environ.items() if k not in ("GITHUB_OUTPUT", "GITHUB_EVENT_PATH")}+ env["EVENT_NAME"] = "pull_request_replay" # never `pull_request`: no gh calls from a test+ out = subprocess.run([sys.executable, str(_CLASSIFIER)], input="\n".join(paths) + "\n",+ capture_output=True, text=True, env=env, check=True, timeout=60).stdout+ pairs = dict(line.split("=", 1) for line in out.splitlines() if "=" in line)+ return {k: v == "true" for k, v in pairs.items()}+++# -- workflow replay ---------------------------------------------------------------------+++@lru_cache(maxsize=None)+def _yaml(rel: str) -> dict:+ yaml = pytest.importorskip("hermes_yaml")+ return yaml.safe_load((_REPO / rel).read_text(encoding="utf-8-sig"))+++def _on(workflow: dict) -> dict:+ return workflow.get("on", workflow.get(True)) or {}+++def _detect_outputs(lanes: dict[str, bool]) -> dict[str, Any]:+ """The classifier's lines -> the composite action's outputs -> ci.yaml ``detect`` outputs."""+ raw = {k: gha.to_string(v) for k, v in lanes.items()}+ action = _yaml(".github/actions/detect-changes/action.yml")+ action_out = {k: gha.render(v["value"], {"steps": {"classify": {"outputs": raw}}})+ for k, v in action["outputs"].items()}+ detect = _yaml(".github/workflows/ci.yaml")["jobs"]["detect"]+ gate = next(s for s in detect["steps"] if s.get("id") == "gate-lanes")+ classify = next(s for s in detect["steps"] if s.get("id") == "classify")+ assert classify["uses"] == "./.github/actions/detect-changes"+ # gate-lanes copies every classified value unchanged unless RELEASE is true (a PR is not).+ assert gate["env"]["RELEASE"] == "${{ inputs.release }}"+ assert "steps.classify.outputs" in gate["env"]["CLASSIFIED"]+ steps = {"classify": {"outputs": action_out}, "gate-lanes": {"outputs": action_out}}+ ctx = {"steps": steps, "github": {"event_name": "pull_request"}, "inputs": {}}+ return {k: gha.render(v, ctx) for k, v in detect["outputs"].items()}+++def _inputs_for(called: str, given: dict[str, Any]) -> dict[str, Any]:+ declared = (_on(_yaml(called)).get("workflow_call") or {}).get("inputs") or {}+ unknown = set(given) - set(declared)+ assert not unknown, f"{called} is passed input(s) it never declares: {sorted(unknown)}"+ return {name: given.get(name, spec.get("default")) for name, spec in declared.items()}+++def _run_workflow(rel: str, *, inputs: dict[str, Any], detect: dict[str, Any] | None = None) -> dict:+ """Which jobs of ``rel`` run on a pull request, recursing into called workflows.++ Returns ``{job: {"inputs": ..., "jobs": <child result>}}`` for every job that runs.+ ``detect`` (ci.yaml only) is the replayed ``detect`` job's outputs.+ """+ jobs = _yaml(rel)["jobs"]+ ran: dict[str, dict] = {}+ done: set[str] = set()+ pending = list(jobs)+ while pending:+ progressed = False+ for name in list(pending):+ body = jobs[name]+ needs = body.get("needs") or []+ needs = [needs] if isinstance(needs, str) else list(needs)+ if any(n not in done for n in needs):+ continue+ pending.remove(name)+ done.add(name)+ progressed = True+ if name == "detect" and detect is not None:+ ran[name] = {"outputs": detect}+ continue+ all_ran = all(n in ran for n in needs)+ ctx = {+ "inputs": inputs,+ "github": {"event_name": "pull_request", "ref_type": "branch"},+ "needs": {n: {"outputs": (ran.get(n) or {}).get("outputs", {}),+ "result": "success" if n in ran else "skipped"} for n in needs},+ "__status__": {"always": True, "success": all_ran, "failure": False, "cancelled": False},+ }+ cond = body.get("if")+ uses_status = isinstance(cond, str) and re.search(r"\b(always|success|failure|cancelled)\(", cond)+ if not uses_status and not all_ran:+ continue # implicit success(): a skipped dependency skips this job+ if not gha.condition(cond, ctx):+ continue+ entry: dict[str, Any] = {"ctx": ctx}+ uses = body.get("uses")+ if isinstance(uses, str) and uses.startswith("./.github/workflows/"):+ called = uses[2:]+ given = {k: gha.render(v, ctx) for k, v in (body.get("with") or {}).items()}+ entry["inputs"] = _inputs_for(called, given)+ entry["jobs"] = _run_workflow(called, inputs=entry["inputs"])+ ran[name] = entry+ assert progressed, f"{rel}: unresolvable needs among {pending}"+ return ran+++def _ci_run(lanes: dict[str, bool]) -> dict:+ return _run_workflow(".github/workflows/ci.yaml", inputs={}, detect=_detect_outputs(lanes))+++def _reached(run: dict, *path: str) -> dict | None:+ node: dict | None = {"jobs": run}+ for job in path:+ node = (node or {}).get("jobs", {}).get(job)+ if node is None:+ return None+ return node+++def _windows_desktop_updater_tests_selected(run: dict) -> bool:+ """tests-os os-tests runs, and its Windows step keeps the desktop-update hand-off files."""+ os_tests = _reached(run, "tests-os", "os-tests")+ if os_tests is None:+ return False+ body = _yaml(".github/workflows/tests-os.yml")["jobs"]["os-tests"]+ windows = next(m for m in body["strategy"]["matrix"]["include"] if m["marker"] == "windows")+ step = next(s for s in body["steps"] if "list_os_marked_tests.py" in str(s.get("run", "")))+ ctx = {**os_tests["ctx"], "matrix": windows, "runner": {"os": "Windows", "arch": "X64"}}+ script = gha.render(step["run"], ctx)+ gate = re.search(r'if \[ "(\w*)" != "true" \]; then\s+echo "desktop_updater lane off', script)+ assert gate, "the desktop_updater deselect gate moved: update this replay"+ return gate.group(1) == "true"+++# Each real consumer of a lane, as a path of job names from ci.yaml down.+_CONSUMERS: dict[str, tuple[tuple[str, ...], ...]] = {+ "e2e_upgrade": (+ ("tests", "e2e-upgrade-plan"),+ ("tests", "e2e-upgrade"),+ ("tests-os", "install-update-e2e", "install-update"),+ ),+ "e2e": (("tests", "e2e"), ("tests-os", "e2e-windows")),+ "e2e_desktop_update": (("e2e-desktop-update", "update"),),+}+++def _consumers_reached(run: dict, lane: str) -> dict[str, bool]:+ if lane == "desktop_updater":+ return {"tests-os/os-tests[windows] keeps test_desktop_update_windows_*":+ _windows_desktop_updater_tests_selected(run)}+ return {"/".join(path): _reached(run, *path) is not None for path in _CONSUMERS[lane]}+++_GATED = ("python", "desktop_updater", "e2e", "e2e_upgrade", "e2e_desktop_update")+++def test_replay_evaluator_follows_actions_semantics():+ ctx = {"needs": {"detect": {"outputs": {"python": "false", "e2e": "true"}}}, "inputs": {"flag": True}}+ assert gha.condition("needs.detect.outputs.python == 'true' || needs.detect.outputs.e2e == 'true'", ctx)+ assert not gha.condition("needs.detect.outputs.python == 'true'", ctx)+ assert not gha.evaluate("'true' == true", ctx) # a string output is not the boolean+ assert gha.render('x "${{ inputs.flag }}" y', ctx) == 'x "true" y'+ assert gha.render("${{ inputs.flag && '1' || '' }}", ctx) == "1"+ assert gha.render("${{ inputs.missing && '1' || '' }}", ctx) == ""+ with pytest.raises(gha.Unsupported):+ gha.condition("hashFiles('x') != ''", ctx) # unmodelled: fail, never guess++[email protected]("combo", list(itertools.product((False, True), repeat=len(_GATED))),+ ids=lambda c: "-".join(n for n, on in zip(_GATED, c) if on) or "none")+def test_every_set_lane_reaches_its_consumer_whatever_the_other_lanes_say(combo):+ """The R15 hole was a parent ``if:`` keyed on ``python`` alone: a TypeScript-only+ change to the hand-off's marker reader set ``desktop_updater`` and nothing ran it."""+ lanes = {k: False for k in cc.classify(["README.md"])}+ lanes.update(zip(_GATED, combo))+ run = _ci_run(lanes)+ for lane in ("desktop_updater", "e2e", "e2e_upgrade", "e2e_desktop_update"):+ reached = _consumers_reached(run, lane)+ if lanes[lane]:+ assert all(reached.values()), f"{lane}=true but not dispatched: {reached}"+ elif lane != "desktop_updater":+ assert not any(reached.values()), f"{lane}=false but ran anyway: {reached}"+++# One-file changes from the review's direct classifier run (acceptance/classifier.json),+# and the suites each must dispatch on a pull request.+_R15_CASES = {+ "scripts/build/desktop.mjs": ("e2e_upgrade", "e2e_desktop_update"),+ "scripts/build/web.mjs": ("e2e_upgrade", "e2e_desktop_update"),+ "hermes_cli/_subprocess_compat.py": ("e2e_upgrade", "e2e_desktop_update"),+ "hermes_cli/desktop_build_lock.py": ("e2e_upgrade", "e2e_desktop_update"),+ "hermes_cli/memory_provider_migration.py": ("e2e_upgrade", "e2e_desktop_update"),+ "hermes_cli/source_build.py": ("e2e_upgrade", "e2e_desktop_update"),+ "hermes_cli/source_completion.py": ("e2e_upgrade", "e2e_desktop_update"),+ "apps/desktop/electron/update-marker.ts": ("desktop_updater", "e2e_desktop_update"),+ "apps/desktop/electron/handoff-result.ts": ("desktop_updater", "e2e_desktop_update"),+}++[email protected]("path,lanes", list(_R15_CASES.items()))+def test_update_owner_change_dispatches_its_suites_end_to_end(path, lanes):+ assert (_REPO / path).is_file(), f"{path} moved: update this table"+ classified = _real_classifier([path])+ run = _ci_run(classified)+ for lane in lanes:+ assert classified[lane], f"{path}: classifier leaves {lane} off"+ reached = _consumers_reached(run, lane)+ assert all(reached.values()), f"{path}: {lane}=true never reaches {reached}"+++def test_every_detect_output_a_lane_sets_is_consumed_by_some_job():+ """A lane output nothing reads is a lane that can never run anything."""+ ci = _yaml(".github/workflows/ci.yaml")+ text = json.dumps({k: v for k, v in ci["jobs"].items() if k != "detect"})+ # python_prod's only reader is the deferred Desktop E2E job (`if: false`, see ci.yaml).+ unread = [k for k in ci["jobs"]["detect"]["outputs"]+ if k not in ("event_name", "python_prod") and f"needs.detect.outputs.{k}" not in text]+ assert unread == []+++# -- ownership: the update entry points' real imports ---------------------------------------++_SKIP_DIRS = {".git", ".venv", "venv", "node_modules", ".worktrees", "tests", "website", "__pycache__"}+++def _product_python() -> list[Path]:+ out = []+ for dirpath, dirnames, filenames in os.walk(_REPO):+ dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".")]+ out += [Path(dirpath) / f for f in filenames if f.endswith(".py")]+ return out+++def _module_file(module: str) -> Path | None:+ base = _REPO / module.replace(".", "/")+ for candidate in (base.with_suffix(".py"), base / "__init__.py"):+ if candidate.is_file():+ return candidate+ return None+++@lru_cache(maxsize=None)+def _imports(path: Path) -> frozenset[str]:+ """Repo modules ``path`` imports anywhere (module level or lazily in a function)."""+ try:+ tree = ast.parse(path.read_text(encoding="utf-8-sig"))+ except (SyntaxError, UnicodeDecodeError):+ return frozenset()+ package = path.relative_to(_REPO).with_suffix("").parts[:-1]+ names: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ names.update(a.name for a in node.names)+ elif isinstance(node, ast.ImportFrom):+ base = node.module or ""+ if node.level:+ parts = list(package[: len(package) - (node.level - 1)])+ base = ".".join([*parts, base] if base else parts)+ names.add(base)+ names.update(f"{base}.{a.name}" for a in node.names)+ found = set()+ for name in names:+ target = _module_file(name)+ if target is not None and target != path:+ found.add(target.relative_to(_REPO).as_posix())+ return frozenset(found)+++def _entry_modules(prefixes: tuple[str, ...]) -> list[Path]:+ hits = [p for p in _product_python() if p.relative_to(_REPO).as_posix().startswith(prefixes)]+ assert hits, f"no module matches {prefixes}: the entry-point list went stale"+ return sorted(hits)+++@lru_cache(maxsize=None)+def _importers() -> dict[str, int]:+ counts: dict[str, int] = {}+ for path in _product_python():+ for target in _imports(path):+ counts[target] = counts.get(target, 0) + 1+ return counts+++def _unowned(entries: tuple[str, ...], lane: str) -> dict[str, list[str]]:+ out: dict[str, list[str]] = {}+ for module in _entry_modules(entries):+ for target in _imports(module):+ if not cc.classify([target])[lane] and target not in cc._SHARED_HUBS:+ out.setdefault(target, []).append(module.relative_to(_REPO).as_posix())+ return out++[email protected]("entries,lane", [+ ("_UPDATE_ENTRY_POINTS", "e2e_upgrade"),+ ("_DESKTOP_BUILD_ENTRY_POINTS", "e2e_desktop_update"),+])+def test_every_module_an_update_entry_point_imports_starts_its_suite(entries, lane):+ """Add the module to the classifier's owner list for this lane. Only a shared+ hub (``_SHARED_HUBS``: imported across the product, covered by the unit lanes+ and by this suite on every push to main) may stay out."""+ missing = _unowned(getattr(cc, entries), lane)+ assert missing == {}, f"{lane}: imported by the update path but not routed to it: {missing}"+++def test_entry_points_themselves_start_their_suites():+ for module in _entry_modules(cc._UPDATE_ENTRY_POINTS):+ assert cc.classify([module.relative_to(_REPO).as_posix()])["e2e_upgrade"], module+ for module in _entry_modules(cc._DESKTOP_BUILD_ENTRY_POINTS):+ rel = module.relative_to(_REPO).as_posix()+ assert cc.classify([rel])["e2e_desktop_update"] and cc.classify([rel])["e2e_upgrade"], rel+++def test_shared_hubs_are_real_hubs_still_on_the_update_path():+ """The hub exemption cannot hide an update-specific module: each hub must be+ imported by many product modules, and still be imported by an entry point."""+ counts = _importers()+ thin = {h: counts.get(h, 0) for h in cc._SHARED_HUBS if counts.get(h, 0) < cc.HUB_MIN_IMPORTERS}+ assert thin == {}, f"not a shared hub (fewer than {cc.HUB_MIN_IMPORTERS} importers): own it instead"+ reached = set()+ for entries in (cc._UPDATE_ENTRY_POINTS, cc._DESKTOP_BUILD_ENTRY_POINTS):+ for module in _entry_modules(entries):+ reached |= _imports(module)+ assert set(cc._SHARED_HUBS) - reached == set(), "stale hub exemption: no entry point imports it"+++# -- ownership: the JavaScript compilers an update runs -------------------------------------++_SCRIPT_LITERAL = re.compile(r"""["']((?:scripts/build|apps/desktop/scripts)/[\w./-]+\.(?:mjs|js|py|ps1))["']""")+_ESM_IMPORT = re.compile(r"""(?:from|import)\s*\(?\s*['"](\.{1,2}/[^'"]+)['"]""")+_STEP = re.compile(r"""step\(\s*['"]([\w./-]+\.mjs)['"]""")+++def _js_closure(seeds: set[str]) -> set[str]:+ seen: set[str] = set()+ stack = list(seeds)+ while stack:+ rel = stack.pop()+ if rel in seen:+ continue+ path = _REPO / rel+ assert path.is_file(), f"{rel} is referenced on the update path but does not exist"+ seen.add(rel)+ if not rel.endswith((".mjs", ".js")):+ continue+ text = path.read_text(encoding="utf-8-sig")+ for spec in _ESM_IMPORT.findall(text):+ target = (path.parent / spec).resolve()+ if target.is_file() and _REPO in target.parents:+ stack.append(target.relative_to(_REPO).as_posix())+ stack += _STEP.findall(text)+ return seen+++def _python_script_seeds(entries: tuple[str, ...]) -> set[str]:+ seeds = set()+ for module in _entry_modules(entries):+ seeds |= set(_SCRIPT_LITERAL.findall(module.read_text(encoding="utf-8-sig")))+ return seeds+++def test_build_scripts_the_update_runs_start_the_upgrade_suite():+ reached = _js_closure(_python_script_seeds(cc._UPDATE_ENTRY_POINTS))+ assert "scripts/build/web.mjs" in reached, "seed scan broke: source_build runs web.mjs"+ unowned = sorted(f for f in reached if not cc.classify([f])["e2e_upgrade"])+ assert unowned == []+++def test_desktop_build_scripts_start_the_desktop_update_suite():+ """`hermes desktop --build-only` (the update's Desktop rebuild) runs+ apps/desktop's `build` script, which steps through scripts/build/desktop.mjs."""+ package = json.loads((_REPO / "apps/desktop/package.json").read_text(encoding="utf-8-sig"))+ build = re.search(r"node\s+(\S+\.mjs)", package["scripts"]["build"])+ assert build, package["scripts"]["build"]+ seeds = {("apps/desktop/" + build.group(1)).replace("/./", "/")}+ seeds |= _python_script_seeds(cc._DESKTOP_BUILD_ENTRY_POINTS)+ reached = _js_closure(seeds)+ assert "scripts/build/desktop.mjs" in reached, "seed scan broke: the Desktop build runs desktop.mjs"+ unowned = sorted(f for f in reached if not cc.classify([f])["e2e_desktop_update"])+ assert unowned == []