The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(pm): own the lock/atomic-write primitives in pm.filesystem
ethernetb728fdd6276b
diff --git a/hermes_cli/runtime_state.py b/hermes_cli/runtime_state.pyindex 813c7bd233e..7a74b6e9d5f 100644--- a/hermes_cli/runtime_state.py+++ b/hermes_cli/runtime_state.py@@ -2,7 +2,6 @@from __future__ import annotationsimport atexit-import errnoimport base64from collections.abc import Callablefrom contextlib import contextmanager, suppress@@ -12,11 +11,19 @@ import loggingimport osfrom pathlib import Pathimport shutil-import tempfileimport timeimport uuidfrom pm.environments import dependency_home_root, install_state_dir, runtime_facts_path+# Private aliases: this module calls them through its globals (tests patch ``_atomic_bytes``+# here) and updaters shipped before PM import them by these names mid-swap+# (tests/compat/old_updater_surface.json). New code imports the pm.filesystem names.+from pm.filesystem import (+ durable_write_bytes as _atomic_bytes,+ file_digest as _digest,+ lock_fd as _lock,+ read_bytes_or_none as _bytes,+)LOG = logging.getLogger(__name__)@@ -26,37 +33,6 @@ LOG = logging.getLogger(__name__)# binds its port is worse than one that binds against the previous generation. Losers skip — the# same rule boot_bootstrap._RecordLock states for home maintenance.INSTALL_LOCK_TIMEOUT_SECONDS = 10.0-_LOCK_POLL_SECONDS = 0.05---def _lock(fd: int, *, wait: bool, timeout: float | None = None) -> bool:- """Take the byte lock; ``timeout`` bounds the retry loop (None waits forever, 0 tries once)."""- deadline = None if timeout is None else time.monotonic() + timeout- if os.name == "nt":- import msvcrt- while True:- try:- os.lseek(fd, 0, os.SEEK_SET)- msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)- return True- except OSError as exc:- if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):- raise- if not wait or (deadline is not None and time.monotonic() >= deadline):- return False- time.sleep(_LOCK_POLL_SECONDS)- else:- import fcntl- while True:- try:- fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)- return True- except BlockingIOError:- pass- if not wait or (deadline is not None and time.monotonic() >= deadline):- return False- time.sleep(_LOCK_POLL_SECONDS)-@contextmanagerdef runtime_lock(project: Path, *, timeout: float | None = INSTALL_LOCK_TIMEOUT_SECONDS):@@ -81,37 +57,6 @@ def runtime_lock(project: Path, *, timeout: float | None = INSTALL_LOCK_TIMEOUT_os.close(fd)-def _bytes(path: Path) -> bytes | None:- try:- return path.read_bytes()- except FileNotFoundError:- return None---def _digest(path: Path) -> str | None:- data = _bytes(path)- return hashlib.sha256(data).hexdigest() if data is not None else None---def _atomic_bytes(path: Path, data: bytes):- path.parent.mkdir(parents=True, exist_ok=True)- fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".publish-")- try:- with os.fdopen(fd, "wb") as stream:- stream.write(data)- stream.flush()- os.fsync(stream.fileno())- os.replace(temporary, path)- if os.name != "nt":- directory = os.open(path.parent, os.O_RDONLY)- try:- os.fsync(directory)- finally:- os.close(directory)- finally:- Path(temporary).unlink(missing_ok=True)--def _recover_plugin_publication(project: Path, row: dict, journal: Path) -> None:from hermes_cli.fs_utils import rmtree_forcediff --git a/pm/client.py b/pm/client.pyindex c1c95c4d6df..54af0488e0f 100644--- a/pm/client.py+++ b/pm/client.py@@ -207,8 +207,8 @@ def sync_venv(extras=None, *, explicit=False, plugin_dirs=None, extra_plugin_dirf"({sys.prefix}); only an explicit install may change what later processes boot into",)if selection is not None and "expected_config" not in selection:- from hermes_cli.runtime_state import _digest- selection = {**selection, "expected_config": _digest(Path(selection["home"]) / "config.yaml") or "missing"}+ from pm.filesystem import file_digest+ selection = {**selection, "expected_config": file_digest(Path(selection["home"]) / "config.yaml") or "missing"}foreign = project_root is not None and Path(project_root).resolve() != paths.repo_root().resolve()if is_runtime() and not foreign:from pm.install import sync_venv as directdiff --git a/pm/download_state.py b/pm/download_state.pyindex 9905e7418e2..a6af93a63b1 100644--- a/pm/download_state.py+++ b/pm/download_state.py@@ -6,7 +6,7 @@ import osfrom pathlib import Pathimport time-from hermes_cli.runtime_state import _lock+from pm.filesystem import lock_fd@contextmanager@@ -17,7 +17,7 @@ def partial_lock(root: Path, key: str, *, cancelled=None, wait: bool = True):locks.mkdir(parents=True, exist_ok=True)fd = os.open(locks / key, os.O_CREAT | os.O_RDWR, 0o600)try:- while not _lock(fd, wait=False):+ while not lock_fd(fd, wait=False):if not wait:yield Falsereturndiff --git a/pm/downloader.py b/pm/downloader.pyindex 6fa2ebc2f25..0176e814e10 100644--- a/pm/downloader.py+++ b/pm/downloader.py@@ -445,14 +445,14 @@ class Download:@staticmethoddef _write_sidecar(side: Path, part: Path, covered: _Ranges, remote: _Remote, sha256: str) -> None:- from hermes_cli.runtime_state import _atomic_bytes+ from pm.filesystem import durable_write_bytes# All writers have closed before coverage is persisted. A sidecar can# describe durable bytes, never data still buffered in a worker.with part.open("r+b") as stream:os.fsync(stream.fileno())record = {"total": remote.total, "etag": remote.etag, "sha256": sha256, "ranges": covered}- _atomic_bytes(side, json.dumps(record).encode("utf-8"))+ durable_write_bytes(side, json.dumps(record).encode("utf-8"))def _fetch_ranged(self, source: Source, remote: _Remote, tick) -> int:key = self._key(source.url)diff --git a/pm/filesystem.py b/pm/filesystem.pyindex df86354f550..f7dc30b4823 100644--- a/pm/filesystem.py+++ b/pm/filesystem.py@@ -1,11 +1,82 @@-"""Filesystem checks used before PM can replace the caller's interpreter."""+"""Stdlib-only filesystem primitives PM needs before it can replace the caller's interpreter.++Boot-time dependency selection (``hermes_cli.runtime_state``) imports these, so nothing here+may import a dependency or another PM module.+"""from __future__ import annotations+import errno+import hashlibimport osfrom pathlib import Pathimport stat+import tempfile+import time++_LOCK_POLL_SECONDS = 0.05def is_junction(path: Path) -> bool:"""Keep junctions opaque even before Python 3.12's Path.is_junction exists."""return os.name == "nt" and path.lstat().st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT+++def lock_fd(fd: int, *, wait: bool, timeout: float | None = None) -> bool:+ """Take the byte lock; ``timeout`` bounds the retry loop (None waits forever, 0 tries once)."""+ deadline = None if timeout is None else time.monotonic() + timeout+ if os.name == "nt":+ import msvcrt+ while True:+ try:+ os.lseek(fd, 0, os.SEEK_SET)+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)+ return True+ except OSError as exc:+ if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):+ raise+ if not wait or (deadline is not None and time.monotonic() >= deadline):+ return False+ time.sleep(_LOCK_POLL_SECONDS)+ else:+ import fcntl+ while True:+ try:+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ return True+ except BlockingIOError:+ pass+ if not wait or (deadline is not None and time.monotonic() >= deadline):+ return False+ time.sleep(_LOCK_POLL_SECONDS)+++def read_bytes_or_none(path: Path) -> bytes | None:+ try:+ return path.read_bytes()+ except FileNotFoundError:+ return None+++def file_digest(path: Path) -> str | None:+ data = read_bytes_or_none(path)+ return hashlib.sha256(data).hexdigest() if data is not None else None+++def durable_write_bytes(path: Path, data: bytes) -> None:+ """Replace ``path`` atomically and fsync file and directory so a crash keeps old or new bytes."""+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".publish-")+ try:+ with os.fdopen(fd, "wb") as stream:+ stream.write(data)+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, path)+ if os.name != "nt":+ directory = os.open(path.parent, os.O_RDONLY)+ try:+ os.fsync(directory)+ finally:+ os.close(directory)+ finally:+ Path(temporary).unlink(missing_ok=True)diff --git a/pm/lock.py b/pm/lock.pyindex ba3ef60a149..e13773ea7af 100644--- a/pm/lock.py+++ b/pm/lock.py@@ -64,8 +64,8 @@ def _read(path: Path, *, strict: bool = False) -> dict:def _write(path: Path, data: dict) -> None:- from hermes_cli.runtime_state import _atomic_bytes- _atomic_bytes(path, (json.dumps(data, indent=2, sort_keys=True) + "\n").encode("utf-8"))+ from pm.filesystem import durable_write_bytes+ durable_write_bytes(path, (json.dumps(data, indent=2, sort_keys=True) + "\n").encode("utf-8"))class StaleLockRow(RuntimeError):@@ -109,12 +109,12 @@ class Lockfile:def save(self) -> None:"""Merge touched rows under the file's lock, or leave all rows unchanged."""- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdself.path.parent.mkdir(parents=True, exist_ok=True)fd = os.open(self.path.with_name(f".{self.path.name}.lock"), os.O_CREAT | os.O_RDWR, 0o600)try:- _lock(fd, wait=True)+ lock_fd(fd, wait=True)current = _read(self.path, strict=True)["packages"]updated = dict(current)for name in self._touched:diff --git a/pm/operations.py b/pm/operations.pyindex 4dbdbf20680..f25421b7ccf 100644--- a/pm/operations.py+++ b/pm/operations.py@@ -254,7 +254,7 @@ def _ensure_generation(Build at the final path: Windows launchers and scripts embed that path.The prior generation survives both successful replacement and failed builds."""- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdfrom pm._uv import _toolchainfrom pm.install import _refuse_lazy, lazy_installs_allowedfrom pm.lock import Lockfile, _write@@ -293,7 +293,7 @@ def _ensure_generation(raise _refuse_lazy(name, "isolated Python environment is missing or outdated")root.mkdir(parents=True, exist_ok=True)with (root / ".install.lock").open("a+b") as mutex:- _lock(mutex.fileno(), wait=True)+ lock_fd(mutex.fileno(), wait=True)base_python = selected_python()existing = current(base_python)if existing is not None:diff --git a/pm/publication.py b/pm/publication.pyindex a2b42314d9d..3ea1c7d4ac3 100644--- a/pm/publication.py+++ b/pm/publication.py@@ -13,7 +13,7 @@ import threadingfrom pathlib import Pathfrom pm.environments import dependency_home_root, install_state_dir, runtime_facts_path-from hermes_cli.runtime_state import _atomic_bytes, _bytes, _digest+from pm.filesystem import durable_write_bytes, file_digest, read_bytes_or_nonefrom pm.workspace import enabled_plugin_dirs, _is_member_candidate@@ -46,7 +46,7 @@ def candidate_members(extra_dirs=(), **selection):def selection_snapshot() -> dict[Path, bytes | None]:from pm.plugins_state import dependency_homes- return {home / "config.yaml": _bytes(home / "config.yaml") for home in dependency_homes()}+ return {home / "config.yaml": read_bytes_or_none(home / "config.yaml") for home in dependency_homes()}def validate_manifest(source: Path) -> dict:@@ -68,7 +68,7 @@ class PluginSelection:if not self.home.is_relative_to(dependency_home_root().resolve()):raise ValueError("config path is outside Hermes state")self.path = self.home / "config.yaml"- self.previous = _bytes(self.path)+ self.previous = read_bytes_or_none(self.path)expected = selection.get("expected_config")actual = hashlib.sha256(self.previous).hexdigest() if self.previous is not None else "missing"if expected is not None and expected != actual:@@ -91,14 +91,14 @@ class PluginSelection:enabled=selection["enabled"], disabled=selection["disabled"])def publish(self, project: Path) -> None:- if selection_snapshot() != self.configs or _bytes(self.path) != self.previous:+ if selection_snapshot() != self.configs or read_bytes_or_none(self.path) != self.previous:raise ValueError("plugin configuration changed while preparing publication; retry")row = {"config": str(self.path),"previous": base64.b64encode(self.previous).decode() if self.previous is not None else None,- "facts_before": _digest(runtime_facts_path(project)),+ "facts_before": file_digest(runtime_facts_path(project)),"config_after": hashlib.sha256(self.proposed).hexdigest()}- _atomic_bytes(install_state_dir(project) / "publication.json", json.dumps(row).encode())- _atomic_bytes(self.path, self.proposed)+ durable_write_bytes(install_state_dir(project) / "publication.json", json.dumps(row).encode())+ durable_write_bytes(self.path, self.proposed)class StagedPlugin:@@ -119,7 +119,7 @@ class StagedPlugin:raise ValueError("The updated plugin changed its installed name; reinstall it explicitly.")self.staged_digest = tree_digest(self.staged)self.metadata = self.target.parent / ".install-metadata.json"- previous = _bytes(self.metadata)+ previous = read_bytes_or_none(self.metadata)current = _metadata_records(previous)self.old_record = plugin["old_metadata"].get(self.target.name)if current.get(self.target.name) != self.old_record:@@ -152,7 +152,7 @@ class StagedPlugin:lock = self.metadata.with_name(f"{self.metadata.name}.lock")with _file_lock(lock, _METADATA_LOCK_HOLDER, 10.0,"Timed out waiting for the plugin install metadata lock"):- previous = _bytes(self.metadata)+ previous = read_bytes_or_none(self.metadata)metadata = _metadata_records(previous)if metadata.get(self.target.name) != self.old_record:raise ValueError("Plugin install metadata changed while preparing the update; retry.")@@ -164,12 +164,12 @@ class StagedPlugin:backup = self.target.parent / f".previous-{uuid.uuid4().hex}"row = {"kind": "plugin", "target": str(self.target), "backup": str(backup), "metadata": str(self.metadata),- "target_existed": self.target.exists(), "facts_before": _digest(runtime_facts_path(project)),+ "target_existed": self.target.exists(), "facts_before": file_digest(runtime_facts_path(project)),"metadata_before": base64.b64encode(previous).decode() if previous is not None else None,"metadata_after": base64.b64encode(proposed).decode(),}- _atomic_bytes(install_state_dir(project) / "publication.json", json.dumps(row).encode())+ durable_write_bytes(install_state_dir(project) / "publication.json", json.dumps(row).encode())if self.target.exists():os.replace(self.target, backup)os.replace(self.staged, self.target)- _atomic_bytes(self.metadata, proposed)+ durable_write_bytes(self.metadata, proposed)diff --git a/pm/receipt.py b/pm/receipt.pyindex 166ecac185c..34cca627827 100644--- a/pm/receipt.py+++ b/pm/receipt.py@@ -298,7 +298,7 @@ def _receipt_name(data: dict[str, Any]) -> str:def _write_rotated(data: dict[str, Any]) -> Path:"""Use the same stdlib-only atomic writer as PM's installed facts."""- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdfrom pm.lock import _writed = _receipt_dir()@@ -306,7 +306,7 @@ def _write_rotated(data: dict[str, Any]) -> Path:path = d / _receipt_name(data)# Concurrent completions share latest.json; serialize its replacement.with (d / ".pm-write.lock").open("a+b") as lock:- _lock(lock.fileno(), wait=True)+ lock_fd(lock.fileno(), wait=True)_write(path, data)_write(d / "latest.json", data)_rotate(d)diff --git a/pm/runtime.py b/pm/runtime.pyindex 5ac889d2bdd..dca7b0e8fb3 100644--- a/pm/runtime.py+++ b/pm/runtime.py@@ -110,7 +110,7 @@ def prepare_runtime(uv: Path, python: Path, root: Path, *, offline: bool = FalseGenerations are immutable after publication. Failed preparation leaves theprevious generation intact, including when an old worker is still running."""- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdfrom pm.lock import _writefrom pm.runtime_stage import stage_runtime@@ -119,7 +119,7 @@ def prepare_runtime(uv: Path, python: Path, root: Path, *, offline: bool = Falseenv = runtime_environment()root.mkdir(parents=True, exist_ok=True)with (root / ".prepare.lock").open("a+b") as lock:- _lock(lock.fileno(), wait=True)+ lock_fd(lock.fileno(), wait=True)selected = root / "selected.json"try:fact = json.loads(selected.read_text(encoding="utf-8"))@@ -162,14 +162,15 @@ def collect_runtime_generations(root: Path) -> list[Path]:once every worker launched from it has exited; generations published before leasesexisted stay, as the application collector keeps its own."""- from hermes_cli.runtime_state import _lock, leases_held+ from pm.filesystem import lock_fd+ from hermes_cli.runtime_state import leases_heldgenerations = root / "generations"removed: list[Path] = []if not generations.is_dir():return removedwith (root / ".prepare.lock").open("a+b") as lock:- if not _lock(lock.fileno(), wait=False):+ if not lock_fd(lock.fileno(), wait=False):return removed # a stage is in flight; maintenance skips rather than queuestry:selected = json.loads((root / "selected.json").read_text(encoding="utf-8-sig")).get("generation", "")diff --git a/pm/store.py b/pm/store.pyindex 6e228d0a767..cda20d53710 100644--- a/pm/store.py+++ b/pm/store.py@@ -389,16 +389,16 @@ class Store:@contextmanagerdef install_lock(self):"""Serialize writers using the same advisory lock as runtime publication."""- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdself.root.mkdir(parents=True, exist_ok=True)lock = self.root / ".install.lock"fd = os.open(lock, os.O_CREAT | os.O_RDWR, 0o600)try:# A second `hermes pm install` behind an sdist build otherwise sits# silent for minutes; say what it is waiting on.- if not _lock(fd, wait=True, timeout=2):+ if not lock_fd(fd, wait=True, timeout=2):print(f"waiting for {lock} (another PM operation holds it)", file=sys.stderr, flush=True)- _lock(fd, wait=True)+ lock_fd(fd, wait=True)yieldfinally:os.close(fd)diff --git a/tests/hermes_cli/test_doctor_command_install.py b/tests/hermes_cli/test_doctor_command_install.pyindex 7cfb0f94896..f10a0a3de91 100644--- a/tests/hermes_cli/test_doctor_command_install.py+++ b/tests/hermes_cli/test_doctor_command_install.py@@ -46,7 +46,7 @@ def _pm_source(project, home):root = Path(__file__).resolve().parents[2]for relative in ("hermes", "hermes_bootstrap.py", "hermes_constants.py", "hermes_cli/__init__.py",- "pm/environments.py", "hermes_cli/runtime_state.py",+ "pm/environments.py", "pm/filesystem.py", "hermes_cli/runtime_state.py","hermes_cli/_early_recovery.py", "hermes_cli/_parser.py","hermes_cli/venv_sync.py", "hermes_cli/steward.py", "hermes_cli/stderr_timestamp.py",):diff --git a/tests/hermes_cli/test_launcher_runtime_selection.py b/tests/hermes_cli/test_launcher_runtime_selection.pyindex 02e788f96f3..5cc91062071 100644--- a/tests/hermes_cli/test_launcher_runtime_selection.py+++ b/tests/hermes_cli/test_launcher_runtime_selection.py@@ -26,6 +26,7 @@ def test_minted_launcher_reads_current_selection_and_editable_members(tmp_path,(pm_package / "__init__.py").write_text("")# Real selection code, with a fixture entry point rather than a live CLI.(pm_package / "environments.py").write_bytes(Path(runtime_paths.__file__).read_bytes())+ (pm_package / "filesystem.py").write_bytes((Path(runtime_paths.__file__).parent / "filesystem.py").read_bytes())(package / "runtime_state.py").write_bytes(Path(runtime_state.__file__).read_bytes())(root / "hermes_constants.py").write_bytes(Path(hermes_constants.__file__).read_bytes())(root / "hermes_bootstrap.py").write_text(diff --git a/tests/hermes_cli/test_plugin_install_ref.py b/tests/hermes_cli/test_plugin_install_ref.pyindex d36abe526d8..4d5b33e059a 100644--- a/tests/hermes_cli/test_plugin_install_ref.py+++ b/tests/hermes_cli/test_plugin_install_ref.py@@ -400,12 +400,12 @@ def test_metadata_write_failure_rolls_back_new_install(monkeypatch, tmp_path, is# The PM worker process publishes the plugin; fail its metadata write there.worker_toolchain(client, monkeypatch, isolated_python,"import pm.publication as publication\n"- "original = publication._atomic_bytes\n"+ "original = publication.durable_write_bytes\n""def fail_metadata(path, data):\n"f" if Path(path) == Path({str(metadata)!r}):\n"" raise OSError('disk full')\n"" return original(path, data)\n"- "publication._atomic_bytes = fail_metadata\n")+ "publication.durable_write_bytes = fail_metadata\n")with pytest.raises(PluginOperationError, match="disk full"):_install_plugin_core(repo.as_uri(), force=False, ref=old_sha)diff --git a/tests/hermes_cli/test_plugins_admission_setter.py b/tests/hermes_cli/test_plugins_admission_setter.pyindex 66284304df4..4fbe3cb504d 100644--- a/tests/hermes_cli/test_plugins_admission_setter.py+++ b/tests/hermes_cli/test_plugins_admission_setter.py@@ -30,12 +30,12 @@ def test_failed_publication_preserves_selection_and_imports(plugin_world, monkeyif failure == "config":prelude = ("from pm import publication\n"- "atomic_bytes = publication._atomic_bytes\n"+ "atomic_bytes = publication.durable_write_bytes\n""def fail(path, data):\n"f" if path == Path({str(config)!r}) and b'publication-candidate' in data:\n"" raise OSError('fixture config disk full')\n"" return atomic_bytes(path, data)\n"- "publication._atomic_bytes = fail\n"+ "publication.durable_write_bytes = fail\n")else:# Config and facts now publish in the worker; the failed command mustdiff --git a/tests/hermes_cli/test_source_launcher_publication.py b/tests/hermes_cli/test_source_launcher_publication.pyindex 3f44154b021..3b7aff3e699 100644--- a/tests/hermes_cli/test_source_launcher_publication.py+++ b/tests/hermes_cli/test_source_launcher_publication.py@@ -15,7 +15,7 @@ from pm.environments import install_state_dir, site_packagesROOT = Path(__file__).resolve().parents[2]BOOT_FILES = ("hermes_bootstrap.py", "hermes_constants.py", "hermes_cli/__init__.py", "hermes_cli/_launchers.py",- "pm/environments.py", "pm/paths.py", "hermes_cli/runtime_state.py",+ "pm/environments.py", "pm/filesystem.py", "pm/paths.py", "hermes_cli/runtime_state.py","hermes_cli/_early_recovery.py", "hermes_cli/_parser.py","hermes_cli/venv_sync.py", "hermes_cli/steward.py","hermes_cli/stderr_timestamp.py",diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.pyindex 43de34f8543..ded107f709f 100644--- a/tests/pm/test_pm_core.py+++ b/tests/pm/test_pm_core.py@@ -246,7 +246,7 @@ def test_warm_install_verifies_shared_dependencies_once_under_lock(pm_env, monkeimport importlibimport osfrom collections import Counter- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdfrom pm.cli import _install_namesensure = importlib.import_module("pm.install")@@ -262,7 +262,7 @@ def test_warm_install_verifies_shared_dependencies_once_under_lock(pm_env, monkedef verify(package, fact, store, target):fd = os.open(store.root / ".install.lock", os.O_CREAT | os.O_RDWR, 0o600)try:- locked.append(not _lock(fd, wait=False))+ locked.append(not lock_fd(fd, wait=False))finally:os.close(fd)checked[package.name] += 1@@ -301,7 +301,7 @@ def test_standalone_warm_ensure_does_not_wait_for_unrelated_writer(pm_env):def test_install_forgets_verification_when_state_operation_releases_lock(pm_env, monkeypatch):import importlibimport os- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdfrom pm.cli import _install_namesensure = importlib.import_module("pm.install")@@ -319,7 +319,7 @@ def test_install_forgets_verification_when_state_operation_releases_lock(pm_env,# acquire the lock independently, and invalidate prior observations.fd = os.open(runtime / ".install.lock", os.O_CREAT | os.O_RDWR, 0o600)try:- assert _lock(fd, wait=False), "tool lock leaked into the state operation"+ assert lock_fd(fd, wait=False), "tool lock leaked into the state operation"binary.write_text("corrupt", encoding="utf-8")finally:os.close(fd)diff --git a/tests/pm/test_runtime_gc.py b/tests/pm/test_runtime_gc.pyindex 4851a1f719a..66e8a2d9f10 100644--- a/tests/pm/test_runtime_gc.py+++ b/tests/pm/test_runtime_gc.py@@ -37,13 +37,13 @@ def test_collector_keeps_selected_leased_and_pre_lease_generations(tmp_path):def test_collector_yields_to_an_in_flight_stage(tmp_path):- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdroot = tmp_path / "pm-runtime"aborted = _generation(root, "aborted", published=False)root.mkdir(exist_ok=True)with (root / ".prepare.lock").open("a+b") as lock:- assert _lock(lock.fileno(), wait=False)+ assert lock_fd(lock.fileno(), wait=False)assert collect_runtime_generations(root) == []assert aborted.is_dir()assert collect_runtime_generations(root) == [aborted]diff --git a/tests/pm/test_store_lock_wait.py b/tests/pm/test_store_lock_wait.pyindex a47d21c4495..e190c8e7570 100644--- a/tests/pm/test_store_lock_wait.py+++ b/tests/pm/test_store_lock_wait.py@@ -3,7 +3,7 @@ import osimport threadingimport time-from hermes_cli.runtime_state import _lock+from pm.filesystem import lock_fdfrom pm.store import Store@@ -11,7 +11,7 @@ def test_install_lock_reports_what_it_waits_on(tmp_path, capsys):store = Store(tmp_path / "store")store.root.mkdir()holder = os.open(store.root / ".install.lock", os.O_CREAT | os.O_RDWR, 0o600)- assert _lock(holder, wait=False)+ assert lock_fd(holder, wait=False)entered = threading.Event()def contend():diff --git a/tests/pm/test_worker.py b/tests/pm/test_worker.pyindex 395cf19ae0a..0bfdb7cdc7c 100644--- a/tests/pm/test_worker.py+++ b/tests/pm/test_worker.py@@ -162,10 +162,10 @@ def test_currency_probe_preserves_union_and_candidate_inputs(client, tmp_path, mdef _assert_worker_holds_lock(repo):from pm.environments import install_state_dir- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdwith (install_state_dir(repo) / ".install.lock").open("a+b") as lock:- assert not _lock(lock.fileno(), wait=False), "callback escaped the worker's runtime lock"+ assert not lock_fd(lock.fileno(), wait=False), "callback escaped the worker's runtime lock"@pytest.mark.parametrize("explicit", [True, False])@@ -241,7 +241,7 @@ def test_lazy_disabled_sync_does_not_bootstrap_tools(client, tmp_path, monkeypatdef test_invalid_selection_waits_for_failed_receipt_and_lock_release(client, tmp_path, monkeypatch):import jsonfrom pm.environments import install_state_dir- from hermes_cli.runtime_state import _lock+ from pm.filesystem import lock_fdrepo = _current_environment(tmp_path, monkeypatch, [])home = tmp_path / "home"@@ -252,7 +252,7 @@ def test_invalid_selection_waits_for_failed_receipt_and_lock_release(client, tmpassert len(receipts) == 1assert json.loads(receipts[0].read_text())["outcome"] == "failed"with (install_state_dir(repo) / ".install.lock").open("a+b") as lock:- assert _lock(lock.fileno(), wait=False)+ assert lock_fd(lock.fileno(), wait=False)def _node_archive(server, body=b"#!/bin/sh\nexit 0\n"):diff --git a/tests/pm/test_worker_publication.py b/tests/pm/test_worker_publication.pyindex e73a4f067e7..8255a0135f2 100644--- a/tests/pm/test_worker_publication.py+++ b/tests/pm/test_worker_publication.py@@ -233,7 +233,7 @@ def test_worker_death_recovers_at_each_durable_publication_boundary(f" if {phase!r} == 'journal' and path.name == 'publication.json': os._exit(17)\n"f" if {phase!r} == 'payload' and path == Path({str(payload)!r}): os._exit(17)\n"f" if {phase!r} == 'commit' and path.name == 'publication.json' and json.loads(data).get('committed'): os._exit(17)\n"- "publication._atomic_bytes = state._atomic_bytes = write\n"+ "publication.durable_write_bytes = state._atomic_bytes = write\n""original_replace = os.replace\ndef replace(source, target):\n original_replace(source, target)\n"f" if {phase!r} == 'backup' and Path(target).name.startswith('.previous-'): os._exit(17)\n"f" if {phase!r} == 'tree' and Path(target) == Path({str(target)!r}): os._exit(17)\n"diff --git a/tests/scripts/test_mint_launchers.py b/tests/scripts/test_mint_launchers.pyindex ab4924c8127..4d7decd549b 100644--- a/tests/scripts/test_mint_launchers.py+++ b/tests/scripts/test_mint_launchers.py@@ -67,7 +67,7 @@ def payload_tree(tmp_path: Path):# Exercise the real bootstrap before the fixture entry point.for relative in ("hermes_bootstrap.py", "hermes_constants.py", "hermes_cli/__init__.py",- "pm/environments.py", "hermes_cli/runtime_state.py",+ "pm/environments.py", "pm/filesystem.py", "hermes_cli/runtime_state.py","hermes_cli/_early_recovery.py", "hermes_cli/_parser.py",# prepare_launch returns early for a fixture repo (no .git), but the bootstrap# imports these two before it can tell.