The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): startup syntax is judged by the target's Python over the whole entry closure (review G3, N15)
Tekniume92cec9dff16
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex e94d13414df..a04580b3b23 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -197,7 +197,13 @@ def _map_ssl_cert_file_for_git(git_cmd) -> None:os.environ["GIT_SSL_CAINFO"] = bundle+# Compiled before (preflight) and after (post-pull guard, ZIP gate) every tree move. The first rows+# are what the launcher and ``hermes_bootstrap`` import before any application code (review G3);+# test_update_post_pull_syntax_guard derives that set from the real entry paths and pins it here._UPDATE_CRITICAL_FILES = (+ "hermes_bootstrap.py", "hermes_cli/_parser.py", "hermes_cli/_launchers.py",+ "hermes_cli/_early_recovery.py", "hermes_cli/update_lock.py", "hermes_cli/update_custody.py",+ "hermes_cli/update_handoff.py", "hermes_cli/venv_sync.py", "pm/__init__.py", "pm/environments.py","hermes_cli/main.py", "hermes_cli/config.py", "hermes_cli/__init__.py","hermes_cli/web_server.py", "cli.py", "run_agent.py", "model_tools.py", "toolsets.py","hermes_constants.py")@@ -910,12 +916,9 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=Nfile no longer compiles (a bad admin-merge past CI must not brick the CLI)."""pyproject = Path(_m().PROJECT_ROOT) / "pyproject.toml"if pyproject.is_file() and _commit.requires_other_python(pyproject.read_bytes()):- # A newer Python's syntax: this interpreter's compile() cannot judge it; a conflict marker- # is broken under every Python.- marked = [(rel, reason) for rel in _UPDATE_CRITICAL_FILES- if (path := Path(_m().PROJECT_ROOT) / rel).is_file()- and (reason := _commit.conflict_marker(path.read_bytes()))]- syntax_ok, failing_path, syntax_error = (not marked, *(marked[0] if marked else (None, None)))+ # A newer Python's syntax: judged by an installed interpreter the target admits (N15).+ broken = _commit.tree_syntax_error(_m().PROJECT_ROOT, _UPDATE_CRITICAL_FILES)+ syntax_ok, failing_path, syntax_error = (broken is None, *(broken or (None, None)))else:syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT)if syntax_ok:diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.pyindex 3e1a9431b33..0f35b4a82b0 100644--- a/hermes_cli/update_cmd_commit.py+++ b/hermes_cli/update_cmd_commit.py@@ -355,67 +355,182 @@ def settle_failed_tree_move(root: Path) -> bool:return not marker.is_file()+def _requires_python_spec(pyproject: bytes | str | None) -> str | None:+ """The target's ``requires-python`` specifier, None when absent or unreadable."""+ if not pyproject:+ return None+ import tomllib++ try:+ text = pyproject.decode("utf-8") if isinstance(pyproject, bytes) else pyproject+ spec = tomllib.loads(text)["project"]["requires-python"]+ except (KeyError, TypeError, ValueError): # TOMLDecodeError is a ValueError+ return None+ return spec if isinstance(spec, str) else None+++def _spec_admits(spec: str, version: str) -> bool:+ import re++ try:+ from packaging.specifiers import InvalidSpecifier, SpecifierSet+ except ImportError: # the lower bound is the part a Python bump moves+ floor = re.search(r">=\s*(\d+)\.(\d+)", spec)+ found = re.match(r"(\d+)\.(\d+)", version)+ return not floor or bool(found) and (int(found[1]), int(found[2])) >= (int(floor[1]), int(floor[2]))+ try:+ return SpecifierSet(spec).contains(version, prereleases=True)+ except InvalidSpecifier:+ return True # unknown: keep judging with this interpreter, never wave a file through++def requires_other_python(pyproject: bytes | str | None) -> bool:"""True when a target's ``requires-python`` excludes the running interpreter.Its startup modules may then use a newer Python's syntax that this interpreter's ``compile()``- cannot judge (PM provisions the required Python with the new code). Unknown -> False: keep- checking, so a real syntax error is never waved through on a guess.+ cannot judge: ``startup_syntax_error`` asks an installed interpreter the target admits instead.+ Unknown -> False: keep checking, so a real syntax error is never waved through on a guess."""- if not pyproject:- return Falseimport platform- import re- import tomllib++ spec = _requires_python_spec(pyproject)+ return spec is not None and not _spec_admits(spec, platform.python_version())+++_PYTHON_VERSION = "import platform; print(platform.python_version())"+# Run by the target's interpreter: compile every startup file sent on stdin, print the first error.+_COMPILE_ALL = (+ "import base64, json, sys\n"+ "verdict = None\n"+ "for rel, data in json.load(sys.stdin).items():\n"+ " try:\n"+ " compile(base64.b64decode(data), rel, 'exec', dont_inherit=True)\n"+ " except (SyntaxError, ValueError) as exc:\n"+ " verdict = [rel, f'{type(exc).__name__}: {exc}']\n"+ " break\n"+ "print(json.dumps(verdict))\n")+++def _run_python(argv: list[str], *, stdin: str = "", timeout: float = 60) -> str | None:+ """Stdout of a read-only interpreter child (it never writes the checkout), None when it failed."""+ from hermes_cli._subprocess_compat import windows_hide_flagstry:- text = pyproject.decode("utf-8") if isinstance(pyproject, bytes) else pyproject- spec = tomllib.loads(text)["project"]["requires-python"]- try:- from packaging.specifiers import SpecifierSet- except ImportError: # the lower bound is the part a Python bump moves- floor = re.search(r">=\s*(\d+)\.(\d+)", spec)- return bool(floor) and sys.version_info[:2] < (int(floor[1]), int(floor[2]))- return not SpecifierSet(spec).contains(platform.python_version(), prereleases=True)- except (KeyError, TypeError, ValueError): # TOMLDecodeError / InvalidSpecifier are ValueErrors- return False+ done = subprocess.run(argv, input=stdin, capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=timeout, creationflags=windows_hide_flags())+ except (OSError, subprocess.SubprocessError):+ return None+ return done.stdout if done.returncode == 0 else None-def conflict_marker(data: bytes) -> str | None:- """Why ``data`` is broken under EVERY Python (a merge-conflict marker line), else None: no- ``requires-python`` bump excuses it. Only git's ``<<<<<<< ``/``>>>>>>> `` lines: a bare- ``=======`` is also a reST heading in a docstring."""- for number, line in enumerate(data.splitlines(), 1):- if line.startswith((b"<<<<<<< ", b">>>>>>> ")):- return f"unresolved merge-conflict marker at line {number}"+def _admitted_python(spec: str) -> str | None:+ """An installed interpreter the target's ``requires-python`` admits (uv's view first, then+ ``python3.N`` on PATH, newest first), or None when this machine has none."""+ import shutil++ candidates = []+ if uv := shutil.which("uv"):+ found = (_run_python([uv, "python", "find", "--no-project", spec], timeout=30) or "").strip()+ candidates += found.splitlines()[-1:]+ candidates += [path for minor in range(40, sys.version_info[1], -1)+ if (path := shutil.which(f"python3.{minor}"))][:3]+ for python in candidates:+ version = (_run_python([python, "-I", "-c", _PYTHON_VERSION], timeout=30) or "").strip()+ if version and _spec_admits(spec, version):+ return pythonreturn None+def _compile_here(sources: dict[str, bytes]) -> tuple[str, str] | None:+ for rel, data in sources.items():+ try:+ compile(data, rel, "exec", dont_inherit=True)+ except (SyntaxError, ValueError) as exc:+ return rel, f"{type(exc).__name__}: {exc}"+ return None+++def startup_syntax_error(sources: dict[str, bytes | None], pyproject: bytes | None) -> tuple[str, str] | None:+ """``(path, error)`` for the first startup file that does not compile, else None.++ Judged by the interpreter that will run the target: this one when the target's+ ``requires-python`` admits it, else an installed interpreter it admits (review N15: a+ conflict-marker scan is not a syntax check). With none installed, this interpreter still+ judges: code it parses is code a newer Python parses, and a refusal names the Python to install+ so the release can be judged by its own interpreter. ``None`` values (absent files) are skipped.+ """+ import base64+ import json+ import platform++ present = {rel: data for rel, data in sources.items() if data is not None}+ spec = _requires_python_spec(pyproject)+ if spec is None or _spec_admits(spec, platform.python_version()):+ return _compile_here(present)+ if python := _admitted_python(spec):+ payload = json.dumps({rel: base64.b64encode(data).decode("ascii") for rel, data in present.items()})+ out = _run_python([python, "-I", "-c", _COMPILE_ALL], stdin=payload, timeout=120)+ try:+ verdict = json.loads((out or "").strip().splitlines()[-1])+ except (IndexError, ValueError):+ verdict = False # the target's interpreter gave no verdict: judge here (below)+ if verdict is None:+ return None+ if isinstance(verdict, list) and len(verdict) == 2:+ return str(verdict[0]), f"{verdict[1]} (judged by {python})"+ broken = _compile_here(present)+ if broken is None:+ return None+ return broken[0], (f"{broken[1]}\nJudged by Python {platform.python_version()}: the target requires Python "+ f"{spec} and no installed interpreter satisfies it. Install one (`uv python install "+ f"'{spec}'`) and re-run `hermes update` so the release is judged by its own Python.")+++def read_target_files(git_cmd, root: Path, target_ref: str, relpaths) -> dict[str, bytes | None]:+ """``{rel: bytes}`` of each path as committed at ``target_ref`` (None: absent there or unreadable),+ in ONE ``git cat-file --batch`` instead of one ``git show`` per file."""+ names = list(dict.fromkeys(relpaths))+ found: dict[str, bytes | None] = dict.fromkeys(names)+ request = "".join(f"{target_ref}:{rel}\n" for rel in names).encode("utf-8")+ cp = run_git(git_cmd, ["cat-file", "--batch"], cwd=str(root), input=request, capture_output=True, timeout=120)+ out, pos = (cp.stdout or b"") if cp.returncode == 0 else b"", 0+ for rel in names:+ end = out.find(b"\n", pos)+ if end < 0:+ break+ header, pos = out[pos:end].split(), end + 1+ if len(header) == 3 and header[2].isdigit(): # "<oid> <type> <size>", then the bytes and "\n"+ size = int(header[2])+ if header[1] == b"blob":+ found[rel] = out[pos:pos + size]+ pos += size + 1+ return found++def target_syntax_error(git_cmd, root: Path, target_ref: str, relpaths) -> tuple[str, str] | None:"""``(path, error)`` for the first startup-critical file that does not compile at ``target_ref``.Read from the object store, never written to the tree: this runs BEFORE HEAD moves, so a brokenrelease is refused with the install untouched (the post-pull rollback stays as the backstop).- A target that requires a Python this interpreter is not (``requires_other_python``) is held only- to ``conflict_marker``: its syntax may be a newer Python's.+ ``startup_syntax_error`` judges it under the interpreter the target admits. A file absent at the+ target (or unreadable) is skipped: the post-pull guard has the last word."""- pyproject = run_git(git_cmd, ["show", f"{target_ref}:pyproject.toml"], cwd=str(root),- capture_output=True, stdin=subprocess.DEVNULL, timeout=120)- other_python = pyproject.returncode == 0 and requires_other_python(pyproject.stdout)+ files = read_target_files(git_cmd, root, target_ref, ["pyproject.toml", *relpaths])+ pyproject = files.pop("pyproject.toml", None)+ return startup_syntax_error(files, pyproject)+++def tree_syntax_error(root: Path, relpaths) -> tuple[str, str] | None:+ """``startup_syntax_error`` for the files in the worktree at ``root`` (the post-move backstop)."""+ root = Path(root)+ sources: dict[str, bytes | None] = {}for rel in relpaths:- shown = run_git(git_cmd, ["show", f"{target_ref}:{rel}"], cwd=str(root), capture_output=True,- stdin=subprocess.DEVNULL, timeout=120)- if shown.returncode != 0:- continue # absent at the target (or unreadable): the post-pull guard has the last word- if other_python:- if reason := conflict_marker(shown.stdout or b""):- return rel, reason- continuetry:- compile(shown.stdout, rel, "exec", dont_inherit=True)- except (SyntaxError, ValueError) as exc:- return rel, f"{type(exc).__name__}: {exc}"- return None+ sources[rel] = (root / rel).read_bytes() if (root / rel).is_file() else None+ except OSError as exc:+ return str(rel), f"could not read: {exc}"+ pyproject = root / "pyproject.toml"+ return startup_syntax_error(sources, pyproject.read_bytes() if pyproject.is_file() else None)def head_and_branch(git_cmd, root: Path) -> tuple[str, str]:diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 056b359c7c9..fe4b5e9c05f 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -509,20 +509,10 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, taprint(" Files appeared in the checkout while the update was downloading; committing the swap would delete them.")print(_STASH_HINT)_m().sys.exit(1)- # Pre-commit gate: a target whose startup modules do not compile is refused untouched. A- # target that requires a Python this interpreter is not may use syntax this compile() cannot- # judge; it is still held to ``conflict_marker``, which is broken under every Python.- pyproject = Path(extracted, "pyproject.toml")- newer_python = pyproject.is_file() and _commit.requires_other_python(pyproject.read_bytes())- for rel in _UPDATE_CRITICAL_FILES:- path = os.path.join(extracted, *rel.split("/"))- if os.path.isfile(path):- with open(path, "rb") as handle:- source = handle.read()- if not newer_python:- compile(source, rel, "exec", dont_inherit=True)- elif reason := _commit.conflict_marker(source):- raise SyntaxError(f"{rel}: {reason}")+ # Pre-commit gate: a target whose startup modules do not compile is refused untouched, judged+ # under the interpreter the target admits (``startup_syntax_error``, review N15).+ if broken := _commit.tree_syntax_error(Path(extracted), _UPDATE_CRITICAL_FILES):+ raise SyntaxError(f"{broken[0]}: {broken[1]}")# The commit point: tail + fleet restart owed before the first live rename._commit.arm_commit_obligations(root, target_sha or "")for entry in journal_entries:diff --git a/tests/hermes_cli/test_update_post_pull_syntax_guard.py b/tests/hermes_cli/test_update_post_pull_syntax_guard.pyindex c997916afb1..8be74fd83e8 100644--- a/tests/hermes_cli/test_update_post_pull_syntax_guard.py+++ b/tests/hermes_cli/test_update_post_pull_syntax_guard.py@@ -19,6 +19,7 @@ from hermes_cli import mainimport pytestimport subprocessimport sys+from pathlib import Path# ---------------------------------------------------------------------------@@ -89,19 +90,16 @@ def test_pull_rolls_back_broken_critical_file_and_accepts_corrected_retry(tmp_paassert subprocess.run([sys.executable, str(source)], capture_output=True, text=True, encoding="utf-8", check=True).stdout == "corrected\n"-def test_syntax_guards_skip_a_target_that_requires_a_newer_python(tmp_path, monkeypatch):- """A release that bumps ``requires-python`` past this interpreter may use syntax only the new- Python parses; compiling it here would refuse that release forever. A target this interpreter- satisfies is still refused for the same file (real git object store, real worktree)."""- from hermes_cli import update_cmd_commit as commit-+def _python_bump_repo(tmp_path, broken_source: str):+ """Commits: ``newer`` (requires-python >=3.99, ``hermes_constants.py`` = broken_source) and ``same``+ (the same file, a requires-python this interpreter satisfies)."""def git(*args):return subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True, text=True, encoding="utf-8").stdout.strip()git("init", "-b", "main")git("config", "user.email", "[email protected]")git("config", "user.name", "Test")- (tmp_path / "hermes_constants.py").write_text("def newer_syntax(:\n", encoding="utf-8")+ (tmp_path / "hermes_constants.py").write_text(broken_source, encoding="utf-8")pyproject = tmp_path / "pyproject.toml"pyproject.write_text('[project]\nname = "x"\nrequires-python = ">=3.99"\n', encoding="utf-8")git("add", ".")@@ -109,18 +107,126 @@ def test_syntax_guards_skip_a_target_that_requires_a_newer_python(tmp_path, monknewer = git("rev-parse", "HEAD")pyproject.write_text('[project]\nname = "x"\nrequires-python = ">=3.8"\n', encoding="utf-8")git("commit", "-am", "same file, this python")- same = git("rev-parse", "HEAD")+ return git, newer, git("rev-parse", "HEAD")+++def test_a_python_bump_with_no_admitted_interpreter_is_still_syntax_checked(tmp_path, monkeypatch):+ """A release that raises requires-python past this interpreter used to be held only to a+ conflict-marker scan, so ``def broken(:`` (broken under every Python) passed preflight and the+ post-pull guard (review N15). With no installed interpreter the target admits, this one judges,+ and the refusal names the Python to install (real git object store, real worktree)."""+ from hermes_cli import update_cmd_commit as commit+ monkeypatch.setattr(commit, "_admitted_python", lambda spec: None)+ git, newer, same = _python_bump_repo(tmp_path, "def broken(:\n")critical = ["hermes_constants.py"]- assert commit.target_syntax_error(["git"], tmp_path, newer, critical) is None- refused = commit.target_syntax_error(["git"], tmp_path, same, critical)+ refused = commit.target_syntax_error(["git"], tmp_path, newer, critical)assert refused is not None and refused[0] == "hermes_constants.py"+ assert "uv python install '>=3.99'" in refused[1]+ assert commit.target_syntax_error(["git"], tmp_path, same, critical)[0] == "hermes_constants.py"- # The post-pull backstop judges the worktree the same way (no rollback, no exit).+ # The post-pull backstop judges the worktree the same way: rolled back, exit 1.monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)git("checkout", "-q", newer)- update_cmd._rollback_if_pulled_syntax_error(["git"], same)- assert git("rev-parse", "HEAD") == newer+ with pytest.raises(SystemExit):+ update_cmd._rollback_if_pulled_syntax_error(["git"], same)+ assert git("rev-parse", "HEAD") == same++[email protected]("posix")[email protected]("verdict", ["null", '["hermes_constants.py", "SyntaxError: judged by the target"]'])+def test_a_python_bump_is_judged_by_an_interpreter_the_target_admits(tmp_path, monkeypatch, verdict):+ """Newer grammar this interpreter rejects is admitted when the target's own Python accepts it,+ and refused when that Python rejects it: its verdict, not this compile(), decides (N15)."""+ from hermes_cli import update_cmd_commit as commit++ target_python = tmp_path / "python3.99"+ target_python.write_text(f"#!/bin/sh\ncat > /dev/null\necho '{verdict}'\n", encoding="utf-8")+ target_python.chmod(0o755)+ monkeypatch.setattr(commit, "_admitted_python", lambda spec: str(target_python))+ repo = tmp_path / "repo"+ repo.mkdir()+ _git, newer, _same = _python_bump_repo(repo, "def newer_syntax(:\n")+ judged = commit.target_syntax_error(["git"], repo, newer, ["hermes_constants.py"])+ if verdict == "null":+ assert judged is None+ else:+ assert judged == ("hermes_constants.py", f"SyntaxError: judged by the target (judged by {target_python})")+++def test_the_critical_inventory_covers_every_module_the_entry_paths_import_first():+ """``hermes_bootstrap.py`` was absent from the inventory, so a target that broke only the+ bootstrap passed preflight and the post-pull guard and failed at the first import (review G3).+ Derived from the real launcher text, ``hermes_bootstrap``'s imports and the recovery closure."""+ import ast++ from hermes_cli import _launchers+ from hermes_cli._early_recovery import RECOVERY_CLOSURE++ root = Path(update_cmd.__file__).resolve().parents[1]++ def files(source: str) -> set[str]:+ names = set()+ for node in ast.walk(ast.parse(source)):+ if isinstance(node, ast.Import):+ names |= {alias.name for alias in node.names}+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:+ names |= {node.module, *(f"{node.module}.{alias.name}" for alias in node.names)}+ found = set()+ for name in names:+ parts = name.split(".")+ for i in range(1, len(parts) + 1):+ stem = "/".join(parts[:i])+ found |= {rel for rel in (f"{stem}.py", f"{stem}/__init__.py") if (root / rel).is_file()}+ return found++ launcher = _launchers._launcher_script("hermes", root, None)+ entry = files(launcher) | files((root / "hermes_bootstrap.py").read_text(encoding="utf-8"))+ entry |= {"hermes_bootstrap.py", *RECOVERY_CLOSURE}+ assert "hermes_bootstrap.py" in entry and "hermes_cli/main.py" in entry+ assert entry <= set(update_cmd._UPDATE_CRITICAL_FILES), sorted(entry - set(update_cmd._UPDATE_CRITICAL_FILES))+++def test_a_malformed_bootstrap_is_refused_before_the_move(tmp_path):+ """The preflight reads the real inventory from the target commit: a broken bootstrap refuses."""+ from hermes_cli import update_cmd_commit as commit++ def git(*args):+ return subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True, text=True, encoding="utf-8").stdout.strip()++ git("init", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "Test")+ (tmp_path / "hermes_bootstrap.py").write_text("def broken(:\n", encoding="utf-8")+ (tmp_path / "hermes_constants.py").write_text("ok = 1\n", encoding="utf-8")+ git("add", ".")+ git("commit", "-m", "broken bootstrap")+ refused = commit.target_syntax_error(["git"], tmp_path, "HEAD", update_cmd._UPDATE_CRITICAL_FILES)+ assert refused is not None and refused[0] == "hermes_bootstrap.py"+++def test_the_preflight_reads_every_critical_file_in_one_git_spawn(tmp_path, monkeypatch):+ """One ``git cat-file --batch`` for pyproject + the whole inventory, not a ``git show`` each."""+ from hermes_cli import update_cmd_commit as commit++ def git(*args):+ return subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True, text=True, encoding="utf-8").stdout.strip()++ git("init", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "Test")+ for rel in ("hermes_constants.py", "cli.py"):+ (tmp_path / rel).write_text("ok = 1\n", encoding="utf-8")+ (tmp_path / "hermes_cli").mkdir()+ (tmp_path / "hermes_cli" / "main.py").write_text("x = (\n", encoding="utf-8")+ git("add", ".")+ git("commit", "-m", "c")+ spawns = []+ real = commit.run_git+ monkeypatch.setattr(commit, "run_git", lambda git_cmd, args, **kw: spawns.append(args) or real(git_cmd, args, **kw))+ refused = commit.target_syntax_error(["git"], tmp_path, "HEAD", update_cmd._UPDATE_CRITICAL_FILES)+ assert refused is not None and refused[0] == "hermes_cli/main.py"+ assert spawns == [["cat-file", "--batch"]]def test_the_tree_move_marker_records_the_absolute_git_the_repair_reruns(tmp_path, monkeypatch):