The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a custody refusal is what `hermes update` reports, and every refusal is receipted (R8 m2)
Teknium2d36c7b6439b
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 6ebbb4a2231..1d6b68f9f41 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2525,10 +2525,17 @@ def cmd_update(args):from hermes_cli.update_cmd import _cmd_update_implfrom pm import InstallError+ def _custody_refusal() -> str | None:+ # m2: readers swallow an OSError, so a refused update child can end the run as a misleading+ # downstream error; the refusal is what stopped it. Never on POSIX (nothing refuses there).+ custody = sys.modules.get("hermes_cli.update_custody")+ return custody.refusal_notice() if custody is not None else None+try:_cmd_update_impl(args, gateway_mode=gateway_mode)except (InstallError, OSError, subprocess.SubprocessError) as exc:- print(f"✗ Update failed: {exc}")+ refusal = _custody_refusal()+ print(refusal or f"✗ Update failed: {exc}")_finalize_update_receipt(1, f"{type(exc).__name__}: {exc}")if gateway_mode:from hermes_cli.update_cmd_fleet import _write_gateway_update_exit_code@@ -2540,6 +2547,8 @@ def cmd_update(args):# reach an inner finalize. Persist any still-open receipt with the real# exit code (no-op if already finalized), then let the exit proceed._code = _update_exit.code if isinstance(_update_exit.code, int) else 1+ if _code and (refusal := _custody_refusal()):+ print(refusal)_finalize_update_receipt(_code, f"sys.exit({_code})")if gateway_mode and _code:from hermes_cli.update_cmd_fleet import _write_gateway_update_exit_codediff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex 0eeaec55502..69c47cacee1 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -481,6 +481,10 @@ def _finish(request: dict, result_path: Path) -> int:_report_unbuilt_desktop(request)update_receipt.record_followup("completion", f"{type(exc).__name__}: {exc}")finally:+ custody = sys.modules.get("hermes_cli.update_custody")+ refusal = custody.refusal_notice() if code and custody is not None else None+ if refusal: # m2: what stopped it, whatever error the refusal turned into downstream+ print(refusal)# The new interpreter owns recovery too. The original parent's atexit# token is updated from the response; it acts only if this process dies.try:diff --git a/hermes_cli/update_custody.py b/hermes_cli/update_custody.pyindex 57cea1bbdcc..36a61610c8c 100644--- a/hermes_cli/update_custody.py+++ b/hermes_cli/update_custody.py@@ -85,11 +85,63 @@ class CustodyRefused(OSError):import osname = os.path.basename(str(argv[0])) if argv else "child"- super().__init__(+ self.reason = (f"Windows would not put `{name}` in this update's process job ({cause}), so it was not ""run: a checkout writer outside the job could outlive a killed update and write the "- "checkout after its lock is released. Run the command again from a regular terminal, "- "outside any sandbox or tool that confines the processes it starts.")+ "checkout after its lock is released.")+ super().__init__(f"{self.reason} {_RETRY.format(command='the command')}")+++_RETRY = ("Run {command} again from a regular terminal, outside any sandbox or tool that confines "+ "the processes it starts.")+++# This run's custody (m2): whether an update child already ran in custody, and the first refusal.+# Many readers swallow an OSError (a reader's None, a best-effort probe), so a refusal can end+# the update as a misleading downstream error; the command's failure path prints+# :func:`refusal_notice` instead.+_RUN: dict = {"ran": False, "refused": None}+++def _refuse(argv: Sequence[str], cause: object, *, receipted: bool = False) -> CustodyRefused:+ """The :class:`CustodyRefused` for ``argv``: logged, noted in the receipt (unless the caller+ already did) and kept as this run's first refusal."""+ argv = list(argv) if isinstance(argv, (list, tuple)) else [argv]+ exc = CustodyRefused(argv, cause)+ detail = f"{exc.reason}: {' '.join(str(arg) for arg in argv[:2])}"+ if not receipted:+ logger.warning("Refused update child: %s", detail)+ with contextlib.suppress(Exception):+ from hermes_cli.update_receipt import record_step++ record_step("update_custody", False, detail)+ if _RUN["refused"] is None:+ _RUN["refused"] = (exc, not _RUN["ran"] and not _past_commit())+ return exc+++def _past_commit() -> bool:+ """The update reached its commit point: its receipt records the ``apply`` stage (the+ completion child resumes that receipt). No receipt is open before an update begins, nor in+ the parent after its completion child returned, which starts no update child."""+ try:+ from hermes_cli.update_receipt import _current++ current = _current.get()+ except Exception: # noqa: BLE001 - unknown: never claim that nothing changed+ return True+ return current is not None and any(stage.get("name") == "apply" for stage in current.data.get("stages") or ())+++def refusal_notice(command: str = "hermes update") -> str | None:+ """What the command's failure path prints when this run refused an update child (m2), in+ place of whatever generic error the refusal turned into downstream; ``None`` otherwise."""+ if _RUN["refused"] is None:+ return None+ exc, unchanged = _RUN["refused"]+ outcome = ("Nothing was changed: no update step had run yet." if unchanged else+ "Update steps before it had already run.")+ return f"✗ `{command}` stopped: {exc.reason}\n {outcome}\n {_RETRY.format(command=f'`{command}`')}"def git_subcommand(args: Sequence[str]) -> str | None:@@ -169,23 +221,16 @@ def _bind_suspended(proc: subprocess.Popen) -> None:Suspended until bound, so nothing it spawns can escape the job. A refused bind kills thechild before it ran a single instruction and raises :class:`CustodyRefused` (D2: never anunfenced writer); a failed resume kills the child."""- import ctypes-- from hermes_cli.update_lock import _bind_to_kill_on_close_job+ from hermes_cli.update_lock import _bind_to_kill_on_close_job, resume_suspended_childtry:_bind_to_kill_on_close_job(proc)except OSError as exc:proc.kill()proc.wait()- logger.warning("Refused update child %s: the update's job would not take it (%s)", proc.args, exc)- raise CustodyRefused(proc.args if isinstance(proc.args, (list, tuple)) else [proc.args], exc) from exc- ntdll = ctypes.WinDLL("ntdll")- ntdll.NtResumeProcess.argtypes = [ctypes.c_void_p]- ntdll.NtResumeProcess.restype = ctypes.c_long- if ntdll.NtResumeProcess(int(proc._handle)) != 0:- proc.kill()- raise OSError(f"could not resume update child {proc.pid}")+ raise _refuse(proc.args, exc) from exc+ resume_suspended_child(proc)+ _RUN["ran"] = Truedef popen(argv: Sequence[str], *, inherit_lock: bool = False, **kwargs) -> subprocess.Popen:@@ -392,7 +437,7 @@ def contained_command(argv: Sequence[str], *, inherit_lock: bool = True):try:handle = _inheritable_job_handle()except OSError as exc:- raise CustodyRefused(argv, exc) from exc+ raise _refuse(argv, exc) from excimport osimport tempfile@@ -410,7 +455,8 @@ def contained_command(argv: Sequence[str], *, inherit_lock: bool = True):note = _report_refused_join(report, argv)if note:cause = note.removeprefix(f"{_CUSTODY_UNAVAILABLE} (").partition(")")[0]- raise CustodyRefused(argv, cause)+ raise _refuse(argv, cause, receipted=True)+ _RUN["ran"] = Truedef _inheritable_job_handle() -> int:diff --git a/tests/hermes_cli/test_update_custody.py b/tests/hermes_cli/test_update_custody.pyindex c913f749881..0c15acb2519 100644--- a/tests/hermes_cli/test_update_custody.py+++ b/tests/hermes_cli/test_update_custody.py@@ -197,6 +197,44 @@ def test_a_refused_build_join_is_logged_and_noted_in_the_receipt(tmp_path, monkeassert update_custody._report_refused_join(str(empty), ["node"]) is None # joined: silent+def test_a_swallowed_refusal_is_what_the_update_reports(tmp_path, monkeypatch, capsys):+ """R8 m2: readers swallow an OSError (``_git_stdout``, ``_capture_head_sha``), so a refused+ child used to end ``hermes update`` as whatever error followed downstream. The refusal is+ receipted and kept for the run, and the command's failure path prints it, actionably."""+ import contextlib+ from types import SimpleNamespace++ import hermes_cli.update_receipt as ur+ from hermes_cli import main, update_cmd, update_custody, update_owning_install++ monkeypatch.setattr(update_custody, "_RUN", {"ran": False, "refused": None})+ monkeypatch.setattr(update_owning_install, "retarget_to_owning_install", lambda root: None)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ (tmp_path / "checkout").mkdir()+ monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path / "checkout")+ monkeypatch.setattr(main, "_update_preflight_handled", lambda args: False)+ monkeypatch.setattr(main, "_install_hangup_protection", lambda **kw: None)+ monkeypatch.setattr(main, "_finalize_update_output", lambda state: None)++ def impl(args, gateway_mode):+ ur.begin_update_receipt()+ with contextlib.suppress(OSError): # a reader that swallows it, as _git_stdout does+ raise update_custody._refuse(["git", "rev-parse"], OSError(6, "The handle is invalid"))+ print("✗ Could not resolve HEAD") # the downstream error it turned into+ raise SystemExit(1)++ monkeypatch.setattr(update_cmd, "_cmd_update_impl", impl)+ with ur.update_receipt_scope(), pytest.raises(SystemExit) as stop:+ main.cmd_update(SimpleNamespace(gateway=False))+ assert stop.value.code == 1+ out = capsys.readouterr().out+ assert "`hermes update` stopped: Windows would not put `git` in this update's process job" in out, out+ assert "Nothing was changed" in out and "Run `hermes update` again from a regular terminal" in out, out+ payload = ur.read_latest_receipt()+ steps = [s for s in payload["steps"] if s["name"] == "update_custody"]+ assert steps and steps[0]["ok"] is False and "rev-parse" in steps[0]["detail"], payload["steps"]++@pytest.mark.skipif(not Path("/proc/self/fd").is_dir(), reason="needs /proc fd listing")def test_a_partial_clone_move_never_fetches_under_the_lock_fd(repo, tmp_path, monkeypatch):"""m3: installer checkouts are partial clones, so `reset --hard <target>` used to fetch thediff --git a/tests/hermes_cli/test_update_lock_windows_live.py b/tests/hermes_cli/test_update_lock_windows_live.pyindex a2b882b1fa9..53135d325f1 100644--- a/tests/hermes_cli/test_update_lock_windows_live.py+++ b/tests/hermes_cli/test_update_lock_windows_live.py@@ -337,3 +337,49 @@ def test_a_completion_child_runs_only_after_its_bind_and_a_refusal_is_receipted(assert result["exit_code"] == 0 and started.exists(), resultsteps = [s for s in result["receipt"].get("steps", []) if s["name"] == "update_custody"]assert steps and steps[0]["ok"] is False and "completion child" in steps[0]["detail"], result["receipt"]+++# --- R8 m2: a refusal a reader swallows is what `hermes update` reports -----------------------++_SWALLOWING_OWNER = r"""+import sys+from pathlib import Path+from types import SimpleNamespace+sys.path.insert(0, sys.argv[1])+from hermes_cli import main, update_cmd, update_owning_install+from hermes_cli.update_cmd_git import _git_stdout+root = Path(sys.argv[2])+main.PROJECT_ROOT = root+update_owning_install.retarget_to_owning_install = lambda project_root: None+main._update_preflight_handled = lambda args: False+main._install_hangup_protection = lambda **kw: None+main._finalize_update_output = lambda state: None++def impl(args, gateway_mode):+ from hermes_cli.update_receipt import begin_update_receipt+ begin_update_receipt()+ REFUSE_JOBS+ # The real readers swallow the refusal: HEAD reads as unknown.+ pre, head = update_cmd._capture_head_sha(["git"], root), _git_stdout(["git"], ["rev-parse", "HEAD"], root)+ print(f"✗ Could not resolve the checkout's HEAD ({pre!r}, {head!r})", flush=True)+ sys.exit(1)++update_cmd._cmd_update_impl = impl+main.cmd_update(SimpleNamespace(gateway=False))+"""+++def test_a_refusal_the_readers_swallow_is_what_the_update_reports(tmp_path):+ install = tmp_path / "checkout"+ install.mkdir()+ _git(install, "init", "-q")+ refuse = "\n ".join(_REFUSE_JOBS.strip().splitlines())+ home = tmp_path / "home"+ out = subprocess.run([sys.executable, "-c", _SWALLOWING_OWNER.replace("REFUSE_JOBS", refuse), str(REPO_ROOT),+ str(install)], stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=120,+ env={**os.environ, "HERMES_HOME": str(home), "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"})+ text = out.stdout + out.stderr+ assert out.returncode == 1, text+ assert "`hermes update` stopped: Windows would not put `git` in this update's process job" in text, text+ assert "Nothing was changed" in text and "Run `hermes update` again from a regular terminal" in text, text