Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
perf(runtime): persist the latest-version cache across processes (#1609)
Call White76d63bd11cf0
diff --git a/config/atomic_io.py b/config/atomic_io.pynew file mode 100644index 000000000..df8df18e4--- /dev/null+++ b/config/atomic_io.py@@ -0,0 +1,118 @@+"""One owner for replacing an agent-owned state document atomically.++Nineteen modules used to hand-roll "write a temp file, then ``os.replace`` it+over the destination", and no two of them hand-rolled it quite the same way.+Most of the variation was harmless drift — some fsynced the payload, most did+not, almost none fsynced the parent directory — but two call sites had shipped+a real defect nobody had noticed, because each one only ever had to satisfy its+own test:++* ``core/managed_runtime`` and ``vibe/codex_config`` both derived a fixed+ ``<name>.tmp`` path, so two concurrent writers share one temp file and one+ can ``os.replace`` the other's half-flushed bytes onto the destination.+* ``vibe/codex_config`` wrote that temp file under the ambient umask and+ tightened the *destination* after the rename, leaving a window in which a+ Codex auth file is world-readable — permanent if the process dies in between.++So this module owns the swap and the callers own the bytes. Serialization+formats stay where they are (``indent=2`` for human-read state, compact for+machine-read projections, ``sort_keys`` for diffable manifests): those are real+per-file decisions, unlike the durability and permission gaps above.++**Scope.** This owns replacing one *whole* state document that Avibe itself+owns. It is deliberately not the owner of every rename in the repository, and+several callers stay outside it on purpose: a compare-and-swap that re-reads+before replacing (``config/v2_config``), an editor writing *user* files whose+existing mode and mtime must survive (``core/file_browser_service``), a+database swap that must move sidecars with the file (``storage/backups``), and+anything reserving a temp *name* without writing content (``vibe/screenshot``).+Reach for this when the write is "these bytes, entirely, or nothing".++The guarantees, for every caller:++* A reader never observes a partial write. The payload lands in a temp file+ that is fsynced before it is renamed over the destination.+* Two writers never collide. ``tempfile.mkstemp`` allocates a distinct temp+ name per call, so overlapping writers publish whole payloads rather than+ each other's fragments.+* A failed write never leaves a temp file behind, and never truncates the+ destination — the old contents survive until the rename succeeds.+* The replacement is owner-private (0600) from the moment it exists, because+ ``mkstemp`` creates it that way and the rename preserves it. There is no+ window in which a file holding agent credentials is world-readable.++Every path written through here is agent-owned or user-owned local state, so+0600 is the right mode for all of them and this module does not take a+parameter for it. A caller that genuinely needs a looser mode should say so+explicitly rather than inherit one by accident.+"""++from __future__ import annotations++import os+import tempfile+from pathlib import Path++__all__ = ["write_atomic"]+++def _fsync_directory(path: Path) -> None:+ """Best-effort durability for a replaced directory entry."""++ flags = getattr(os, "O_DIRECTORY", None)+ if flags is None:+ return+ try:+ descriptor = os.open(path, flags)+ except OSError:+ return+ try:+ os.fsync(descriptor)+ except OSError:+ pass+ finally:+ os.close(descriptor)+++def write_atomic(path: Path, data: str | bytes, *, follow_symlinks: bool = False) -> None:+ """Replace *path* with *data* atomically, creating parent directories.++ ``follow_symlinks`` writes *through* a symlink to its real target instead of+ replacing the link with a regular file. Needed where a user may have linked+ a file into a shared dotfiles repository (``~/.claude/CLAUDE.md`` ->+ ``~/dotfiles/CLAUDE.md``): replacing the link would silently break that+ setup. Off by default, because for state this process owns, resolving a+ symlink an attacker planted is the wrong answer.++ Raises ``OSError`` if the write fails; the destination is left untouched.+ """++ target = Path(os.path.realpath(path)) if follow_symlinks else Path(path)+ target.parent.mkdir(parents=True, exist_ok=True)+ payload = data.encode("utf-8") if isinstance(data, str) else data++ # mkstemp creates the file 0600 without relying on Unix-only APIs, and the+ # rename carries that mode onto the destination.+ descriptor, temporary_name = tempfile.mkstemp(+ prefix=f".{target.name}.",+ suffix=".tmp",+ dir=str(target.parent),+ )+ unpublished: str | None = temporary_name+ try:+ with os.fdopen(descriptor, "wb") as handle:+ descriptor = -1+ handle.write(payload)+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary_name, target)+ unpublished = None+ _fsync_directory(target.parent)+ finally:+ if descriptor >= 0:+ os.close(descriptor)+ if unpublished is not None:+ try:+ os.unlink(unpublished)+ except OSError: # pragma: no cover - best effort cleanup+ passdiff --git a/config/discovered_chats.py b/config/discovered_chats.pyindex b9c0633e4..35a1b7a69 100644--- a/config/discovered_chats.py+++ b/config/discovered_chats.py@@ -2,7 +2,6 @@ from __future__ import annotationsimport jsonimport logging-import tempfileimport threadingfrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timezone@@ -10,6 +9,7 @@ from pathlib import Pathfrom typing import Dict, Optionalfrom config import paths+from config.atomic_io import write_atomiclogger = logging.getLogger(__name__)@@ -125,17 +125,7 @@ class DiscoveredChatsStore:for platform, chats in self.state.chats.items()},}- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.storage_path.parent,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- handle.write("\n")- tmp_path = Path(handle.name)- tmp_path.replace(self.storage_path)+ write_atomic(self.storage_path, json.dumps(payload, indent=2) + "\n")try:self._file_mtime = self.storage_path.stat().st_mtimeexcept FileNotFoundError:diff --git a/config/v2_config.py b/config/v2_config.pyindex 733007a95..a5f286900 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -28,6 +28,7 @@ from typing import (from urllib.parse import parse_qsl, urlsplit, urlunsplitfrom config import paths+from config.atomic_io import write_atomicfrom config.platform_registry import (WORKBENCH_PLATFORM_ID,get_platform_descriptor,@@ -67,53 +68,6 @@ def _path_file_lock(lock_path: Path, *, timeout_seconds: float | None):return MigrationFileLock(lock_path, timeout_seconds=timeout_seconds)-def _fsync_directory(path: Path) -> None:- """Best-effort durability for a replaced directory entry."""-- flags = getattr(os, "O_DIRECTORY", None)- if flags is None:- return- try:- descriptor = os.open(path, flags)- except OSError:- return- try:- os.fsync(descriptor)- except OSError:- pass- finally:- os.close(descriptor)---def _atomic_write_text(path: Path, content: str) -> None:- """Replace one text file durably without retaining a failed temp file."""-- descriptor, temp_name = tempfile.mkstemp(- prefix=f".{path.name}.",- suffix=".tmp",- dir=path.parent,- text=True,- )- temporary: Path | None = Path(temp_name)- try:- with os.fdopen(descriptor, "w", encoding="utf-8") as handle:- descriptor = -1- handle.write(content)- handle.flush()- os.fsync(handle.fileno())- os.replace(temporary, path)- temporary = None- _fsync_directory(path.parent)- finally:- if descriptor >= 0:- os.close(descriptor)- if temporary is not None:- try:- temporary.unlink()- except FileNotFoundError:- pass--@contextmanagerdef _memory_config_transaction(config_path: Path) -> Iterator[None]:"""Narrow cross-process exclusive section for Memory candidate+marker writes.@@ -1505,7 +1459,7 @@ def _write_config_payload(path: Path, payload: dict) -> None:content = json.dumps(payload, indent=2)path.parent.mkdir(parents=True, exist_ok=True)with config_file_lock(path):- _atomic_write_text(path, content)+ write_atomic(path, content)def _write_config_payload_if_unchanged(diff --git a/core/handlers/model_hub/state_file.py b/core/handlers/model_hub/state_file.pyindex b3cd7db44..0b0dd7613 100644--- a/core/handlers/model_hub/state_file.py+++ b/core/handlers/model_hub/state_file.py@@ -2,57 +2,33 @@Five collections persist under the state directory — resolution events, sourceprovenance, credential revocations, OAuth flow bindings, token usage — and every-one of them wants the same three things: the parent directory to exist, one-compact credential-free JSON encoding, and a replacement that either lands whole-or leaves the previous document exactly as it was.--Each of them used to spell that out for itself, in the same seven lines. Which is-how one temp file that outlived a failed write was really five latent orphans in-one directory: the writers deliberately swallow ``OSError`` so metering and event-recording cannot be broken by a full disk, and nothing downstream would ever-notice the residue. A bounded ledger whose state directory grows without bound is-not bounded.+one of them wants the same compact credential-free JSON encoding. That encoding+is what this module still owns; the atomic replacement underneath it belongs to+``config.atomic_io``, which every other state writer in Avibe shares.++Each of the five used to spell the whole thing out for itself, in the same seven+lines. Which is how one temp file that outlived a failed write was really five+latent orphans in one directory: the writers deliberately swallow ``OSError`` so+metering and event recording cannot be broken by a full disk, and nothing+downstream would ever notice the residue. A bounded ledger whose state directory+grows without bound is not bounded."""from __future__ import annotationsimport json-import os-import tempfile-from contextlib import suppressfrom pathlib import Pathfrom typing import Any-STATE_FILE_MODE = 0o600+from config.atomic_io import write_atomicdef write_state_document(path: Path, payload: Any) -> None:"""Replace ``path`` with ``payload`` as one compact owner-only JSON document.- The temporary file is removed unless the replacement itself succeeded, so an- encoding, ``fsync``, ``chmod``, or rename that raises costs the caller the- write it was already prepared to lose and nothing else.+ Compact and ``ensure_ascii=False``: these documents are machine-read ledgers+ that routinely carry non-ASCII model and source names, so escaping them buys+ nothing and costs bytes on every append."""- path.parent.mkdir(parents=True, exist_ok=True)- content = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))- handle = tempfile.NamedTemporaryFile(- "w",- encoding="utf-8",- dir=path.parent,- delete=False,- )- temporary = Path(handle.name)- replaced = False- try:- with handle:- handle.write(content)- handle.flush()- os.fsync(handle.fileno())- os.chmod(temporary, STATE_FILE_MODE)- os.replace(temporary, path)- replaced = True- finally:- if not replaced:- with suppress(OSError):- temporary.unlink()+ write_atomic(path, json.dumps(payload, ensure_ascii=False, separators=(",", ":")))diff --git a/core/internal_server.py b/core/internal_server.pyindex 909e86123..8089d7f51 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -36,7 +36,6 @@ import osimport reimport socketimport stat-import tempfileimport timefrom dataclasses import replacefrom pathlib import Path@@ -48,6 +47,7 @@ from fastapi.responses import JSONResponse, StreamingResponsefrom sqlalchemy.exc import IntegrityErrorfrom config import paths+from config.atomic_io import write_atomicfrom core.memory.blocking import run_blockingfrom core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULEDfrom modules.im.base import MessageContext@@ -2300,38 +2300,22 @@ def _write_internal_server_status() -> None:"""Persist internal-server lifecycle state for the out-of-process CLI."""- target = paths.get_internal_server_status_path()+ payload: dict[str, str] = {+ "state": state,+ "updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ }+ if error is not None:+ payload["error"] = error+ if detail is not None:+ payload["detail"] = detailtry:- target.parent.mkdir(parents=True, exist_ok=True)- payload = {- "state": state,- "updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),- }- if error is not None:- payload["error"] = error- if detail is not None:- payload["detail"] = detail- file_descriptor, temporary_name = tempfile.mkstemp(- dir=target.parent,- prefix=f".{target.name}.",- suffix=".tmp",+ # Compact: the CLI polls this, nobody reads it by eye. Losing the write is+ # survivable — the status file is a courtesy to an out-of-process reader,+ # not something the server's own lifecycle depends on.+ write_atomic(+ paths.get_internal_server_status_path(),+ json.dumps(payload, separators=(",", ":")),)- temporary = Path(temporary_name)- try:- if hasattr(os, "fchmod"):- os.fchmod(file_descriptor, 0o600)- with os.fdopen(file_descriptor, "w", encoding="utf-8") as stream:- json.dump(payload, stream, separators=(",", ":"))- file_descriptor = -1- os.replace(temporary, target)- except Exception:- if file_descriptor >= 0:- try:- os.close(file_descriptor)- except OSError:- pass- temporary.unlink(missing_ok=True)- raiseexcept OSError:logger.warning("could not persist internal dispatch server status", exc_info=True)diff --git a/core/latest_version_cache.py b/core/latest_version_cache.pynew file mode 100644index 000000000..7bd5855af--- /dev/null+++ b/core/latest_version_cache.py@@ -0,0 +1,224 @@+"""One owner for "what is the newest published version of X", cached on disk.++The answer used to live only in a module-level dict, which is right for the+long-running service and useless for the CLI: ``vibe runtime prepare`` is a+fresh process that asks GitHub for askill's newest release, exits, and throws+the answer away. Install, upgrade, every regression sync, and every tenant+update pay that probe again — and they pay it against the unauthenticated+GitHub budget of 60 requests per hour per IP, shared with the opencode probe+that reads the same cache.++Exhausting that budget is not a slow path, it is a wrong one: a 403 makes the+latest lookup fail, prepare cannot establish currency, and it falls back to+reinstalling askill — about 30 seconds of network to land the version already on+disk. So persisting the answer across processes matters more for the failures it+prevents than for the round trip it skips.++The cache is two tiers holding different things. The file tier holds *answers*,+so a cold process inherits what a previous one paid GitHub for. A failed probe+stops at the memory tier, which is the tier that needs it: a long-running+service polling a dead registry should back off, a fresh CLI process has nothing+to back off from.++Keeping failures off disk is also what removes the interesting race rather than+narrowing it. Two processes missing the same name both probe, outside any+cross-process lock, and no check-then-write can stop a slower failure from+landing on a fresh success — a guard only shrinks the window. A failure that+never reaches the file cannot overwrite anything, so every remaining+read-modify-write race is success-over-success, where the loser costs one extra+probe.++Inheriting a failure was never worth that window anyway: it does not avoid the+fallback it looks like it avoids. A process reading a cached ``None`` reports+``latest_unavailable`` and reinstalls askill; a process that re-probes might find+the blip over instead. Persisting the failure turns "maybe" into "certainly+reinstall" to save one HTTP request against a budget that, in the only case this+arises, is already exhausted.++Nothing here is authoritative. Every entry is a best-effort answer with an+expiry, and a caller that reads a stale or absent one gets the same behaviour it+had before this file existed: it probes.+"""++from __future__ import annotations++import json+import logging+import math+import threading+import time+from pathlib import Path+from typing import Any, Callable, NamedTuple++from config import paths+from config.atomic_io import write_atomic++logger = logging.getLogger(__name__)++__all__ = ["cache_path", "cached_latest"]++#: Bumped when the on-disk shape changes. A file written by a newer Avibe is+#: ignored rather than guessed at, and the next write replaces it — this is a+#: cache, so discarding it costs one probe and never a correctness problem.+SCHEMA_VERSION = 1++SUCCESS_TTL_SECONDS = 3600.0+#: Governs the memory tier only. A failed lookup (network down, registry hiccup,+#: rate limit) re-probes sooner so a transient outage doesn't pin "—" for the+#: full hour, and never outlives the process that had the bad luck.+FAILURE_TTL_SECONDS = 120.0+++class _Entry(NamedTuple):+ at: float+ value: str | None++ def is_live(self, now: float) -> bool:+ age = now - self.at+ if age < 0:+ # A timestamp from the future is a clock that moved, not a fresh+ # answer. Treating it as live would pin the entry until the clock+ # caught up, which for a backwards system-clock step is unbounded.+ return False+ return age < (SUCCESS_TTL_SECONDS if self.value else FAILURE_TTL_SECONDS)+++_LOCK = threading.Lock()+_MEMORY: dict[str, _Entry] = {}+++def cache_path() -> Path:+ return paths.get_state_dir() / "latest_versions.json"+++def _entry_from(raw: Any) -> _Entry | None:+ """Turn one untrusted mapping into an answer, or into nothing. Never raises.++ The guard is the boundary, not a list of the ways parsing has gone wrong so+ far. Two review rounds each supplied the next member of such a list — a+ non-UTF-8 file raising ``UnicodeDecodeError`` where only ``JSONDecodeError``+ was expected, then ``float(10**400)`` raising ``OverflowError``, which is an+ ``ArithmeticError`` and so was outside the widened ``ValueError`` too. A+ third enumeration would predict a fourth round.++ So this function owns the whole conversion, and its contract is a property:+ whatever the file says, the caller gets an ``_Entry`` it can use or ``None``.+ A field check added later inherits that, instead of needing its own+ ``except``.++ The explicit checks above the guard are still worth their lines, because+ they reject values that do *not* raise: ``inf`` and ``NaN`` survive a JSON+ round trip, compare false against every TTL, and would then be written back+ out as the non-standard ``Infinity``/``NaN`` tokens. And a null value is not+ something this version writes, so it is not something it trusts — corruption+ must not pin ``latest_unavailable`` on every cold process.+ """++ try:+ if not isinstance(raw, dict):+ return None+ at = raw.get("at")+ value = raw.get("value")+ if isinstance(at, bool) or not isinstance(at, (int, float)):+ return None+ if not isinstance(value, str) or not value:+ return None+ at = float(at)+ if not math.isfinite(at):+ return None+ return _Entry(at, value)+ except Exception as exc:+ logger.debug("Latest-version cache entry unusable: %s", exc)+ return None+++def _read_file() -> dict[str, _Entry]:+ """Load the persisted entries, discarding anything we cannot trust.++ A cache file is written by whichever Avibe process got there first, which+ may be an older or newer build, and may have died mid-write on a machine+ without atomic renames. Every failure mode collapses to the same answer:+ fewer entries, one more probe — per entry, so one unreadable name never+ costs its neighbours their answers.+ """++ try:+ raw = json.loads(cache_path().read_text(encoding="utf-8"))+ except FileNotFoundError:+ return {}+ except Exception as exc:+ logger.debug("Latest-version cache unreadable: %s", exc)+ return {}+ if not isinstance(raw, dict) or raw.get("schema_version") != SCHEMA_VERSION:+ return {}+ entries = raw.get("entries")+ if not isinstance(entries, dict):+ return {}++ out: dict[str, _Entry] = {}+ for name, entry in entries.items():+ if not isinstance(name, str):+ continue+ parsed = _entry_from(entry)+ if parsed is not None:+ out[name] = parsed+ return out+++def _persist(name: str, entry: _Entry) -> None:+ """Write *entry* through to disk, leaving the other names alone.++ A failed probe stops here, at the one place that can enforce it: whatever a+ caller hands over, only answers reach the file. That is what makes the+ same-name race disappear instead of narrow (see the module docstring), and+ it is not the caller's rule to remember.++ What remains is a read-modify-write with no cross-process lock, so two+ processes publishing two *different* dependencies at the same instant can+ drop one of the two entries. That costs one extra probe on the next run,+ which is cheaper than a lock file every CLI invocation would have to+ acquire — and with failures excluded, the same-name collision is now+ success-over-success, where either winner is a correct answer.+ """++ if entry.value is None:+ return+ persisted = _read_file()+ persisted[name] = entry+ payload = {+ "schema_version": SCHEMA_VERSION,+ "entries": {key: {"at": item.at, "value": item.value} for key, item in persisted.items()},+ }+ try:+ write_atomic(cache_path(), json.dumps(payload, indent=2) + "\n")+ except OSError as exc:+ # A read-only or full state directory must not break a version lookup;+ # the caller still has its answer, it just won't outlive this process.+ logger.debug("Latest-version cache not persisted: %s", exc)+++def cached_latest(name: str, fetch: Callable[[], str | None]) -> str | None:+ """Return the newest published version of *name*, probing only when stale.++ *fetch* is the upstream probe, called at most once and never while holding+ the lock: it is a network round trip, and unrelated lookups should not queue+ behind it.+ """++ now = time.time()+ with _LOCK:+ cached = _MEMORY.get(name)+ if cached is not None and cached.is_live(now):+ return cached.value++ persisted = _read_file().get(name)+ if persisted is not None and persisted.is_live(now):+ with _LOCK:+ _MEMORY[name] = persisted+ return persisted.value++ entry = _Entry(time.time(), fetch())+ with _LOCK:+ _MEMORY[name] = entry+ _persist(name, entry)+ return entry.valuediff --git a/core/managed_runtime.py b/core/managed_runtime.pyindex 0085ce560..cc726e161 100644--- a/core/managed_runtime.py+++ b/core/managed_runtime.py@@ -22,6 +22,7 @@ from pathlib import Path, PurePosixPath, PureWindowsPathfrom sysconfig import get_platformfrom typing import Any, Iterator+from config.atomic_io import write_atomicfrom core.dependency_network import (dependency_error_details,dependency_error_message,@@ -728,7 +729,7 @@ class ManagedRuntimeManager:if cache_remote:cached_manifest = self._remote_manifest_cache_path()try:- write_bytes_atomic(cached_manifest, payload)+ write_atomic(cached_manifest, payload)except OSError:logger.warning("Failed to cache %s manifest", self.spec.runtime_id, exc_info=True)return manifest@@ -1179,15 +1180,7 @@ def env_flag_enabled(name: str, *, default: bool = False) -> bool:return value.strip().lower() in {"1", "true", "yes", "on"}-def write_bytes_atomic(path: Path, payload: bytes) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- temporary = path.with_suffix(path.suffix + ".tmp")- temporary.write_bytes(payload)- temporary.replace(path)--def write_json_atomic(path: Path, payload: dict[str, Any]) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- temporary = path.with_suffix(path.suffix + ".tmp")- temporary.write_text(json.dumps(payload, sort_keys=True) + "\n", encoding="utf-8")- temporary.replace(path)+ # ``sort_keys`` keeps the manifest and install-state files diffable across+ # runs; the swap itself belongs to ``write_atomic``.+ write_atomic(path, json.dumps(payload, sort_keys=True) + "\n")diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 9b3b9105a..a486c26dc 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -6,7 +6,6 @@ import asyncioimport jsonimport loggingimport os-import tempfileimport threadingimport timefrom dataclasses import asdict, dataclass, field, replace@@ -26,6 +25,7 @@ from sqlalchemy import selectfrom sqlalchemy.exc import SQLAlchemyErrorfrom config import paths+from config.atomic_io import write_atomicfrom config.platform_registry import PLATFORM_REGISTRYfrom config.v2_config import (DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS,@@ -1381,16 +1381,7 @@ class ScheduledTaskStore:returnself.path.parent.mkdir(parents=True, exist_ok=True)payload = {"tasks": [task.to_dict() for task in self.list_tasks()]}- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.path.parent,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(self.path)+ write_atomic(self.path, json.dumps(payload, indent=2))self._signature = _path_signature(self.path)def list_tasks(self) -> list[ScheduledTask]:@@ -2261,16 +2252,7 @@ class TaskExecutionStore:},})- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.completed_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(self.completed_dir / path.name)+ write_atomic(self.completed_dir / path.name, json.dumps(payload, indent=2))path.unlink(missing_ok=True)return status@@ -2336,16 +2318,7 @@ class TaskExecutionStore:if not isinstance(payload, dict):return Falsepayload.update({"pid": os.getpid(), "started_at": now, "updated_at": now})- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.processing_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(processing_path)+ write_atomic(processing_path, json.dumps(payload, indent=2))return Truedef record_command_worker(@@ -2407,16 +2380,7 @@ class TaskExecutionStore:metadata[key] = dict(value)payload["metadata"] = metadatapayload["updated_at"] = _utc_now_iso()- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.processing_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(processing_path)+ write_atomic(processing_path, json.dumps(payload, indent=2))return Truedef list_running_command_workers(self) -> list[dict[str, Any]]:@@ -2493,16 +2457,7 @@ class TaskExecutionStore:return requestself._ensure_dirs()path = self._request_path(request.id, state="pending")- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.pending_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(request.to_dict(), handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(path)+ write_atomic(path, json.dumps(request.to_dict(), indent=2))return requestdef enqueue_task_run(@@ -3179,16 +3134,7 @@ class TaskExecutionStore:"updated_at": now,})- with tempfile.NamedTemporaryFile(- mode="w",- dir=path.parent,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(path)+ write_atomic(path, json.dumps(payload, indent=2))returndef mark_callback_pending(self, run_id: str) -> None:@@ -3214,16 +3160,7 @@ class TaskExecutionStore:"updated_at": now,})- with tempfile.NamedTemporaryFile(- mode="w",- dir=path.parent,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(path)+ write_atomic(path, json.dumps(payload, indent=2))returndef list_runs_page(@@ -3345,16 +3282,7 @@ class TaskExecutionStore:})completed_path = self._request_path(run_id, state="completed")- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.completed_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(completed_path)+ write_atomic(completed_path, json.dumps(payload, indent=2))pending_path.unlink(missing_ok=True)return True@@ -3374,16 +3302,7 @@ class TaskExecutionStore:"updated_at": now,})- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.processing_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(processing_path)+ write_atomic(processing_path, json.dumps(payload, indent=2))return Truereturn False@@ -3425,16 +3344,7 @@ class TaskExecutionStore:})completed_path = self._request_path(run_id, state="completed")- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.completed_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(completed_path)+ write_atomic(completed_path, json.dumps(payload, indent=2))if state != "completed":source_path.unlink(missing_ok=True)return True@@ -3607,16 +3517,7 @@ class TaskExecutionStore:),**({"escalation_run_id": escalation_run_id} if escalation_run_id else {}),}- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.completed_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(completed_path)+ write_atomic(completed_path, json.dumps(payload, indent=2))processing_path.unlink(missing_ok=True)return terminal_statusdiff --git a/core/update_checker.py b/core/update_checker.pyindex 5dedfb4ed..6b52e5f00 100644--- a/core/update_checker.py+++ b/core/update_checker.py@@ -13,7 +13,6 @@ import calendarimport jsonimport loggingimport re-import tempfileimport timeimport urllib.parseimport urllib.request@@ -22,6 +21,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Dict, Optionalfrom config import paths+from config.atomic_io import write_atomicfrom config.v2_config import UpdateConfigfrom config.v2_settings import _infer_channel_platformfrom core.handlers.admin_notifications import delivery_succeeded, resolve_admin_target, send_admin_text@@ -178,10 +178,9 @@ class UpdateState:return cls()def save(self) -> None:- """Save state atomically using temp file + rename."""+ """Persist update state; a failure here must never break the caller."""try:path = self._get_path()- path.parent.mkdir(parents=True, exist_ok=True)data = {"notified_version": self.notified_version,"notified_at": self.notified_at,@@ -192,13 +191,7 @@ class UpdateState:"blocked_auto_update_at": self.blocked_auto_update_at,"blocked_auto_update_current_version": self.blocked_auto_update_current_version,}- # Atomic write: write to temp file, then rename- with tempfile.NamedTemporaryFile(- mode="w", dir=path.parent, suffix=".tmp", delete=False, encoding="utf-8"- ) as f:- json.dump(data, f, indent=2)- temp_path = Path(f.name)- temp_path.replace(path)+ write_atomic(path, json.dumps(data, indent=2))except Exception as e:logger.warning(f"Failed to save update state: {e}")@@ -1126,13 +1119,7 @@ class UpdateChecker:@staticmethoddef _write_update_marker_payload(data: dict[str, Any]) -> None:marker_path = paths.get_state_dir() / "pending_update_notification.json"- marker_path.parent.mkdir(parents=True, exist_ok=True)- with tempfile.NamedTemporaryFile(- mode="w", dir=marker_path.parent, suffix=".tmp", delete=False, encoding="utf-8"- ) as f:- json.dump(data, f)- temp_path = Path(f.name)- temp_path.replace(marker_path)+ write_atomic(marker_path, json.dumps(data))def _record_post_update_admin_progress(self,diff --git a/core/watches.py b/core/watches.pyindex f29c50158..317f25fe3 100644--- a/core/watches.py+++ b/core/watches.py@@ -6,7 +6,6 @@ import asyncioimport jsonimport loggingimport os-import tempfileimport threadingfrom dataclasses import asdict, dataclass, field, replacefrom datetime import datetime, timezone@@ -16,6 +15,7 @@ from typing import Any, Optionalfrom uuid import uuid4from config import paths+from config.atomic_io import write_atomicfrom core import watch_workerfrom core.command_runner import SupervisedCommandStartupError, run_supervised_commandfrom core.process_isolation import (@@ -424,16 +424,7 @@ class ManagedWatchStore:)]}- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.path.parent,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(self.path)+ write_atomic(self.path, json.dumps(payload, indent=2))self._signature = _path_signature(self.path)def list_watches(self) -> list[ManagedWatch]:@@ -947,16 +938,7 @@ class WatchRuntimeStateStore:self._sqlite.write_watch_runtime(payload, updated_at=_utc_now_iso())returnself.path.parent.mkdir(parents=True, exist_ok=True)- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.path.parent,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(self.path)+ write_atomic(self.path, json.dumps(payload, indent=2))def load(self) -> dict[str, Any]:if self._sqlite is not None:diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex a56c7f8ea..d49daed85 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -8,12 +8,12 @@ import jsonimport osimport reimport shutil-import tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Literal, Mapping, Optional, castfrom config import paths+from config.atomic_io import write_atomicfrom config.v2_config import ModelHubConfig, ModelHubSourceConfigfrom core.handlers.model_hub.classification import ResolutionDecisionfrom core.handlers.model_hub.events import (@@ -1064,28 +1064,15 @@ class ModelHubRuntimeRouter:)def _secure_write_overlay(self, content: bytes) -> None:+ # ``mode=0o700`` on the directory is this method's own concern; the file is+ # 0600 by ``write_atomic``.self.overlay_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)try:if self.overlay_path.read_bytes() == content:returnexcept FileNotFoundError:pass- descriptor, temporary_name = tempfile.mkstemp(- prefix=f".{self.overlay_path.name}.",- dir=self.overlay_path.parent,- )- try:- with os.fdopen(descriptor, "wb") as stream:- stream.write(content)- stream.flush()- os.fsync(stream.fileno())- os.chmod(temporary_name, 0o600)- os.replace(temporary_name, self.overlay_path)- finally:- try:- os.unlink(temporary_name)- except FileNotFoundError:- pass+ write_atomic(self.overlay_path, content)def opencode_model_for_overlay(model: str | None, overlay: OpenCodeOverlay | None) -> str | None:diff --git a/modules/im/wechat.py b/modules/im/wechat.pyindex 117dda806..f4cafa6d6 100644--- a/modules/im/wechat.py+++ b/modules/im/wechat.py@@ -27,6 +27,7 @@ from .base import (InlineKeyboard,MessageContext,)+from config.atomic_io import write_atomicfrom config.paths import get_state_dirfrom vibe.i18n import t as i18n_tfrom vibe.proxy import resolve_proxy@@ -416,6 +417,9 @@ class WeChatBot(BaseIMClient):# Context tokens per user (needed for replies)self._context_tokens: Dict[str, str] = {}self._context_token_observed_at: Dict[str, float] = {}+ #: The token map as last successfully written to disk, so a save that+ #: would change nothing can be skipped. See ``_save_context_tokens``.+ self._persisted_context_tokens: Dict[str, str] = {}self._typing_tickets: Dict[tuple[str, str], str] = {}# getUpdates cursor@@ -1640,12 +1644,37 @@ class WeChatBot(BaseIMClient):self._context_tokens.update(loaded_tokens)self._context_token_observed_at.update(loaded_observed_at)+ # What we just read *is* what is on disk, so a restarted process+ # seeing the same tokens again has nothing to write. Entries the+ # loop above skipped are simply absent here, which only makes the+ # next save happen — never makes a needed one be skipped.+ self._persisted_context_tokens = dict(loaded_tokens)if loaded_tokens:logger.info("Loaded persisted WeChat context tokens for %d user(s)", len(loaded_tokens))except Exception as exc:logger.warning("Failed to load WeChat context tokens: %s", exc)def _save_context_tokens(self) -> None:+ """Persist the token map, but only when it differs from what is on disk.++ This is reached from ``_process_inbound_message`` for every message+ carrying a ``context_token``, on the single WeChat polling loop — and a+ user's token is the same on message after message, so almost every one+ of those calls used to rewrite a byte-identical document. That was+ merely wasteful while the write was a bare temp-file rename; routing it+ through ``write_atomic`` put two durability barriers in front of the+ next message in the batch, which is a cost this cache has no use for.+ It is re-learned from the next inbound message, so it never needed to+ survive a power loss.++ The comparison is against what was last *successfully written*, not+ against the live map, so a failed write is retried on the next message+ instead of being latched shut.+ """++ tokens = {user_id: token for user_id, token in self._context_tokens.items() if token}+ if tokens == self._persisted_context_tokens:+ returntry:path = self._get_context_token_cache_path()payload = {@@ -1655,22 +1684,14 @@ class WeChatBot(BaseIMClient):"context_token": token,"observed_at": self._context_token_observed_at.get(user_id, 0),}- for user_id, token in self._context_tokens.items()- if token+ for user_id, token in tokens.items()},}- with tempfile.NamedTemporaryFile(- mode="w",- dir=path.parent,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, ensure_ascii=False)- temp_path = Path(handle.name)- temp_path.replace(path)+ write_atomic(path, json.dumps(payload, ensure_ascii=False))except Exception as exc:logger.warning("Failed to save WeChat context tokens: %s", exc)+ return+ self._persisted_context_tokens = tokensdef _remember_context_token(self, user_id: str, context_token: str) -> None:if not user_id or not context_token:diff --git a/tests/conftest.py b/tests/conftest.pyindex 6827c37ba..b9cf4ec37 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -160,6 +160,22 @@ def _isolate_vibe_remote_home(request, tmp_path, monkeypatch):monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(isolated_home / ".claude"))[email protected](autouse=True)+def _reset_latest_version_cache():+ """Keep the process-lifetime version cache from crossing test boundaries.++ Its file tier already lands in each test's isolated home, but the memory+ tier is module state: one test's probe answer would otherwise satisfy the+ next test's lookup, and which test that is depends on the shuffle order.+ """++ from core import latest_version_cache++ latest_version_cache._MEMORY.clear() # noqa: SLF001+ yield+ latest_version_cache._MEMORY.clear() # noqa: SLF001++@pytest.fixture(autouse=True)def _seed_sqlite_state_template(request: pytest.FixtureRequest,diff --git a/tests/test_atomic_io.py b/tests/test_atomic_io.pynew file mode 100644index 000000000..d60461a68--- /dev/null+++ b/tests/test_atomic_io.py@@ -0,0 +1,166 @@+"""Properties every caller of ``write_atomic`` relies on.++Stated as properties rather than as a list of call sites: the whole point of+folding nineteen modules onto one function is that the next caller inherits+these guarantees without anybody remembering to extend a list here.+"""++from __future__ import annotations++import json+import os+import threading++import pytest++from config import atomic_io+from config.atomic_io import write_atomic+++def test_write_atomic_creates_missing_parent_directories(tmp_path) -> None:+ target = tmp_path / "deep" / "nested" / "state.json"++ write_atomic(target, json.dumps({"ok": True}))++ assert json.loads(target.read_text(encoding="utf-8")) == {"ok": True}++[email protected]("payload", ["héllo\n", b"h\xc3\xa9llo\n"])+def test_write_atomic_round_trips_text_and_bytes(tmp_path, payload) -> None:+ target = tmp_path / "payload.bin"++ write_atomic(target, payload)++ assert target.read_bytes() == b"h\xc3\xa9llo\n"++[email protected](os.name != "posix", reason="POSIX permission bits")+def test_write_atomic_result_is_owner_private_even_over_a_loose_file(tmp_path) -> None:+ """No window in which a file holding agent credentials is world-readable."""++ target = tmp_path / "auth.json"+ target.write_text("{}", encoding="utf-8")+ target.chmod(0o644)++ write_atomic(target, "{}\n")++ assert target.stat().st_mode & 0o777 == 0o600+++def test_write_atomic_leaves_the_destination_intact_when_the_swap_fails(+ tmp_path, monkeypatch+) -> None:+ target = tmp_path / "state.json"+ write_atomic(target, "original")++ monkeypatch.setattr(+ atomic_io.os,+ "replace",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("replace failed")),+ )+ with pytest.raises(OSError):+ write_atomic(target, "replacement")++ assert target.read_text(encoding="utf-8") == "original"+ assert list(tmp_path.glob(f".{target.name}.*")) == []+++def test_write_atomic_leaves_no_temp_file_when_the_payload_cannot_be_persisted(+ tmp_path, monkeypatch+) -> None:+ target = tmp_path / "state.json"++ monkeypatch.setattr(+ atomic_io.os,+ "fsync",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("disk full")),+ )+ with pytest.raises(OSError):+ write_atomic(target, "never lands")++ assert not target.exists()+ assert list(tmp_path.iterdir()) == []+++def test_concurrent_writers_publish_whole_payloads_never_fragments(tmp_path) -> None:+ """A per-call unique temp name is what keeps overlapping writers honest.++ A shared ``<name>.tmp`` would let one writer's ``os.replace`` publish another+ writer's half-flushed bytes; readers would see a payload nobody wrote.+ """++ target = tmp_path / "status.json"+ payloads = [json.dumps({"writer": index, "filler": "x" * 40_000}) for index in range(8)]+ whole = set(payloads)+ observed: list[str] = []+ stop = threading.Event()++ def _write(payload: str) -> None:+ for _ in range(20):+ write_atomic(target, payload)++ def _read() -> None:+ while not stop.is_set():+ try:+ observed.append(target.read_text(encoding="utf-8"))+ except FileNotFoundError:+ continue++ reader = threading.Thread(target=_read, daemon=True)+ reader.start()+ writers = [threading.Thread(target=_write, args=(payload,)) for payload in payloads]+ for writer in writers:+ writer.start()+ for writer in writers:+ writer.join()+ stop.set()+ reader.join(timeout=5)++ assert target.read_text(encoding="utf-8") in whole+ assert observed, "reader never managed to observe the file"+ assert set(observed) <= whole+ assert list(tmp_path.glob(f".{target.name}.*")) == []+++def test_write_atomic_replaces_a_symlink_by_default(tmp_path) -> None:+ """State this process owns: resolving a planted symlink is the wrong answer."""++ real = tmp_path / "elsewhere.json"+ real.write_text("untouched", encoding="utf-8")+ link = tmp_path / "state.json"+ link.symlink_to(real)++ write_atomic(link, "mine")++ assert not link.is_symlink()+ assert link.read_text(encoding="utf-8") == "mine"+ assert real.read_text(encoding="utf-8") == "untouched"+++def test_write_atomic_follows_a_symlink_when_asked(tmp_path) -> None:+ """A user's dotfiles link must survive an edit to the file it stands for."""++ real = tmp_path / "dotfiles" / "CLAUDE.md"+ real.parent.mkdir()+ real.write_text("old", encoding="utf-8")+ link = tmp_path / "CLAUDE.md"+ link.symlink_to(real)++ write_atomic(link, "new", follow_symlinks=True)++ assert link.is_symlink()+ assert real.read_text(encoding="utf-8") == "new"++[email protected]("missing", ["fchmod", "O_DIRECTORY"])+def test_write_atomic_does_not_require_optional_os_attributes(+ tmp_path, monkeypatch, missing+) -> None:+ """Neither is available everywhere Avibe runs; both are only ever nice to have."""++ monkeypatch.delattr(atomic_io.os, missing, raising=False)+ target = tmp_path / "state.json"++ write_atomic(target, "portable")++ assert target.read_text(encoding="utf-8") == "portable"diff --git a/tests/test_discovered_chats.py b/tests/test_discovered_chats.pyindex 7a7cf626e..eb7984171 100644--- a/tests/test_discovered_chats.py+++ b/tests/test_discovered_chats.py@@ -1,7 +1,8 @@import jsonfrom pathlib import Path-from config import paths+from config import discovered_chats, paths+from config.atomic_io import write_atomicfrom config.discovered_chats import DiscoveredChatsStore@@ -72,15 +73,13 @@ def test_discovered_chats_save_keeps_target_file_valid_until_replace(tmp_path, mmonkeypatch.setattr(paths, "ensure_data_dirs", lambda: None)store = DiscoveredChatsStore(storage_path)- original_replace = Path.replace- observed_before_replace: dict[str, object] = {}+ handed_to_the_swap: list[tuple[Path, str]] = []- def checking_replace(self: Path, target: Path) -> Path:- if target == storage_path:- observed_before_replace["payload"] = json.loads(target.read_text(encoding="utf-8"))- return original_replace(self, target)+ def spying_write_atomic(path, data, **kwargs):+ handed_to_the_swap.append((path, data))+ return write_atomic(path, data, **kwargs)- monkeypatch.setattr(Path, "replace", checking_replace)+ monkeypatch.setattr(discovered_chats, "write_atomic", spying_write_atomic)store.remember_chat(platform="telegram",@@ -90,9 +89,18 @@ def test_discovered_chats_save_keeps_target_file_valid_until_replace(tmp_path, mis_forum=True,)- before_replace = observed_before_replace["payload"]- assert before_replace["platforms"]["telegram"]["-1001"]["name"] == "Old Chat"- assert "-1002" not in before_replace["platforms"]["telegram"]+ # One call carrying the whole document is what makes "valid until replace"+ # true; ``write_atomic`` owns the swap itself and proves its own atomicity.+ # Were this store to go back to updating the file in place, or to write the+ # platforms out one at a time, that would show up here as a different number+ # of calls or a partial payload — not as a subtly racy file nobody notices.+ assert len(handed_to_the_swap) == 1+ path, payload = handed_to_the_swap[0]+ assert path == storage_path++ handed = json.loads(payload)+ assert handed["platforms"]["telegram"]["-1001"]["name"] == "Old Chat"+ assert handed["platforms"]["telegram"]["-1002"]["name"] == "New Chat"saved_payload = json.loads(storage_path.read_text(encoding="utf-8"))- assert saved_payload["platforms"]["telegram"]["-1002"]["name"] == "New Chat"+ assert saved_payload == handeddiff --git a/tests/test_latest_version_cache.py b/tests/test_latest_version_cache.pynew file mode 100644index 000000000..262ad62ba--- /dev/null+++ b/tests/test_latest_version_cache.py@@ -0,0 +1,344 @@+"""Properties of the managed-dependency latest-version cache.++The point of the file tier is that a *different process* inherits the answer, so+the tests below simulate that the only honest way: clear the memory tier and ask+again, exactly as a fresh ``vibe runtime prepare`` would.+"""++from __future__ import annotations++import json+import math+import time+from types import SimpleNamespace++import pytest++from core import latest_version_cache+from core.latest_version_cache import cache_path, cached_latest+++class _NovelFailure(Exception):+ """An exception type no hand-written list of failure modes could contain."""+++class _Probe:+ """A fetch callable that records how often it was actually asked."""++ def __init__(self, *values: str | None) -> None:+ self._values = list(values)+ self.calls = 0++ def __call__(self) -> str | None:+ self.calls += 1+ return self._values[min(self.calls - 1, len(self._values) - 1)]+++def _never_probed() -> str | None:+ raise AssertionError("the cached answer should have satisfied this lookup")+++def _cold_process() -> None:+ """Drop the memory tier, leaving only what a new process would find."""++ latest_version_cache._MEMORY.clear() # noqa: SLF001+++def _remember(name: str, *, age: float, value: str | None) -> None:+ """Seed the memory tier alone with an entry of a given age."""++ latest_version_cache._MEMORY[name] = latest_version_cache._Entry(time.time() - age, value) # noqa: SLF001+++def _persisted() -> dict:+ return json.loads(cache_path().read_text(encoding="utf-8"))+++def _not_json(token: str) -> float:+ """Refuse the tokens Python emits but the JSON grammar does not contain."""++ raise AssertionError(f"the cache file must be readable by any JSON parser, found {token!r}")+++def test_a_second_process_inherits_the_answer_without_probing() -> None:+ probe = _Probe("0.1.15")++ assert cached_latest("askill", probe) == "0.1.15"+ _cold_process()+ assert cached_latest("askill", probe) == "0.1.15"++ assert probe.calls == 1+++def test_a_failed_probe_stops_at_the_memory_tier() -> None:+ """The file holds answers; a failure is not one, so it does not travel.++ Inheriting one never bought what it looked like it bought: a process that+ reads a cached ``None`` reports ``latest_unavailable`` and reinstalls askill+ outright, where re-probing might find the blip already over. It saves one+ HTTP request against a budget that — in the only case this arises — is+ already exhausted, and pays for it with the race in the next test.+ """++ probe = _Probe(None, "0.1.15")++ assert cached_latest("askill", probe) is None+ assert not cache_path().exists()++ # Same process asks again: the memory tier still backs off, which is the+ # tier that needs to — a service polling a dead registry, not a fresh CLI.+ assert cached_latest("askill", probe) is None+ assert probe.calls == 1++ _cold_process()+ assert cached_latest("askill", probe) == "0.1.15"+ assert probe.calls == 2+++def test_a_failed_probe_never_writes_the_file() -> None:+ """Why the same-name race is gone rather than narrowed.++ Two cold processes miss the same name and both probe, outside any+ cross-process lock, so the failure can land after the success. No+ check-then-write can stop that — it only shrinks the window. A failure that+ never touches the file cannot lose the race in the first place.+ """++ stale = time.time() - latest_version_cache.SUCCESS_TTL_SECONDS - 1+ _write_entries({"askill": {"at": stale, "value": "0.1.15"}})+ before = cache_path().read_bytes()+ _cold_process()++ # Expired, so this process really does probe — and really does fail.+ assert cached_latest("askill", _Probe(None)) is None+ assert cache_path().read_bytes() == before+++def test_the_memory_tier_retries_a_failure_far_sooner_than_a_success() -> None:+ """Both TTLs still govern, in the one tier where the backoff pays for itself."""++ probe = _Probe("0.1.15")++ _remember("askill", age=latest_version_cache.FAILURE_TTL_SECONDS + 1, value=None)+ assert cached_latest("askill", probe) == "0.1.15"++ _remember("askill", age=latest_version_cache.FAILURE_TTL_SECONDS - 1, value=None)+ assert cached_latest("askill", _never_probed) is None++ _remember("askill", age=latest_version_cache.SUCCESS_TTL_SECONDS - 60, value="0.1.14")+ assert cached_latest("askill", _never_probed) == "0.1.14"+ assert probe.calls == 1+++def test_an_expired_entry_is_re_probed() -> None:+ probe = _Probe("0.1.15", "0.1.16")+ cached_latest("askill", probe)++ _write_entries(+ {"askill": {"at": time.time() - latest_version_cache.SUCCESS_TTL_SECONDS - 1, "value": "0.1.15"}}+ )+ _cold_process()++ assert cached_latest("askill", probe) == "0.1.16"+ assert probe.calls == 2+++def test_a_timestamp_from_the_future_is_never_live() -> None:+ """A clock that stepped backwards must not pin an entry until it catches up."""++ probe = _Probe("0.1.16")+ _write_entries({"askill": {"at": time.time() + 86_400, "value": "0.1.15"}})++ assert cached_latest("askill", probe) == "0.1.16"+ assert probe.calls == 1+++def test_a_null_answer_on_disk_is_ignored_rather_than_inherited() -> None:+ """The rule holds in both directions: never written, so never trusted.++ Otherwise a corrupted byte or a foreign writer could pin+ ``latest_unavailable`` — and therefore an askill reinstall — on every cold+ process for the whole failure TTL.+ """++ _write_entries({"askill": {"at": time.time(), "value": None}})++ assert cached_latest("askill", _Probe("0.1.15")) == "0.1.15"+ assert _persisted()["entries"]["askill"]["value"] == "0.1.15"+++def test_entries_for_other_dependencies_survive_a_write() -> None:+ """askill runs from the CLI and opencode from the service; neither may evict."""++ cached_latest("askill", _Probe("0.1.15"))+ cached_latest("opencode", _Probe("1.2.3"))+ _cold_process()++ assert cached_latest("askill", _never_probed) == "0.1.15"+ assert set(_persisted()["entries"]) == {"askill", "opencode"}++ # opencode expires and is re-probed; the rewrite that publishes its new+ # answer must carry askill's untouched entry along with it.+ _write_entries(+ {+ "askill": _persisted()["entries"]["askill"],+ "opencode": {"at": time.time() - latest_version_cache.SUCCESS_TTL_SECONDS - 1, "value": "1.2.3"},+ }+ )+ _cold_process()+ assert cached_latest("opencode", _Probe("1.2.4")) == "1.2.4"+ _cold_process()+ assert cached_latest("askill", _never_probed) == "0.1.15"+++ "content",+ [+ "not json at all",+ json.dumps({"schema_version": 999, "entries": {"askill": {"at": 0, "value": "0.1.15"}}}),+ json.dumps({"schema_version": 1, "entries": "not-a-mapping"}),+ json.dumps(["not", "a", "mapping"]),+ json.dumps({"schema_version": 1}),+ ],+)+def test_an_unusable_cache_file_costs_a_probe_and_nothing_else(content) -> None:+ cache_path().parent.mkdir(parents=True, exist_ok=True)+ cache_path().write_text(content, encoding="utf-8")+ probe = _Probe("0.1.15")++ assert cached_latest("askill", probe) == "0.1.15"+ assert probe.calls == 1+ assert _persisted()["entries"]["askill"]["value"] == "0.1.15"+++def test_bytes_that_are_not_a_document_cost_a_probe_and_nothing_else() -> None:+ """Not one more entry in an enumeration — the property the loader promises.++ A non-UTF-8 file raises ``UnicodeDecodeError`` rather than+ ``JSONDecodeError``, which is exactly the member a hand-written list of+ failure modes was always going to be missing.+ """++ cache_path().parent.mkdir(parents=True, exist_ok=True)+ cache_path().write_bytes(b'{"schema_version": 1, "entries": {"\xff\xfe": 0}}')+ probe = _Probe("0.1.15")++ assert cached_latest("askill", probe) == "0.1.15"+ assert probe.calls == 1+ assert _persisted()["entries"]["askill"]["value"] == "0.1.15"+++ "entry",+ [+ {"at": "yesterday", "value": "0.1.15"},+ {"at": True, "value": "0.1.15"},+ {"at": 0, "value": {"nested": "junk"}},+ "not-a-mapping",+ # Raises rather than mismatches: ``float`` of an integer this large is an+ # ``OverflowError``, which is an ``ArithmeticError`` and so slips past any+ # guard written in terms of ``ValueError``.+ {"at": int("9" * 400), "value": "0.1.15"},+ ],+)+def test_an_unusable_entry_is_skipped_without_discarding_its_neighbours(entry) -> None:+ fresh = time.time()+ _write_entries({"askill": entry, "opencode": {"at": fresh, "value": "1.2.3"}})++ assert cached_latest("opencode", _never_probed) == "1.2.3"+ assert cached_latest("askill", _Probe("0.1.15")) == "0.1.15"++[email protected]("at", [float("inf"), float("nan")])+def test_a_timestamp_that_is_not_a_number_never_reaches_the_file_again(at) -> None:+ """The file this process writes has to stay readable by every other reader.++ ``inf`` and ``NaN`` neither raise nor mismatch: they survive a JSON round+ trip and merely compare false against every TTL, so simply skipping the+ lookup looks like enough. It is not, because publishing *another* name+ rewrites the whole file, and ``json.dumps`` renders them as the bare+ ``Infinity``/``NaN`` tokens that are not JSON. One poisoned neighbour then+ costs every stricter reader the entire file instead of one entry.+ """++ expired = time.time() - latest_version_cache.SUCCESS_TTL_SECONDS - 1+ _write_entries({"askill": {"at": at, "value": "0.1.15"}, "opencode": {"at": expired, "value": "1.2.3"}})+ _cold_process()++ # opencode re-probes, and publishing its answer rewrites the whole file --+ # carrying whatever askill's entry was parsed into along with it.+ assert cached_latest("opencode", _Probe("1.2.4")) == "1.2.4"++ written = json.loads(cache_path().read_text(encoding="utf-8"), parse_constant=_not_json)+ assert written["entries"]["opencode"]["value"] == "1.2.4"+ assert "askill" not in written["entries"]+++def test_an_unforeseen_entry_failure_still_costs_only_a_probe(monkeypatch) -> None:+ """The property, stated where enumerating members kept failing to state it.++ Two review rounds each handed over the next member of a list —+ ``UnicodeDecodeError`` from non-UTF-8 bytes, then ``OverflowError`` from an+ integer too large for a float. Both were fixed by naming that member. This+ test instead raises something no list could have named, and demands the+ answer every other unusable entry already gets: one probe, no traceback. It+ fails the moment the guard is narrowed back into an enumeration.+ """++ def boom(_value: float) -> bool:+ raise _NovelFailure("no enumeration was ever going to list this one")++ monkeypatch.setattr(latest_version_cache, "math", SimpleNamespace(isfinite=boom))+ _write_entries({"askill": {"at": time.time(), "value": "0.1.15"}})++ probe = _Probe("0.1.16")+ assert cached_latest("askill", probe) == "0.1.16"+ assert probe.calls == 1+++def test_an_answer_is_timestamped_when_the_question_was_asked() -> None:+ """What bounds the one race this file still permits, so it stays bounded.++ Two cold processes can probe the same name across a release publication and+ the older probe can write last, so the cache can serve the version that was+ newest when its question was asked. That is only acceptable because the+ entry carries *that* moment rather than the moment its answer arrived: the+ loser of the race is by construction the process that asked earlier, so its+ entry also expires earlier, and the cache serves exactly what a single+ unraced probe issued at the same instant would have served.++ Timestamp the answer on arrival instead and the loser looks the fresher of+ the two, extending the stale answer past the TTL that justifies it.+ """++ def slow_probe() -> str:+ time.sleep(0.2)+ return "0.1.15"++ asked_at = time.time()+ cached_latest("askill", slow_probe)+ answered_at = time.time()++ at = _persisted()["entries"]["askill"]["at"]+ assert at - asked_at < 0.1+ assert answered_at - at >= 0.2+++def test_a_lookup_still_answers_when_the_state_directory_cannot_be_written(+ monkeypatch,+) -> None:+ monkeypatch.setattr(+ latest_version_cache,+ "write_atomic",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only filesystem")),+ )++ assert cached_latest("askill", _Probe("0.1.15")) == "0.1.15"+++def _write_entries(entries: dict) -> None:+ cache_path().parent.mkdir(parents=True, exist_ok=True)+ cache_path().write_text(+ json.dumps({"schema_version": latest_version_cache.SCHEMA_VERSION, "entries": entries}),+ encoding="utf-8",+ )diff --git a/tests/test_local_deps.py b/tests/test_local_deps.pyindex 61fef0996..6b5e24d14 100644--- a/tests/test_local_deps.py+++ b/tests/test_local_deps.py@@ -20,6 +20,7 @@ from unittest.mock import Mockimport pytest+from core import latest_version_cachefrom vibe import api@@ -848,6 +849,69 @@ def test_refresh_askill_if_stale_does_not_run_the_installer_when_current(monkeypassert "action" not in out+def test_a_second_prepare_process_reuses_the_persisted_askill_latest(monkeypatch):+ # The waste this closes: ``vibe runtime prepare`` is a fresh process on every+ # install, upgrade, regression sync, and tenant update, and each one used to+ # spend a GitHub request re-learning askill's newest release. That request+ # comes out of the unauthenticated 60/hour/IP budget, and exhausting it makes+ # the latest lookup fail, which makes prepare reinstall askill outright.+ monkeypatch.setattr(+ api,+ "askill_status",+ lambda: {"id": "askill", "installed": True, "version": "0.1.14", "status": "ready"},+ )+ monkeypatch.setattr(api, "ensure_askill_installed", lambda force=False: pytest.fail("should not install"))+ probes = []+ monkeypatch.setattr(+ api,+ "_fetch_latest_askill_version",+ lambda: probes.append(1) or "0.1.14",+ )++ assert api.refresh_askill_if_stale()["reason"] == "up_to_date"+ latest_version_cache._MEMORY.clear() # noqa: SLF001 - stand in for a new process+ assert api.refresh_askill_if_stale()["reason"] == "up_to_date"++ assert len(probes) == 1+++def test_installing_askill_keeps_the_persisted_latest_for_the_next_process(monkeypatch):+ """An install is the one moment prepare runs most, and must not cost a probe.++ Installing 0.1.14 does not change the fact that 0.1.14 is what askill+ publishes, so the entry that justified the install is exactly what the next+ process needs: it compares a freshly measured local version against it and+ concludes ``up_to_date``. Retiring it here — the reflex the in-memory cache+ this replaced had — would send every post-update ``runtime prepare`` back to+ GitHub for a string already on disk.+ """++ installed = {"version": "0.1.13"}+ monkeypatch.setattr(+ api,+ "askill_status",+ lambda: {"id": "askill", "installed": True, "version": installed["version"], "status": "ready"},+ )++ def _install(force=False):+ installed["version"] = "0.1.14"+ return {"ok": True, "installed": True, "changed": True, "path": "/x/askill"}++ monkeypatch.setattr(api, "ensure_askill_installed", _install)+ probes = []+ monkeypatch.setattr(+ api,+ "_fetch_latest_askill_version",+ lambda: probes.append(1) or "0.1.14",+ )++ assert api.refresh_askill_if_stale()["action"] == "update"+ latest_version_cache._MEMORY.clear() # noqa: SLF001 - stand in for a new process++ assert api.refresh_askill_if_stale()["reason"] == "up_to_date"+ assert len(probes) == 1++def test_refresh_askill_if_stale_ignores_the_auto_update_gate(monkeypatch):# ``VIBE_ASKILL_AUTO_UPDATE`` disables the update-checker cadence, not the# lifecycle refresh that ``vibe runtime prepare`` performs; keeping the gatediff --git a/tests/test_memory_config.py b/tests/test_memory_config.pyindex 95a7a7b8e..f2635e69f 100644--- a/tests/test_memory_config.py+++ b/tests/test_memory_config.py@@ -902,7 +902,7 @@ def test_memory_config_drops_retired_proactive_capture_flag(tmp_path) -> None:def test_fresh_config_save_fsyncs_parent_after_replace(monkeypatch, tmp_path) -> None:- from config import v2_config+ from config import atomic_ioconfig_path = tmp_path / "config.json"observed: list[tuple[Path, str]] = []@@ -910,7 +910,7 @@ def test_fresh_config_save_fsyncs_parent_after_replace(monkeypatch, tmp_path) ->def observe_directory_sync(directory: Path) -> None:observed.append((directory, config_path.read_text(encoding="utf-8")))- monkeypatch.setattr(v2_config, "_fsync_directory", observe_directory_sync)+ monkeypatch.setattr(atomic_io, "_fsync_directory", observe_directory_sync)V2Config.from_payload(_payload({"recovery_intent": "rebuild"})@@ -925,7 +925,7 @@ def test_config_save_cleans_temporary_file_when_replace_fails(monkeypatch,tmp_path,) -> None:- from config import v2_config+ from config import atomic_ioconfig_path = tmp_path / "config.json"config = V2Config.from_payload(_payload({"recovery_intent": "rebuild"}))@@ -935,7 +935,7 @@ def test_config_save_cleans_temporary_file_when_replace_fails(def fail_replace(source: Path, target: Path) -> None:raise OSError("replace failed")- monkeypatch.setattr(v2_config.os, "replace", fail_replace)+ monkeypatch.setattr(atomic_io.os, "replace", fail_replace)with pytest.raises(OSError, match="replace failed"):config.language = "zh"diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex 7884aebcd..6fcec9060 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -1413,18 +1413,26 @@ def test_wire_bytes_reach_the_observer_before_the_buffer_that_can_refuse_them()assert owner.index("wire_state.observe(") < owner.index("prelude.write(")-def test_model_hub_state_documents_have_one_atomic_replacement_owner() -> None:+def test_no_model_hub_module_spells_its_own_atomic_replacement() -> None:"""Review 4965677908: a failed replacement must not leave a temp file behind.Cleanup is unobservable from outside — the writers swallow ``OSError`` so afull disk cannot break metering — so it cannot be maintained one collectionat a time. A module that spells its own temporary file is a second owner ofthe property, whether or not it remembers the cleanup.++ Stated as "nobody here re-implements it" rather than "exactly ``state_file``+ implements it": the owner has since moved out of this package entirely, into+ ``config.atomic_io``, and naming the owner made this guard fail for the one+ change that satisfied it best."""- owners = set()- for module in sorted((ROOT / "core/handlers/model_hub").glob("*.py")):- text = module.read_text(encoding="utf-8")- if any(marker in text for marker in ("tempfile", "os.replace", "os.rename")):- owners.add(module.name)- assert owners == {"state_file.py"}+ second_owners = {+ module.name+ for module in sorted((ROOT / "core/handlers/model_hub").glob("*.py"))+ if any(+ marker in module.read_text(encoding="utf-8")+ for marker in ("tempfile", "os.replace", "os.rename")+ )+ }+ assert second_owners == set()diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.pyindex 63578747d..696f048e9 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -27,7 +27,6 @@ from pathlib import Pathimport pytestfrom config.v2_config import ModelHubModelConfig-from core.handlers.model_hub import state_filefrom core.handlers.model_hub.identifiers import (MODEL_ID_MAX_LENGTH,USAGE_LEDGER_KEY_MAX_LENGTH,@@ -1306,8 +1305,12 @@ def test_a_record_leaves_no_temporary_file_behind(tmp_path: Path) -> None:assert [entry.name for entry in ledger.path.parent.iterdir()] == [ledger.path.name]+ os.name != "posix" or os.geteuid() == 0,+ reason="needs POSIX directory permissions, which root ignores",+)def test_a_write_that_fails_leaves_neither_residue_nor_a_damaged_document(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ tmp_path: Path,) -> None:"""MH-USAGE-003, review 4965677908: a failed replacement must cost only that write.@@ -1316,21 +1319,28 @@ def test_a_write_that_fails_leaves_neither_residue_nor_a_damaged_document(behind. A ledger bounded to `max_rows` whose state directory gains one orphanper failure is not bounded, and a half-written document would lose the daysalready recorded — so the write either lands whole or changes nothing.++ The failure is a genuinely unwritable directory rather than a patched+ ``os.replace``: the swap moved out of this package into ``config.atomic_io``,+ and a test that reaches for the mechanism has to be rewritten every time the+ mechanism moves. A real ``OSError`` from the filesystem does not care where+ the temp file was going to be created."""ledger = _ledger(tmp_path)ledger.record(source_id="src_a", model_id="model-x", usage=None, at=NOW)recorded = ledger.path.read_bytes()- def refuse(*_args, **_kwargs) -> None:- raise OSError("no space left on device")-- monkeypatch.setattr(state_file.os, "replace", refuse)- with pytest.raises(OSError):- ledger.record(source_id="src_b", model_id="model-y", usage=None, at=NOW)+ directory = ledger.path.parent+ directory.chmod(0o500)+ try:+ with pytest.raises(OSError):+ ledger.record(source_id="src_b", model_id="model-y", usage=None, at=NOW)- assert [entry.name for entry in ledger.path.parent.iterdir()] == [ledger.path.name]- assert ledger.path.read_bytes() == recorded+ assert [entry.name for entry in directory.iterdir()] == [ledger.path.name]+ assert ledger.path.read_bytes() == recorded+ finally:+ directory.chmod(0o700)def test_days_bucket_by_the_host_calendar_not_utc(tmp_path: Path) -> None:diff --git a/tests/test_permissions.py b/tests/test_permissions.pyindex 3add1310c..d32470825 100644--- a/tests/test_permissions.py+++ b/tests/test_permissions.py@@ -3,11 +3,13 @@ from __future__ import annotationsfrom copy import deepcopyimport jsonimport multiprocessing as mp+import osfrom typing import Anyimport pytestimport requests+from config import atomic_iofrom config.v2_config import (AgentsConfig,RemoteAccessConfig,@@ -665,7 +667,7 @@ def test_permissions_offline_cache_is_sanitized_and_exact_instance_bound(monkeypcache = json.loads(permissions._cache_path().read_text(encoding="utf-8")) # noqa: SLF001assert "must-not-persist" not in json.dumps(cache)assert cache["projection"]["debug"] == {"note": "kept"}- if permissions.os.name == "posix":+ if os.name == "posix":assert permissions._cache_path().stat().st_mode & 0o777 == 0o600 # noqa: SLF001monkeypatch.setattr(@@ -682,7 +684,7 @@ def test_permissions_offline_cache_is_sanitized_and_exact_instance_bound(monkeypdef test_permissions_cache_remains_atomic_without_os_fchmod(monkeypatch) -> None:- monkeypatch.delattr(permissions.os, "fchmod", raising=False)+ monkeypatch.delattr(atomic_io.os, "fchmod", raising=False)projection = _complete_projection()config = _config()monkeypatch.setattr(@@ -700,7 +702,7 @@ def test_permissions_cache_remains_atomic_without_os_fchmod(monkeypatch) -> Nonenewer = _complete_projection()newer["instance"]["authorization_revision"] = 4monkeypatch.setattr(- permissions.os,+ atomic_io.os,"replace",lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("replace failed")),)diff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.pyindex 0f4cbf12e..f95890c52 100644--- a/tests/test_wechat_bot.py+++ b/tests/test_wechat_bot.py@@ -10,6 +10,7 @@ from unittest.mock import patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from config.atomic_io import write_atomicfrom config.v2_settings import SettingsStore, UserSettingsfrom core.auth import AuthResultfrom modules.im import InlineButton, InlineKeyboard, MessageContext@@ -660,6 +661,63 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):restored._load_context_tokens()self.assertEqual(restored._get_context_token_for_user("user-1"), "ctx-persisted")+ async def test_an_unchanged_token_costs_no_write(self):+ """A message writes to disk only when it changes what is on disk.++ ``_remember_context_token`` is reached from the WeChat polling loop for+ every inbound message carrying a token, and a user's token is the same+ message after message. That was merely wasteful while the write was a+ bare temp-file rename; through ``write_atomic`` each redundant one is an+ fsync of the payload and of the state directory, sitting between a batch+ of messages and their replies.+ """++ with tempfile.TemporaryDirectory() as tmpdir:+ with patch.dict("os.environ", {"AVIBE_HOME": tmpdir}):+ bot = self._make_bot()+ with patch("modules.im.wechat.write_atomic", wraps=write_atomic) as writes:+ for _ in range(3):+ bot._remember_context_token("user-1", "ctx-1")+ self.assertEqual(writes.call_count, 1)++ # A rotated token and a second user each change the document.+ bot._remember_context_token("user-1", "ctx-2")+ bot._remember_context_token("user-2", "ctx-9")+ self.assertEqual(writes.call_count, 3)++ # Nor does a restarted process that reads back those same tokens.+ restored = self._make_bot()+ restored._load_context_tokens()+ with patch("modules.im.wechat.write_atomic") as writes:+ restored._remember_context_token("user-1", "ctx-2")+ writes.assert_not_called()++ cache_path = Path(tmpdir) / "state" / "wechat_context_tokens.json"+ data = json.loads(cache_path.read_text(encoding="utf-8"))+ self.assertEqual(data["tokens"]["user-1"]["context_token"], "ctx-2")+ self.assertEqual(data["tokens"]["user-2"]["context_token"], "ctx-9")++ async def test_a_failed_save_is_retried_rather_than_latched_shut(self):+ """The skip compares against what reached disk, not against intent.++ Comparing against the in-memory map instead would record a write that+ never happened, and every later message carrying that same token would+ then be skipped as redundant — one transient ``ENOSPC`` losing the token+ for good.+ """++ with tempfile.TemporaryDirectory() as tmpdir:+ with patch.dict("os.environ", {"AVIBE_HOME": tmpdir}):+ bot = self._make_bot()+ with patch("modules.im.wechat.write_atomic", side_effect=OSError("no space left on device")):+ bot._remember_context_token("user-1", "ctx-1")++ bot._remember_context_token("user-1", "ctx-1")++ cache_path = Path(tmpdir) / "state" / "wechat_context_tokens.json"+ data = json.loads(cache_path.read_text(encoding="utf-8"))+ self.assertEqual(data["tokens"]["user-1"]["context_token"], "ctx-1")+async def test_send_dm_reuses_persisted_context_token(self):with tempfile.TemporaryDirectory() as tmpdir:with patch.dict("os.environ", {"AVIBE_HOME": tmpdir}):diff --git a/vibe/api.py b/vibe/api.pyindex 0f65294ef..840ee65aa 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -49,6 +49,7 @@ from config.v2_settings import ()from config.v2_sessions import SessionsStorefrom config.platform_registry import get_platform_descriptor+from core import latest_version_cachefrom core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLeasefrom vibe.opencode_config import (get_opencode_config_paths,@@ -8121,19 +8122,10 @@ def _fetch_latest_askill_version() -> str | None:def _cached_latest_askill() -> str | None:- # Share the backend lifecycle cache so every local tool latest probe obeys the- # same one-hour success TTL and short failure TTL.- key = "askill"- with _BACKEND_CACHE_LOCK:- cached = _BACKEND_LATEST_CACHE.get(key)- if cached:- ttl = _BACKEND_LATEST_TTL_SECONDS if cached[1] else _BACKEND_LATEST_FAILURE_TTL_SECONDS- if time.time() - cached[0] < ttl:- return cached[1]- latest = _fetch_latest_askill_version()- with _BACKEND_CACHE_LOCK:- _BACKEND_LATEST_CACHE[key] = (time.time(), latest)- return latest+ # Share the managed-dependency cache so every local tool latest probe obeys+ # the same TTLs — and, more to the point here, so ``vibe runtime prepare``+ # inherits the answer a previous process already paid GitHub for.+ return latest_version_cache.cached_latest(_ASKILL_CACHE_KEY, _fetch_latest_askill_version)def askill_update_status(*, include_latest: bool = True) -> dict:@@ -8214,8 +8206,13 @@ def refresh_askill_if_stale() -> dict:result["action"] = "update"result["from_version"] = status.get("version")result["latest_version"] = latest- with _BACKEND_CACHE_LOCK:- _BACKEND_LATEST_CACHE.pop("askill", None)+ # Deliberately no cache invalidation here, unlike the in-memory cache this+ # replaced. The entry says which version askill *publishes*, and installing+ # that version does not change the answer — it makes it the one a later+ # ``askill_update_status`` needs, to compare a freshly measured local version+ # against and conclude ``up_to_date``. Dropping it would send the next+ # ``runtime prepare`` back to GitHub for a string we still hold, in the one+ # window (right after an update) where prepare runs most often.return result@@ -8703,9 +8700,14 @@ def start_dependency_install_job(dep: str) -> dict:# Backend lifecycle (version probe, latest check, restart)# =============================================================================-# In-memory caches keyed by (backend, cli_path) so version answers stay tied-# to the binary they came from. Trade freshness for fewer probes during rapid-# popover opens. Tuned for human pacing (seconds), not bots.+# The *locally installed* version, keyed by (backend, cli_path) so answers stay+# tied to the binary they came from. Trade freshness for fewer probes during+# rapid popover opens. Tuned for human pacing (seconds), not bots.+#+# In memory only, deliberately: this answers "what did the binary at this path+# just print", which a new process can re-measure in milliseconds and which a+# stale file could get wrong after an install. The *published* version is the+# expensive one, and :mod:`core.latest_version_cache` persists that instead.## The UI server handles requests on multiple threads, so reads, writes, and# invalidation can race. A single lock serializes mutation — fast in practice@@ -8714,14 +8716,12 @@ def start_dependency_install_job(dep: str) -> dict:# scan in ``_invalidate_version_cache``._BACKEND_CACHE_LOCK = __import__("threading").Lock()_BACKEND_VERSION_CACHE: dict[tuple[str, str], tuple[float, str | None]] = {}-_BACKEND_LATEST_CACHE: dict[str, tuple[float, str | None]] = {}_BACKEND_VERSION_TTL_SECONDS = 30.0-_BACKEND_LATEST_TTL_SECONDS = 3600.0-# Failed lookups (network down, registry hiccup) re-probe sooner so a-# transient outage doesn't pin "—" for the full hour.-_BACKEND_LATEST_FAILURE_TTL_SECONDS = 120.0_BACKEND_RUNTIME_USER_AGENT = "avibe/backend-runtime"_ASKILL_RELEASE_REPOSITORY = "avibe-bot/askill"+#: askill is a managed dependency, not an agent backend, so it needs a name of+#: its own in the shared latest-version cache.+_ASKILL_CACHE_KEY = "askill"_ASKILL_AUTO_UPDATE_ENV = "VIBE_ASKILL_AUTO_UPDATE"_ASKILL_SKIP_ENV = "VIBE_INSTALL_SKIP_ASKILL"_TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}@@ -8841,17 +8841,7 @@ def _invalidate_version_cache(name: str) -> None:def _cached_latest(name: str) -> str | None:- with _BACKEND_CACHE_LOCK:- cached = _BACKEND_LATEST_CACHE.get(name)- if cached:- ttl = _BACKEND_LATEST_TTL_SECONDS if cached[1] else _BACKEND_LATEST_FAILURE_TTL_SECONDS- if time.time() - cached[0] < ttl:- return cached[1]- # Network fetch outside the lock — same reasoning as ``_cached_version``.- latest = _fetch_latest_version(name)- with _BACKEND_CACHE_LOCK:- _BACKEND_LATEST_CACHE[name] = (time.time(), latest)- return latest+ return latest_version_cache.cached_latest(name, lambda: _fetch_latest_version(name))def _is_comparable_version(value: str | None) -> bool:diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.pyindex bf9d2ff9b..ac37d17f0 100644--- a/vibe/backend_model_catalog.py+++ b/vibe/backend_model_catalog.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport hashlibimport jsonimport os-import tempfileimport threadingimport timeimport urllib.error@@ -12,6 +11,7 @@ from pathlib import Pathfrom typing import Any, Iterable, Sequencefrom config import paths+from config.atomic_io import write_atomicfrom vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASES, load_catalog_modelsfrom vibe.codex_config import get_codex_home@@ -586,16 +586,7 @@ def _read_cached_remote_payload(path: Path) -> dict[str, Any]:def _write_cached_remote_payload(payload: dict[str, Any]) -> None:- cache_path = get_cached_catalog_path()- cache_path.parent.mkdir(parents=True, exist_ok=True)- fd, tmp_name = tempfile.mkstemp(prefix=f".{cache_path.name}.", suffix=".tmp", dir=str(cache_path.parent))- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- json.dump(payload, handle, indent=2, sort_keys=True)- handle.write("\n")- Path(tmp_name).replace(cache_path)- finally:- Path(tmp_name).unlink(missing_ok=True)+ write_atomic(get_cached_catalog_path(), json.dumps(payload, indent=2, sort_keys=True) + "\n")with _REMOTE_LOCK:_REMOTE_MEMORY_CACHE.clear()_REMOTE_MEMORY_CACHE.update(payload)diff --git a/vibe/claude_config.py b/vibe/claude_config.pyindex 245ade259..659c230ec 100644--- a/vibe/claude_config.py+++ b/vibe/claude_config.py@@ -23,10 +23,11 @@ from __future__ import annotationsimport jsonimport loggingimport os-import tempfilefrom pathlib import Pathfrom typing import Any, Dict, Optional+from config.atomic_io import write_atomic+logger = logging.getLogger(__name__)# Keys Avibe always keeps in ``~/.claude/settings.json`` for Claude Code.@@ -191,33 +192,6 @@ def _load_settings_for_write(path: Path) -> Dict[str, Any]:return data-def _atomic_write(path: Path, content: str, *, mode: int = 0o600) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- fd, tmp_name = tempfile.mkstemp(- prefix=f".{path.name}.",- suffix=".tmp",- dir=str(path.parent),- text=True,- )- tmp = Path(tmp_name)- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- handle.write(content)- handle.flush()- os.fsync(handle.fileno())- os.replace(tmp, path)- finally:- if tmp.exists():- try:- tmp.unlink()- except OSError: # pragma: no cover - best effort cleanup- pass- try:- path.chmod(mode)- except OSError as exc: # pragma: no cover - non-POSIX- logger.debug("chmod %s failed: %s", path, exc)--def _clean_relevant_env_values(env_values: Dict[str, str]) -> Dict[str, str]:out: Dict[str, str] = {}for key in RELEVANT_ENV_KEYS:@@ -247,10 +221,9 @@ def write_claude_oauth_settings_backup(clear_claude_oauth_settings_backup(home)returnpayload = {"version": 1, "env": cleaned}- _atomic_write(+ write_atomic(get_claude_oauth_settings_backup_path(home),json.dumps(payload, indent=2) + "\n",- mode=0o600,)@@ -333,7 +306,7 @@ def apply_claude_auth(_ensure_managed_env_values(env_block)- _atomic_write(path, json.dumps(settings, indent=2) + "\n", mode=0o600)+ write_atomic(path, json.dumps(settings, indent=2) + "\n")return {"settings_path": str(path)}@@ -382,7 +355,7 @@ def restore_claude_settings_env(env_values: Dict[str, str], home: Path | None =if not env_block:settings.pop("env", None)- _atomic_write(path, json.dumps(settings, indent=2) + "\n", mode=0o600)+ write_atomic(path, json.dumps(settings, indent=2) + "\n")def read_claude_auth_state(home: Path | None = None) -> Dict[str, Any]:diff --git a/vibe/cli.py b/vibe/cli.pyindex a4fe8a4ab..c5510650d 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -33,6 +33,7 @@ from tzlocal import get_localzone_namefrom sqlalchemy import selectfrom config import SettingsStore, paths+from config.atomic_io import write_atomicfrom config.v2_config import V2Configfrom core.scheduled_tasks import (AGENT_RUN_DELIVERY_QUEUE,@@ -9746,31 +9747,6 @@ def cmd_vault_fetch(args):return 0 if 200 <= status <= 299 else 1-def _write_private_file(path: Path, content: str) -> None:- """Atomically write ``content`` to ``path`` as a 0600 file.-- ``tempfile.mkstemp`` creates the temp file 0600 from the start, so the secret is never- momentarily world-readable even when ``path`` pre-existed with looser perms (``O_TRUNC``- would have kept the old mode until a late ``chmod``). ``os.replace`` swaps it in- atomically — a crash mid-write leaves either the old file or the complete new one, never- a truncated/partial secret.- """- import tempfile-- path.parent.mkdir(parents=True, exist_ok=True)- fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp")- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- handle.write(content)- os.replace(tmp, path)- except BaseException:- try:- os.unlink(tmp)- except OSError:- pass- raise--def cmd_vault_export(args):# Deprecated. avault (the custody core) deliberately has no plaintext-to-stdout sink —# emitting `export NAME=...` for `eval` would hand the decrypted value back to the shell@@ -9910,9 +9886,10 @@ def cmd_vault_key_export(args):blob = api.avault_key_export(passphrase)out = getattr(args, "out", None)if out:- # Create 0600 from the start (the blob holds the passphrase-wrapped key) —- # no window where it's world-readable under a permissive umask.- _write_private_file(Path(out), json.dumps(blob, indent=2) + "\n")+ # 0600 from the moment the file exists (the blob holds the passphrase-wrapped+ # key) — write_atomic leaves no window where it's world-readable, whatever the+ # umask and whatever mode ``out`` already had.+ write_atomic(Path(out), json.dumps(blob, indent=2) + "\n")_print_cli_payload("vault_key_export", written=True, path=str(out))else:print(json.dumps(blob, indent=2))diff --git a/vibe/codex_config.py b/vibe/codex_config.pyindex 5b96f9130..53df8a7f9 100644--- a/vibe/codex_config.py+++ b/vibe/codex_config.py@@ -24,6 +24,8 @@ import refrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple+from config.atomic_io import write_atomic+logger = logging.getLogger(__name__)# A TOML "bare key" is the unquoted form — anything outside this character@@ -252,24 +254,6 @@ def _dump_toml(data: Dict[str, Any]) -> str:return "\n".join(lines) + ("\n" if lines else "")-def _atomic_write(path: Path, content: str, *, mode: int = 0o600) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- tmp = path.with_suffix(path.suffix + ".tmp")- tmp.write_text(content, encoding="utf-8")- try:- os.replace(tmp, path)- finally:- if tmp.exists():- try:- tmp.unlink()- except OSError: # pragma: no cover - best effort cleanup- pass- try:- path.chmod(mode)- except OSError as exc: # pragma: no cover - non-POSIX- logger.debug("chmod %s failed: %s", path, exc)--def apply_codex_auth(*,auth_mode: str,@@ -479,8 +463,8 @@ def apply_codex_auth(if not providers:toml_data.pop("model_providers", None)- _atomic_write(auth_path, json.dumps(auth_data, indent=2) + "\n", mode=0o600)- _atomic_write(config_path, _dump_toml(toml_data), mode=0o600)+ write_atomic(auth_path, json.dumps(auth_data, indent=2) + "\n")+ write_atomic(config_path, _dump_toml(toml_data))return {"notices": notices}diff --git a/vibe/global_agents_md.py b/vibe/global_agents_md.pyindex 7817f36a8..2b0e4f5fc 100644--- a/vibe/global_agents_md.py+++ b/vibe/global_agents_md.py@@ -23,11 +23,10 @@ accepting an optional ``home`` override so they stay unit-testable in isolationfrom __future__ import annotations-import os-import tempfilefrom collections.abc import Iterablefrom pathlib import Path+from config.atomic_io import write_atomicfrom modules.agents.catalog import AGENT_BACKENDS, is_agent_backendfrom vibe.claude_config import get_claude_homefrom vibe.codex_config import get_codex_home@@ -100,37 +99,13 @@ def read_all_global_agents_md(home: Path | None = None) -> list[dict]:return [read_global_agents_md(backend, home) for backend in AGENT_BACKENDS]-def _atomic_write(path: Path, content: str) -> None:- """Write *content* to *path* atomically, creating parent dirs as needed.-- A temp file in the target directory is swapped in with ``os.replace`` so a- failed write never truncates an existing global instructions file.-- Writes *through* a symlink to its real target: a user who symlinks their- global prompt file into a shared dotfiles repo (e.g. ``~/.claude/CLAUDE.md``- -> ``~/dotfiles/CLAUDE.md``) keeps the link intact, since replacing it with a- regular file would silently break that sharing setup.- """- target = Path(os.path.realpath(path))- target.parent.mkdir(parents=True, exist_ok=True)- fd, tmp_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=str(target.parent), text=True)- tmp = Path(tmp_name)- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- handle.write(content)- os.replace(tmp, target)- finally:- if tmp.exists():- try:- tmp.unlink()- except OSError: # pragma: no cover - best effort cleanup- pass--def write_global_agents_md(backend: str, content: str, home: Path | None = None) -> dict:"""Write *content* to *backend*'s global instructions file and re-read it."""path = global_instruction_path(backend, home)- _atomic_write(path, content)+ # ``follow_symlinks`` keeps a dotfiles setup intact: a user who links+ # ``~/.claude/CLAUDE.md`` -> ``~/dotfiles/CLAUDE.md`` expects an edit here to+ # land in the repo, not to replace the link with a regular file.+ write_atomic(path, content, follow_symlinks=True)return read_global_agents_md(backend, home)diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex 75fe5025c..7917ee1fc 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -1,12 +1,11 @@from __future__ import annotations-import os-import tempfilefrom pathlib import Pathfrom typing import Any, Iterableimport yaml+from config.atomic_io import write_atomicfrom vibe.model_hub_runtime.state import EngineStateError, EngineStateStore, RuntimeSecrets, SourceRecord@@ -110,17 +109,8 @@ def _append_source(payload: dict[str, Any], source: SourceRecord, store: EngineSdef _secure_write_yaml(path: Path, payload: dict[str, Any]) -> None:+ # The file is 0600 by ``write_atomic``; the directory is this function's own+ # concern, because the config it holds names an upstream API key.path.parent.mkdir(parents=True, exist_ok=True)path.parent.chmod(0o700)- descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)- temporary = Path(temporary_name)- try:- with os.fdopen(descriptor, "w", encoding="utf-8") as handle:- yaml.safe_dump(payload, handle, sort_keys=False, default_flow_style=False)- handle.flush()- os.fsync(handle.fileno())- temporary.chmod(0o600)- temporary.replace(path)- path.chmod(0o600)- finally:- temporary.unlink(missing_ok=True)+ write_atomic(path, yaml.safe_dump(payload, sort_keys=False, default_flow_style=False))diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex b2597112f..c1eea612a 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -1,17 +1,16 @@from __future__ import annotationsimport json-import osimport reimport secretsimport shutilimport stat-import tempfileimport threadingfrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any, Sequence+from config.atomic_io import write_atomicfrom config.v2_config import normalize_model_hub_base_url@@ -457,20 +456,10 @@ class EngineStateStore:@classmethoddef _secure_write_json(cls, path: Path, payload: dict[str, Any]) -> None:+ # The file is 0600 by ``write_atomic``; the directory is this store's own+ # concern, since it holds the engine's secrets alongside its state.cls._ensure_private_dir(path.parent)- descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)- temporary = Path(temporary_name)- try:- with os.fdopen(descriptor, "w", encoding="utf-8") as handle:- json.dump(payload, handle, sort_keys=True)- handle.write("\n")- handle.flush()- os.fsync(handle.fileno())- temporary.chmod(0o600)- temporary.replace(path)- path.chmod(0o600)- finally:- temporary.unlink(missing_ok=True)+ write_atomic(path, json.dumps(payload, sort_keys=True) + "\n")@staticmethoddef _ensure_private_dir(path: Path) -> None:diff --git a/vibe/permissions.py b/vibe/permissions.pyindex b41f5e623..fc96df163 100644--- a/vibe/permissions.py+++ b/vibe/permissions.py@@ -6,9 +6,7 @@ from dataclasses import dataclassfrom datetime import datetime, timezoneimport jsonimport logging-import osfrom pathlib import Path-import tempfileimport threadingimport timefrom typing import Any, Callable, Mapping, NoReturn@@ -17,6 +15,7 @@ from urllib.parse import quote, urlsplitimport requestsfrom config import paths+from config.atomic_io import write_atomicfrom config.v2_config import V2Config, config_file_lockfrom sqlalchemy import select@@ -573,26 +572,10 @@ def _cache_file_lock(path: Path):def _atomic_write_json(path: Path, value: Any) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- fd, temporary_name = tempfile.mkstemp(- dir=path.parent,- prefix=f".{path.name}.",- )- try:- # mkstemp creates the file owner-private without relying on Unix-only APIs.- with os.fdopen(fd, "w", encoding="utf-8") as handle:- fd = -1- json.dump(value, handle, ensure_ascii=True, separators=(",", ":"))- handle.flush()- os.fsync(handle.fileno())- os.replace(temporary_name, path)- finally:- if fd >= 0:- os.close(fd)- try:- os.unlink(temporary_name)- except FileNotFoundError:- pass+ # Compact and ASCII-only: nothing reads these projections by eye, and the+ # cache is re-read on every permission check, so bytes matter more than+ # legibility. The swap itself belongs to ``write_atomic``.+ write_atomic(path, json.dumps(value, ensure_ascii=True, separators=(",", ":")))def _write_cache(diff --git a/vibe/runtime.py b/vibe/runtime.pyindex c9c1be7fd..12912dc7a 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -10,7 +10,6 @@ import shutilimport socketimport subprocessimport sys-import tempfileimport threadingimport timeimport urllib.error@@ -22,6 +21,7 @@ from typing import NamedTupleimport psutilfrom config import paths+from config.atomic_io import write_atomicfrom config.v2_config import (AgentsConfig,ClaudeConfig,@@ -200,24 +200,16 @@ def ensure_config():def write_json(path, payload):- # Write atomically (unique temp file in the same dir + os.replace) so a- # concurrent reader never sees a half-written file. The regression supervisor- # polls status files (e.g. restart_status.json) while restart jobs rewrite- # them, and a partial read would otherwise surface as None and be misread as- # "no restart in progress". The temp name must be unique *per call* — several- # threads in this process can write the same status path at once (e.g.- # overlapping FastAPI control requests dispatched through a threadpool), and a- # shared temp name would let one writer's os.replace yank the file from under- # another.- fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")- tmp = Path(tmp_name)- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- handle.write(json.dumps(payload, indent=2))- os.replace(tmp, path)- except OSError:- tmp.unlink(missing_ok=True)- raise+ # ``write_atomic`` owns the swap so a concurrent reader never sees a+ # half-written file. The regression supervisor polls status files (e.g.+ # restart_status.json) while restart jobs rewrite them, and a partial read+ # would otherwise surface as None and be misread as "no restart in+ # progress". Its per-call unique temp name is what makes that safe here:+ # several threads in this process can write the same status path at once+ # (e.g. overlapping FastAPI control requests dispatched through a+ # threadpool), and a shared temp name would let one writer's os.replace+ # yank the file from under another.+ write_atomic(Path(path), json.dumps(payload, indent=2))def read_json(path):