The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(secrets): delete old secret-store copies instead of moving them
emozillaf413c2ee9abc
diff --git a/agent/secret_sources/_cache.py b/agent/secret_sources/_cache.pyindex a53e1bc18f5..218626146d9 100644--- a/agent/secret_sources/_cache.py+++ b/agent/secret_sources/_cache.py@@ -12,21 +12,22 @@ from __future__ import annotationsimport hashlibimport jsonimport time+from contextlib import suppressfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Callable, Dict, Generic, Optional, TypeVarfrom hermes_constants import secure_parent_dir-from utils import adopt_legacy_file, atomic_json_write+from utils import atomic_json_write__all__ = ["CachedFetch","DiskCache","SecretCache","atomic_write_json",+ "current_cache_path","entry_from_payload","fingerprint",- "live_cache_path","remove_cache_file","resolve_cache_home",]@@ -57,10 +58,12 @@ def resolve_cache_home(home_path: Optional[Path] = None) -> Path:return home_path-def live_cache_path(home: Path, name: str) -> Path:- """``<home>/<name>``, after moving a copy from ``<home>/cache/``, where earlier releases kept- the secret caches; that old path when the move fails."""- return adopt_legacy_file(home / name, home / "cache" / name)+def current_cache_path(home: Path, name: str) -> Path:+ """``<home>/<name>``. A copy at ``<home>/cache/<name>``, where earlier releases kept the secret+ caches, is deleted first without being read: the agent can write that folder."""+ with suppress(OSError):+ (home / "cache" / name).unlink()+ return home / namedef remove_cache_file(home: Path, name: str) -> None:@@ -124,15 +127,15 @@ class DiskCache(Generic[K]):def path(self, home_path: Optional[Path] = None) -> Path:return resolve_cache_home(home_path) / self._basename- def _live_path(self, home_path: Optional[Path]) -> Path:- return live_cache_path(resolve_cache_home(home_path), self._basename)+ def _current_path(self, home_path: Optional[Path]) -> Path:+ return current_cache_path(resolve_cache_home(home_path), self._basename)def read(self, key: K, ttl_seconds: float, home_path: Optional[Path] = None) -> Optional[CachedFetch]:"""Fresh cached entry for ``key``, or None (I/O error, mismatch, stale)."""if ttl_seconds <= 0:return Nonetry:- with open(self._live_path(home_path), "r", encoding="utf-8-sig") as f:+ with open(self._current_path(home_path), "r", encoding="utf-8-sig") as f:payload = json.load(f)except (OSError, json.JSONDecodeError):return None@@ -147,7 +150,7 @@ class DiskCache(Generic[K]):returnpayload = {"key": self._key_serializer(key), "secrets": entry.secrets, "fetched_at": entry.fetched_at}try:- atomic_write_json(self._live_path(home_path), payload)+ atomic_write_json(self._current_path(home_path), payload)except OSError:pass # best-effort — a disk-cache miss next invocation is finediff --git a/agent/secret_sources/bitwarden.py b/agent/secret_sources/bitwarden.pyindex 7e09858a38e..9fb2b78dccf 100644--- a/agent/secret_sources/bitwarden.py+++ b/agent/secret_sources/bitwarden.py@@ -23,7 +23,7 @@ from typing import Dict, List, Optional, Tuplefrom agent.secret_sources._cache import (CachedFetch as _CachedFetch, SecretCache, atomic_write_json, entry_from_payload,- fingerprint as _token_fingerprint, live_cache_path, remove_cache_file, resolve_cache_home,+ current_cache_path, fingerprint as _token_fingerprint, remove_cache_file, resolve_cache_home,)from agent.secret_sources.base import (ErrorKind, FetchResult, SecretSource, classify_cli_error, coerce_float,@@ -58,8 +58,8 @@ def _encrypted_disk_cache_path(home_path: Optional[Path] = None) -> Path:return resolve_cache_home(home_path) / _ENCRYPTED_CACHE_BASENAME-def _live_encrypted_disk_cache_path(home_path: Optional[Path] = None) -> Path:- return live_cache_path(resolve_cache_home(home_path), _ENCRYPTED_CACHE_BASENAME)+def _current_encrypted_disk_cache_path(home_path: Optional[Path] = None) -> Path:+ return current_cache_path(resolve_cache_home(home_path), _ENCRYPTED_CACHE_BASENAME)# First matching rule wins. The BSM identity endpoint rejects a revoked /@@ -143,7 +143,7 @@ def _write_encrypted_disk_cache(*, cache_key: _CacheKey, access_token: str, entrciphertext = AESGCM(key).encrypt(nonce, plaintext, serialized_key.encode("utf-8"))payload = {"version": _ENCRYPTED_CACHE_VERSION, "key": serialized_key,"salt": _b64e(salt), "nonce": _b64e(nonce), "ciphertext": _b64e(ciphertext)}- atomic_write_json(_live_encrypted_disk_cache_path(home_path), payload)+ atomic_write_json(_current_encrypted_disk_cache_path(home_path), payload)_STORE.disk.clear(home_path)except Exception:return@@ -157,7 +157,7 @@ def _read_encrypted_disk_cache(*, cache_key: _CacheKey, access_token: str, max_atry:from cryptography.hazmat.primitives.ciphers.aead import AESGCM- payload = json.loads(_live_encrypted_disk_cache_path(home_path).read_text(encoding="utf-8-sig"))+ payload = json.loads(_current_encrypted_disk_cache_path(home_path).read_text(encoding="utf-8-sig"))serialized_key = _cache_key_str(cache_key)if (not isinstance(payload, dict)or payload.get("version") != _ENCRYPTED_CACHE_VERSIONdiff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 9ac3b5c8717..ed6d22dbefc 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -28,7 +28,7 @@ from agent.provider_media import GENERATED_SUBDIRfrom hermes_cli.archive_safe import normalize_archive_partsfrom hermes_cli.backup_sqlite import _close_quietly, _safe_copy_dbfrom hermes_cli.config_backend import require_file_tooling, supports_file_tooling-from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, SECRET_CACHE_STORES, profile_root_entry+from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, SECRET_CACHE_FILES, profile_root_entryfrom hermes_cli.sizefmt import format_bytes as _format_sizefrom hermes_cli.backup_restore import (@@ -101,7 +101,7 @@ _EXCLUDED_ROOT_DIRS = LOCAL_RUNTIME_ROOT_DIRS | (PM_RUNTIME_ROOT_DIRS - {"cache"# Browser Use CLI profile dir (browser.backend: browser-use): Chromium user-data with Login Data / Cookies;# the secret caches and Photon sidecar token. Root-scoped like models/ — a skill's own browser_profiles/ is# user data. Backup-only: do not fold into LOCAL_RUNTIME_ROOT_DIRS (clone-all identity contract).-_EXCLUDED_BACKUP_ROOT_DIRS = frozenset({"browser_profiles", *SECRET_CACHE_STORES})+_EXCLUDED_BACKUP_ROOT_DIRS = frozenset({"browser_profiles", *SECRET_CACHE_FILES})# ``cache/`` at those same roots mixes regenerable state (model/plugin catalogs, stamps, browser# profiles with locked SQLite, tool-output spill) with durable artifacts nothing can rebuild: mediadiff --git a/hermes_cli/home_data_layout.py b/hermes_cli/home_data_layout.pyindex 52e6cc3a7eb..2ea56a1d9be 100644--- a/hermes_cli/home_data_layout.py+++ b/hermes_cli/home_data_layout.py@@ -6,13 +6,16 @@ from __future__ import annotationsPM_RUNTIME_ROOT_DIRS = frozenset({"installs", "tools", "cache"})# Bitwarden / 1Password secret-value caches and the Photon sidecar auth token, as POSIX paths relative to-# a home: at its top, where a sandbox can hide a file by path (a writable folder above a hidden file can be-# renamed), and at the cache/ and runtime/ paths earlier releases used, which the first read moves up.-# Credential stores for every guard that lists them; regenerated on use, so backups leave them out.-SECRET_CACHE_STORES = (- "bws_cache.json", "bws_cache.enc.json", "op_cache.json", "photon-sidecar.json",+# a home. They sit at its top, where a sandbox can hide a file by path (a writable folder above a hidden+# file can be renamed). Hermes regenerates them on use, so backups leave them out.+SECRET_CACHE_FILES = ("bws_cache.json", "bws_cache.enc.json", "op_cache.json", "photon-sidecar.json")+# Where earlier releases kept the same files, in folders the agent can write. Hermes deletes a copy+# there unread on first use.+LEGACY_SECRET_CACHE_PATHS = ("cache/bws_cache.json", "cache/bws_cache.enc.json", "cache/op_cache.json", "runtime/photon-sidecar.json",)+# Credential stores for every guard that lists them.+SECRET_CACHE_STORES = (*SECRET_CACHE_FILES, *LEGACY_SECRET_CACHE_PATHS)def profile_root_entry(parts: tuple[str, ...]) -> str | None:diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.pyindex d1fc06ad100..ac8ae3144f6 100644--- a/hermes_cli/web_routers/files.py+++ b/hermes_cli/web_routers/files.py@@ -28,6 +28,7 @@ from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResfrom hermes_cli import web_server_file_tickets as file_ticketsfrom hermes_cli._subprocess_compat import windows_hide_flags+from hermes_cli.home_data_layout import SECRET_CACHE_STORESfrom hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_accessfrom hermes_cli.staged_uploads import (ensure_profile_subdir, is_staged_upload, removed_on_failure, resolve_upload_home,@@ -82,8 +83,8 @@ _FS_READDIR_HIDDEN = {_SENSITIVE_MANAGED_FILE_BASENAMES = frozenset({"auth.json", "auth.lock", "credentials", "config.yaml", ".anthropic_oauth.json","google_token.json", "google_oauth_pending.json", "google_oauth.json",- "webhook_subscriptions.json", "bws_cache.json", "bws_cache.enc.json",- "op_cache.json", "photon-sidecar.json",+ "webhook_subscriptions.json",+ *(PurePosixPath(store).name for store in SECRET_CACHE_STORES), # secret caches, Photon sidecar token".git-credentials", # git's credential-store cache (file_safety blocks it too)})diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.pyindex f31677ace26..3642d7346b9 100644--- a/plugins/platforms/photon/adapter.py+++ b/plugins/platforms/photon/adapter.py@@ -45,7 +45,7 @@ from gateway.platforms.event import MessageEvent, MessageTypefrom gateway.platforms.helpers import compile_mention_patterns, strip_markdownfrom gateway.platforms.helpers import MessageDeduplicator, bounded_put, cancel_taskfrom gateway.platforms.send_targets import regex_stripped_parser-from utils import adopt_legacy_file, atomic_json_write+from utils import atomic_json_writefrom .auth import load_project_credentials# Sidecar dir resolution is lazy (never at import): it probes the filesystem and may@@ -114,22 +114,25 @@ def _legacy_runtime_record_path() -> Path:return path.parent / "runtime" / path.name-def _live_runtime_record_path() -> Path:- """The record path, after moving a record left at the legacy path (that path if the move fails)."""- return adopt_legacy_file(_runtime_record_path(), _legacy_runtime_record_path())+def _current_runtime_record_path() -> Path:+ """The record path. A record at the legacy path is deleted first without being read: the agent+ can write that folder."""+ with contextlib.suppress(OSError):+ _legacy_runtime_record_path().unlink()+ return _runtime_record_path()def _write_runtime_record(port: int, token: str, pid: int) -> None:"""Atomically persist ``{port, token, pid}`` 0600 from creation (best-effort)."""try:- atomic_json_write(_live_runtime_record_path(), {"port": port, "token": token, "pid": pid}, indent=None, mode=0o600)+ atomic_json_write(_current_runtime_record_path(), {"port": port, "token": token, "pid": pid}, indent=None, mode=0o600)except Exception as e:logger.warning("[photon] failed to write sidecar runtime record: %s", e)def _read_runtime_record() -> Optional[dict[str, Any]]:try:- raw = json.loads(_live_runtime_record_path().read_text(encoding="utf-8-sig"))+ raw = json.loads(_current_runtime_record_path().read_text(encoding="utf-8-sig"))except (OSError, ValueError):return Nonereturn raw if isinstance(raw, dict) else Nonediff --git a/tests/agent/test_secret_cache_location.py b/tests/agent/test_secret_cache_location.pyindex 1a6340e2d82..ad913ae5ba9 100644--- a/tests/agent/test_secret_cache_location.py+++ b/tests/agent/test_secret_cache_location.py@@ -2,15 +2,14 @@A sandbox that hides credential stores by path can hide a file safely only at the top of theprofile home: a writable folder above a hidden file can be renamed to expose it, and the-sandboxed backend has to write ``cache/``. Earlier releases kept these caches in ``cache/``; the-first read moves such a copy to the new location, and every path keeps a single live copy.+sandboxed backend has to write ``cache/``. Earlier releases kept these caches in ``cache/``; Hermes+deletes such a copy on first use without reading it, since the agent could have written it."""from __future__ import annotationsimport jsonimport os-import statimport timefrom pathlib import Path@@ -47,13 +46,6 @@ def _previous(home: Path, name: str) -> Path:return path-def _refuse_rename(monkeypatch):- def refuse(*_args, **_kwargs):- raise PermissionError(13, "Access is denied")-- monkeypatch.setattr(os, "rename", refuse)--def test_caches_live_at_the_top_of_the_profile_home(home):assert bw._disk_cache_path(home) == home / "bws_cache.json"assert bw._encrypted_disk_cache_path(home) == home / "bws_cache.enc.json"@@ -68,31 +60,14 @@ def test_a_write_lands_in_the_profile_home(home):assert not (home / "cache").exists()-def test_the_first_read_moves_a_cache_from_the_previous_location(home):+def test_the_first_read_deletes_a_previous_copy_unread(home):cache = DiskCache("probe.json", key_serializer=str)previous = _previous(home, "probe.json")previous.write_text(_payload("k", {"A": "b"}), encoding="utf-8")- entry = cache.read("k", 60, home)-- assert entry is not None and entry.secrets == {"A": "b"}- assert (home / "probe.json").is_file()+ assert cache.read("k", 60, home) is Noneassert not previous.exists()--[email protected]("posix") # POSIX permission bits-def test_the_move_keeps_the_file_mode(home):- cache = DiskCache("probe.json", key_serializer=str)- previous = _previous(home, "probe.json")- previous.write_text(_payload("k", {"A": "b"}), encoding="utf-8")- previous.chmod(0o600)- old_umask = os.umask(0o022) # a copy instead of a rename would come out 0o644- try:- assert cache.read("k", 60, home) is not None- finally:- os.umask(old_umask)-- assert stat.S_IMODE((home / "probe.json").stat().st_mode) == 0o600+ assert not (home / "probe.json").exists()def test_a_current_cache_wins_and_the_previous_copy_is_removed(home):@@ -107,37 +82,43 @@ def test_a_current_cache_wins_and_the_previous_copy_is_removed(home):assert not previous.exists()-def test_a_failed_move_keeps_working_from_the_previous_copy(home, monkeypatch):+def test_a_write_deletes_a_previous_copy(home):cache = DiskCache("probe.json", key_serializer=str)previous = _previous(home, "probe.json")- previous.write_text(_payload("k", {"A": "b"}), encoding="utf-8")- _refuse_rename(monkeypatch)-- entry = cache.read("k", 60, home)- assert entry is not None and entry.secrets == {"A": "b"}- assert previous.is_file()+ previous.write_text(_payload("k", {"A": "previous"}), encoding="utf-8")cache.write("k", CachedFetch(secrets={"A": "c"}, fetched_at=time.time()), 60, home)- copies = [p for p in (home / "probe.json", previous) if p.exists()]- assert len(copies) == 1, copies- assert json.loads(copies[0].read_text(encoding="utf-8"))["secrets"] == {"A": "c"}+ assert not previous.exists()+ assert json.loads((home / "probe.json").read_text(encoding="utf-8"))["secrets"] == {"A": "c"}-def test_a_move_another_process_finished_reads_the_new_location(home, monkeypatch):++def test_a_previous_symlink_is_removed_and_its_target_kept(home):cache = DiskCache("probe.json", key_serializer=str)+ target = home / "workspace" / "leak.json"+ target.parent.mkdir()+ target.write_text("{}", encoding="utf-8")previous = _previous(home, "probe.json")- previous.write_text(_payload("k", {"A": "b"}), encoding="utf-8")- real_rename = os.rename+ try:+ previous.symlink_to(target)+ except OSError:+ pytest.skip("creating a symlink needs a privilege this host lacks")- def raced(src, dst):- real_rename(src, dst) # a concurrent reader moved it first- raise FileNotFoundError(2, "The system cannot find the file specified")+ cache.write("k", CachedFetch(secrets={"A": "c"}, fetched_at=time.time()), 60, home)- monkeypatch.setattr(os, "rename", raced)+ assert not os.path.lexists(previous)+ assert target.read_text(encoding="utf-8") == "{}"+ assert json.loads((home / "probe.json").read_text(encoding="utf-8"))["secrets"] == {"A": "c"}- entry = cache.read("k", 60, home)- assert entry is not None and entry.secrets == {"A": "b"}+def test_a_previous_directory_is_left_alone(home):+ cache = DiskCache("probe.json", key_serializer=str)+ (_previous(home, "probe.json") / "inner").mkdir(parents=True)++ cache.write("k", CachedFetch(secrets={"A": "c"}, fetched_at=time.time()), 60, home)++ assert (home / "cache" / "probe.json" / "inner").is_dir()+ assert json.loads((home / "probe.json").read_text(encoding="utf-8"))["secrets"] == {"A": "c"}def test_clear_removes_both_locations(home):@@ -152,16 +133,14 @@ def test_clear_removes_both_locations(home):assert not previous.exists()-def test_onepassword_cache_moves_from_the_previous_location(home):+def test_onepassword_cache_deletes_the_previous_copy_unread(home):key = ("auth-fp", "account", str(home), "refs-fp")previous = _previous(home, "op_cache.json")previous.write_text(_payload(op._disk_key_str(key), {"OP_KEY": "v"}), encoding="utf-8")- entry = op._STORE.disk.read(key, 60, home)-- assert entry is not None and entry.secrets == {"OP_KEY": "v"}- assert (home / "op_cache.json").is_file()+ assert op._STORE.disk.read(key, 60, home) is Noneassert not previous.exists()+ assert not (home / "op_cache.json").exists()def _seed_encrypted(home: Path) -> tuple[tuple[str, str, str], Path]:@@ -175,26 +154,14 @@ def _seed_encrypted(home: Path) -> tuple[tuple[str, str, str], Path]:return cache_key, previous-def test_bitwarden_encrypted_cache_moves_from_the_previous_location(home):+def test_bitwarden_encrypted_cache_deletes_the_previous_copy_unread(home):cache_key, previous = _seed_encrypted(home)entry = bw._read_encrypted_disk_cache(cache_key=cache_key, access_token="0.t",max_age_seconds=3600, home_path=home)- assert entry is not None and entry.secrets == {"K": "v"}- assert (home / "bws_cache.enc.json").is_file()+ assert entry is Noneassert not previous.exists()---def test_bitwarden_encrypted_cache_failed_move_reads_the_previous_copy(home, monkeypatch):- cache_key, previous = _seed_encrypted(home)- _refuse_rename(monkeypatch)-- entry = bw._read_encrypted_disk_cache(cache_key=cache_key, access_token="0.t",- max_age_seconds=3600, home_path=home)-- assert entry is not None and entry.secrets == {"K": "v"}- assert previous.is_file()assert not (home / "bws_cache.enc.json").exists()diff --git a/tests/hermes_cli/test_credential_store_lists.py b/tests/hermes_cli/test_credential_store_lists.pyindex ebad6e3de7c..b592b2f9a69 100644--- a/tests/hermes_cli/test_credential_store_lists.py+++ b/tests/hermes_cli/test_credential_store_lists.py@@ -14,7 +14,7 @@ from pathlib import Pathimport pytest-# Where earlier releases kept the same stores; the first read moves them to the profile home.+# Where earlier releases kept the same stores; Hermes deletes a copy there unread.PREVIOUS_LOCATIONS = ("cache/bws_cache.json", "cache/bws_cache.enc.json", "cache/op_cache.json", "runtime/photon-sidecar.json",)@@ -53,6 +53,14 @@ def test_the_stores_sit_at_the_top_of_the_profile_home(home):assert _current(home) == ("bws_cache.json", "bws_cache.enc.json", "op_cache.json", "photon-sidecar.json")+def test_the_shared_list_names_both_locations(home):+ from hermes_cli.home_data_layout import LEGACY_SECRET_CACHE_PATHS, SECRET_CACHE_FILES, SECRET_CACHE_STORES++ assert SECRET_CACHE_FILES == _current(home)+ assert LEGACY_SECRET_CACHE_PATHS == PREVIOUS_LOCATIONS+ assert SECRET_CACHE_STORES == (*SECRET_CACHE_FILES, *LEGACY_SECRET_CACHE_PATHS)++def test_profile_credential_paths_list_both_locations(home):from hermes_cli.profiles import PROFILE_CREDENTIAL_PATHS, profile_path_is_privatediff --git a/tests/plugins/platforms/photon/test_runtime_record.py b/tests/plugins/platforms/photon/test_runtime_record.pyindex 6cd55a8ca53..dd4c5698b64 100644--- a/tests/plugins/platforms/photon/test_runtime_record.py+++ b/tests/plugins/platforms/photon/test_runtime_record.py@@ -75,27 +75,30 @@ def test_record_lives_at_the_top_of_the_profile_home() -> None:assert photon_adapter._runtime_record_path() == get_hermes_home() / "photon-sidecar.json"-def test_read_moves_a_record_from_the_previous_location(record_path: Path) -> None:- data = {"port": 8789, "token": "tok", "pid": 4242}- previous = _previous_record(record_path, data)+def test_read_deletes_a_previous_record_unread(record_path: Path) -> None:+ previous = _previous_record(record_path, {"port": 8789, "token": "tok", "pid": 4242})- assert photon_adapter._read_runtime_record() == data- assert json.loads(record_path.read_text(encoding="utf-8")) == data+ assert photon_adapter._read_runtime_record() is Noneassert not previous.exists()+ assert not record_path.exists()-def test_a_failed_move_reads_the_previous_record(record_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- data = {"port": 8789, "token": "tok", "pid": 4242}- previous = _previous_record(record_path, data)-- def refuse(*_args: Any, **_kwargs: Any) -> None:- raise PermissionError(13, "Access is denied")+def test_a_previous_symlink_is_removed_and_its_target_kept(record_path: Path) -> None:+ target = record_path.parent / "workspace" / "leak.json"+ target.parent.mkdir()+ target.write_text("{}", encoding="utf-8")+ previous = record_path.parent / "runtime" / record_path.name+ previous.parent.mkdir()+ try:+ previous.symlink_to(target)+ except OSError:+ pytest.skip("creating a symlink needs a privilege this host lacks")- monkeypatch.setattr(os, "rename", refuse)+ photon_adapter._write_runtime_record(8789, "new", 4242)- assert photon_adapter._read_runtime_record() == data- assert previous.exists()- assert not record_path.exists()+ assert not os.path.lexists(previous)+ assert target.read_text(encoding="utf-8") == "{}"+ assert json.loads(record_path.read_text(encoding="utf-8"))["token"] == "new"def test_write_and_delete_leave_no_previous_record(record_path: Path) -> None:diff --git a/utils.py b/utils.pyindex 2912a6b3fcc..8d3193114fa 100644--- a/utils.py+++ b/utils.py@@ -341,28 +341,6 @@ def unlink_files_older_than(directory: str | Path, pattern: str, max_age_secondsreturn removed-def adopt_legacy_file(path: str | Path, legacy: str | Path) -> Path:- """Move the file at *legacy* (where an earlier release kept it) to *path*; return the path to use.-- The move is a rename, so the file keeps its permissions. When *path* already exists the legacy- copy is a stale duplicate and is removed. When the move fails *legacy* is returned, so the caller- keeps working from the old copy and never holds two live copies. Never raises.- """- path, legacy = Path(path), Path(legacy)- if not os.path.lexists(legacy):- return path- if os.path.lexists(path):- with suppress(OSError):- legacy.unlink()- return path- try:- os.rename(legacy, path)- except OSError:- if os.path.lexists(legacy): # still there; gone means another process moved it first- return legacy- return path--def rmtree_readonly(path: str | Path, *, ignore_errors: bool = False) -> None:"""``shutil.rmtree`` that can also delete read-only trees.