diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 5c4c901d..cdc7a1fd 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -47,6 +47,7 @@ from __future__ import annotations import argparse import base64 import datetime as dt +import errno from email.utils import parsedate_to_datetime import fcntl import hashlib @@ -200,6 +201,35 @@ def sync_codex_home(home: Path, *, create: bool = False) -> None: _sync_codex_home(home) +def _copy_across_devices(entry: Path, target: Path) -> None: + import ctypes + + # The private staging directory is also excluded from future mirroring + # by shared() if the process is interrupted before cleanup. + with tempfile.TemporaryDirectory(dir=target.parent, prefix=".codex-sync-", suffix=".lock") as directory: + staged = Path(directory) / entry.name + is_directory = entry.is_dir() + if is_directory: + shutil.copytree(entry, staged, symlinks=True) + else: + shutil.copy2(entry, staged, follow_symlinks=False) + + # Linux/WSL renameat2 with RENAME_NOREPLACE publishes the complete + # entry in one operation without replacing a competing destination. + rename = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None) + if rename is None: + raise OSError(errno.ENOSYS, "Atomic cross-device publication is unavailable", target) + if rename(-100, os.fsencode(staged), -100, os.fsencode(target), 1): + error = ctypes.get_errno() + if error == errno.EEXIST: + return + raise OSError(error, os.strerror(error), target) + if is_directory: + shutil.rmtree(entry) + else: + entry.unlink() + + def _sync_codex_home(home: Path) -> None: """Mirror shared Codex files while holding the home lock.""" for entry in home.iterdir(): @@ -210,6 +240,10 @@ def _sync_codex_home(home: Path) -> None: os.rename(entry, target) except FileNotFoundError: pass + except OSError as exc: + if exc.errno != errno.EXDEV: + raise + _copy_across_devices(entry, target) for src in CODEX_MAIN.iterdir(): dst = home / src.name if shared(src) and not dst.exists() and not dst.is_symlink(): diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index c161c052..cba117bd 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -2,6 +2,7 @@ import importlib.machinery import importlib.util import json +import tempfile from concurrent.futures import ThreadPoolExecutor from io import BytesIO from pathlib import Path @@ -593,3 +594,27 @@ def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): with pytest.raises(OSError), helper._locked(".codex-sync.lock"): pytest.fail("redirected lock opened") assert lock.read_text() == "preserve" + + +@pytest.mark.parametrize("outcome", ["published", "copy failed"]) +def test_account_env_moves_shared_entry_across_devices(helper, monkeypatch, outcome): + if not Path("/dev/shm").is_dir() or Path("/dev/shm").stat().st_dev == helper.STATE.stat().st_dev: + pytest.skip("requires two filesystems") + entry = helper.codex_home("extra") / "session-index.jsonl" + helper.write_private(entry, "original") + helper.write_private(entry.with_name("auth.json"), "{}") + copy = helper.shutil.copy2 + with tempfile.TemporaryDirectory(dir="/dev/shm") as main: + monkeypatch.setattr(helper, "CODEX_MAIN", Path(main)) + def stage(src, dst, **kwargs): + copy(src, dst, **kwargs) + if outcome == "copy failed": + raise OSError("copy interrupted") + monkeypatch.setattr(helper.shutil, "copy2", stage) + if outcome == "copy failed": + with pytest.raises(OSError, match="copy interrupted"): + helper.account_env("codex", "extra") + else: + helper.account_env("codex", "extra") + assert entry.read_text() == "original" and entry.is_symlink() == (outcome == "published") + assert list(Path(main).iterdir()) == ([] if outcome == "copy failed" else [Path(main) / entry.name])