Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix: harden self-mod backup writes
Ruben Lütke50d084b29082
diff --git a/docs/LLM-CONTEXT.md b/docs/LLM-CONTEXT.mdindex 2c1f0eb542..408b806416 100644--- a/docs/LLM-CONTEXT.md+++ b/docs/LLM-CONTEXT.md@@ -354,7 +354,9 @@ Voice/chat must never accept secrets (AP-2: STT log leak vector).3. Read old value via dotted path4. In-memory mutate5. **Pre-validate** via `JarvisConfig.model_validate(doc.unwrap())`-6. Backup to `<config>.parent/.backups/jarvis.toml.<iso>.bak` (**outside watchdog scope, AP-13**)+6. Backup to `JARVIS_DATA_DIR/backups/self_mod/`, or the platform user-data+ fallback (**outside watchdog scope, AP-13**). The former+ `<config>.parent/.backups/` location remains read-only upgrade compatibility.7. Tempfile + `os.replace` atomic swap8. **Synchronous reload-test** via `ConfigLoader.load()` (AP-14 forbids watchdog-driven verify)9. `ConfigReloaded` bus eventdiff --git a/docs/self_mod.md b/docs/self_mod.mdindex 43f8116b5b..a082dee884 100644--- a/docs/self_mod.md+++ b/docs/self_mod.md@@ -78,9 +78,13 @@ a "***" badge instead of cleartext.## 4. Rollback behavior-Before every mutation the `AtomicConfigWriter` creates a backup in-`<jarvis.toml.parent>/.backups/jarvis.toml.<iso>.bak`. If, after the-write, the reload test (`ConfigLoader.load(jarvis.toml)`) crashes — e.g.+Before every mutation the `AtomicConfigWriter` creates a backup under+`JARVIS_DATA_DIR/backups/self_mod/`, or under the platform user-data directory+when `JARVIS_DATA_DIR` is not set. This keeps backup writes outside the config+watchdog scope. Backups from older installations remain discoverable and+restorable from `<jarvis.toml.parent>/.backups/`, but new backups are never+written there. If, after the write, the reload test+(`ConfigLoader.load(jarvis.toml)`) crashes — e.g.because a subtle schema error slipped through pre-validate — the backup isrestored **automatically** and a `ReloadError` is raised. The user hearsa TTS message "Konnte nicht gespeichert werden, hab den vorherigen <!-- i18n-allow -->diff --git a/jarvis/core/self_mod/errors.py b/jarvis/core/self_mod/errors.pyindex 7e333da30d..4541272acb 100644--- a/jarvis/core/self_mod/errors.py+++ b/jarvis/core/self_mod/errors.py@@ -63,5 +63,6 @@ class RollbackError(SelfModError):This is the most severe error state: jarvis.toml may have been writtenin a corrupt state AND the restore also failed. The caller must manually- recover from `<jarvis.toml.parent>/.backups/`.+ recover from `<user-data-dir>/backups/self_mod/`. Backups created by older+ installations remain readable under `<jarvis.toml.parent>/.backups/`."""diff --git a/jarvis/core/self_mod/writer.py b/jarvis/core/self_mod/writer.pyindex 024d144ad2..bce678be50 100644--- a/jarvis/core/self_mod/writer.py+++ b/jarvis/core/self_mod/writer.py@@ -8,7 +8,7 @@ Pipeline per `mutate(request)` call (all steps mandatory, order fixed):3. Read `old_value` via dotted path.4. Apply mutation in-memory.5. Pre-validate: full `JarvisConfig.model_validate(doc.unwrap())`.- 6. Backup to `<config>.parent / .backups / jarvis.toml.<iso>.bak`.+ 6. Backup outside the config watchdog scope under the user data directory.7. Atomic write: `tempfile.mkstemp` in the same directory,`fsync` the tempfile contents, `os.replace` as the atomic swap.8. Reload test: synchronous `ConfigLoader.load()` call. On crash:@@ -53,6 +53,7 @@ from jarvis.core.config import (resolve_config_path,)from jarvis.core.events import ConfigReloaded+from jarvis.core.paths import user_data_dirfrom .audit import SelfModAuditfrom .errors import (@@ -77,10 +78,19 @@ from .schema import (_LOG = logging.getLogger(__name__)-# Plan-§AD-6 / §7.2: Backup directory lives directly next to `jarvis.toml`.-DEFAULT_BACKUP_SUBDIR = ".backups"+# Plan-§AD-6 / §7.2: backups stay outside the config watchdog scope.+DEFAULT_BACKUP_SUBDIR = "backups/self_mod"+_LEGACY_BACKUP_SUBDIR = ".backups"BACKUP_FILE_GLOB = f"{CONFIG_FILE_NAME}.*.bak"BACKUP_TS_FORMAT = "%Y%m%dT%H%M%S_%fZ"+_ATOMIC_REPLACE_RETRY_DELAYS_S = (0.0, 0.025, 0.05, 0.1, 0.2, 0.4)+++def _default_backup_dir() -> Path:+ """Return a portable backup path outside the config watchdog scope."""+ configured = os.environ.get("JARVIS_DATA_DIR", "").strip()+ base = Path(configured).expanduser() if configured else user_data_dir()+ return base / DEFAULT_BACKUP_SUBDIRclass AtomicConfigWriter:@@ -104,10 +114,16 @@ class AtomicConfigWriter:self._config_path: Path = (Path(config_path) if config_path is not None else resolve_config_path())+ using_default_backup_dir = backup_dir is Noneself._backup_dir: Path = (Path(backup_dir)if backup_dir is not None- else self._config_path.parent / DEFAULT_BACKUP_SUBDIR+ else _default_backup_dir()+ )+ self._legacy_backup_dirs: tuple[Path, ...] = (+ (self._config_path.parent / _LEGACY_BACKUP_SUBDIR,)+ if using_default_backup_dir+ else ())if max_backups < backup_min_keep:raise ValueError(@@ -202,15 +218,22 @@ class AtomicConfigWriter:unlink files. We therefore snapshot in a single pass and skipmissing files (TOCTOU-tolerant)."""- if not self._backup_dir.exists():- return []- snapshot: list[tuple[Path, float, int]] = []- for path in self._backup_dir.glob(BACKUP_FILE_GLOB):- try:- stat = path.stat()- except OSError:+ snapshot_by_name: dict[str, tuple[Path, float, int]] = {}+ for root in (self._backup_dir, *self._legacy_backup_dirs):+ if not root.exists():continue- snapshot.append((path, stat.st_mtime, stat.st_size))+ for path in root.glob(BACKUP_FILE_GLOB):+ try:+ stat = path.stat()+ except OSError:+ continue+ # The new, out-of-watchdog location wins if an old backup has+ # the same generated filename. Legacy directories are read-only+ # compatibility inputs and never receive new writes or GC.+ snapshot_by_name.setdefault(+ path.name, (path, stat.st_mtime, stat.st_size)+ )+ snapshot = list(snapshot_by_name.values())snapshot.sort(key=lambda triplet: triplet[1], reverse=True)now = time.time()result: list[BackupRef] = []@@ -234,21 +257,26 @@ class AtomicConfigWriter:restore run under `_LOCK` so that a concurrent GC cannot removethe file between check and use."""- candidate = (self._backup_dir / backup_filename).resolve()- try:- candidate.relative_to(self._backup_dir.resolve())- except ValueError as exc:+ if Path(backup_filename).name != backup_filename or backup_filename in {+ "",+ ".",+ "..",+ }:raise BackupError(f"Backup path '{backup_filename}' lies outside the "- f"backup directory {self._backup_dir}"- ) from exc+ "configured backup directories"+ )with type(self)._LOCK:- if not candidate.is_file():- raise BackupError(- f"Backup '{backup_filename}' does not exist"- )- self._restore(candidate)- return candidate+ for root in (self._backup_dir, *self._legacy_backup_dirs):+ candidate = (root / backup_filename).resolve()+ try:+ candidate.relative_to(root.resolve())+ except ValueError:+ continue+ if candidate.is_file():+ self._restore(candidate)+ return candidate+ raise BackupError(f"Backup '{backup_filename}' does not exist")# ------------------------------------------------------------------# Pipeline@@ -463,7 +491,21 @@ class AtomicConfigWriter:if was_readonly:os.chmod(target, mode | stat.S_IWRITE)try:- os.replace(tmp_path, target)+ last_error: PermissionError | None = None+ for delay_s in _ATOMIC_REPLACE_RETRY_DELAYS_S:+ if delay_s:+ time.sleep(delay_s)+ if was_readonly and target.exists():+ current = target.stat().st_mode+ if not current & stat.S_IWRITE:+ os.chmod(target, current | stat.S_IWRITE)+ try:+ os.replace(tmp_path, target)+ return+ except PermissionError as exc:+ last_error = exc+ if last_error is not None:+ raise last_errorfinally:# On success ``target`` is the freshly swapped file; on failure it is# the still-present old file. Either way re-arm the read-only flag sodiff --git a/tests/unit/self_mod/test_writer.py b/tests/unit/self_mod/test_writer.pyindex dfcf0ba94e..0b2bfc508f 100644--- a/tests/unit/self_mod/test_writer.py+++ b/tests/unit/self_mod/test_writer.py@@ -390,6 +390,37 @@ class TestReloadFailRollback:class TestAtomicWrite:+ def test_retries_transient_replace_permission_error(+ self,+ fixture_path: Path,+ tmp_path: Path,+ audit_log: SelfModAudit,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """A short-lived Windows sharing lock must not reject a safe write."""+ writer = AtomicConfigWriter(+ config_path=fixture_path,+ backup_dir=tmp_path / "backups",+ audit=audit_log,+ config_loader=_isolated_loader,+ )+ real_replace = os.replace+ attempts = 0++ def flaky_replace(src: str | Path, dst: str | Path) -> None:+ nonlocal attempts+ attempts += 1+ if attempts < 3:+ raise PermissionError("simulated transient sharing lock")+ real_replace(src, dst)++ monkeypatch.setattr(os, "replace", flaky_replace)++ result = writer.mutate(_make_request("tts.provider", "elevenlabs"))++ assert result.ok is True+ assert attempts == 3+def test_no_orphan_tmp_after_failure(self,fixture_path: Path,@@ -620,6 +651,78 @@ class TestConcurrencySamePath:class TestListBackups:+ def test_default_backup_dir_is_outside_config_watchdog_scope(+ self,+ fixture_path: Path,+ tmp_path: Path,+ audit_log: SelfModAudit,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ data_root = tmp_path / "jarvis-data"+ monkeypatch.setenv("JARVIS_DATA_DIR", str(data_root))++ writer = AtomicConfigWriter(+ config_path=fixture_path,+ audit=audit_log,+ config_loader=_isolated_loader,+ )++ assert writer.backup_dir == data_root / "backups" / "self_mod"+ assert writer.backup_dir.parent != fixture_path.parent++ def test_default_user_data_fallback_creates_discoverable_backup(+ self,+ fixture_path: Path,+ tmp_path: Path,+ audit_log: SelfModAudit,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ data_root = tmp_path / "fallback-user-data"+ monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)+ monkeypatch.setattr(+ "jarvis.core.self_mod.writer.user_data_dir", lambda: data_root+ )+ writer = AtomicConfigWriter(+ config_path=fixture_path,+ audit=audit_log,+ config_loader=_isolated_loader,+ )++ writer.mutate(_make_request("tts.speed", 1.25))++ assert writer.backup_dir == data_root / "backups" / "self_mod"+ assert len(writer.list_backups()) == 1++ def test_legacy_backup_remains_listed_and_restorable_after_upgrade(+ self,+ fixture_path: Path,+ tmp_path: Path,+ audit_log: SelfModAudit,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ legacy_dir = fixture_path.parent / ".backups"+ legacy_writer = AtomicConfigWriter(+ config_path=fixture_path,+ backup_dir=legacy_dir,+ audit=audit_log,+ config_loader=_isolated_loader,+ )+ legacy_writer.mutate(_make_request("tts.speed", 1.5))+ legacy_filename = legacy_writer.list_backups()[0].filename++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path / "new-user-data"))+ upgraded_writer = AtomicConfigWriter(+ config_path=fixture_path,+ audit=audit_log,+ config_loader=_isolated_loader,+ )++ listed = upgraded_writer.list_backups()+ assert [backup.filename for backup in listed] == [legacy_filename]+ restored = upgraded_writer.rollback(legacy_filename)+ assert restored.parent == legacy_dir.resolve()+ assert _isolated_loader(fixture_path).tts.speed == 1.0+def test_returns_empty_for_no_backups(self,fixture_path: Path,