"""Atomic, Windows-safe file writes. A leaf module -- imports nothing from ``afk_developer`` itself, so every other module can import it with zero circular-import risk (mirrors the constraint already documented for ``campaign_runner.py``'s function-body- local imports of ``cli.py`` helpers). ``atomic_write_text`` is the one retry-hardened NamedTemporaryFile-then- replace pattern that used to be hand-duplicated three times: ``cli.py``'s ``_save_plan`` (the only one with the Windows ``PermissionError`` retry/ backoff), ``campaign_store.py``'s ``CampaignStore.save``, and ``config.py``'s ``save_user_config`` (the latter two used a bare ``.replace()``). Session 2 dedup (docs/refactor-handoffs/02-dedup.md Task 3.1): the campaign/config saves deliberately GAIN the retry protection they were missing -- a real, transient ``PermissionError: [WinError 5]`` has been observed on this machine (antivirus/indexer/backup agent briefly holding a just-written temp file open), and this is the one behavior change the dedup pass allows outside Task 1's retry unification. """ from __future__ import annotations import time from pathlib import Path from tempfile import NamedTemporaryFile def atomic_write_text(path: Path, content: str) -> None: """Atomically write ``content`` to ``path``, creating parent dirs first. Writes to a sibling temp file, then replaces ``path`` with it, so readers never see a partially-written file and a crash mid-write leaves the prior contents of ``path`` untouched. """ path.parent.mkdir(parents=True, exist_ok=True) with NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as handle: handle.write(content) temporary = Path(handle.name) _replace_with_retry(temporary, path) def _replace_with_retry( source: Path, target: Path, *, attempts: int = 5, delay_seconds: float = 0.1 ) -> None: """Replace ``target`` with ``source``, retrying on Windows's transient ``PermissionError: [WinError 5] Access is denied``. Unlike POSIX rename, Windows can briefly deny a rename/replace if another process (antivirus real-time scanning, a search indexer, a backup agent) has the just-written temp file open for a moment. This is reliably transient, not a real conflict -- a short retry loop resolves it instead of crashing the whole run on an unhandled PermissionError. """ last_error: PermissionError | None = None for attempt in range(attempts): try: source.replace(target) return except PermissionError as exc: last_error = exc if attempt < attempts - 1: time.sleep(delay_seconds) if last_error is not None: raise last_error