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
fix(memory): safely delete inaccessible confined directories (#1378)
rkrkrkk6fa57ef5764b
diff --git a/core/memory/confined_filesystem.py b/core/memory/confined_filesystem.pyindex c42099576..87d4f9e98 100644--- a/core/memory/confined_filesystem.py+++ b/core/memory/confined_filesystem.py@@ -2,9 +2,12 @@from __future__ import annotations+import ctypes+import errnoimport osimport sqlite3import stat+import sysfrom collections import OrderedDictfrom collections.abc import Callable, Iteratorfrom contextlib import contextmanager@@ -15,9 +18,21 @@ from typing import Sequence_DIRECTORY_ORDER_INSERT_BATCH_SIZE = 256_DIRECTORY_DESCRIPTOR_CACHE_SIZE = 48+_LINUX_OPENAT2_SYSCALL = 437+_RESOLVE_NO_XDEV = 0x01+_RESOLVE_NO_SYMLINKS = 0x04+_RESOLVE_BENEATH = 0x08PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS = 5.0+class _LinuxOpenHow(ctypes.Structure):+ _fields_ = [+ ("flags", ctypes.c_uint64),+ ("mode", ctypes.c_uint64),+ ("resolve", ctypes.c_uint64),+ ]++class ConfinedFilesystemError(RuntimeError):"""A confined filesystem operation refused an unsafe path or entry."""@@ -702,6 +717,7 @@ class _DirectoryDescriptorCache:def __init__(self, root_fd: int) -> None:self._root_fd = root_fd+ self._root_device = os.fstat(root_fd).st_devself._descriptors: OrderedDict[int, tuple[_RelativeNode, int]] = OrderedDict()def __enter__(self) -> _DirectoryDescriptorCache:@@ -729,12 +745,16 @@ class _DirectoryDescriptorCache:try:for component_node in reversed(trail):try:- next_descriptor = os.open(+ next_descriptor = _open_directory_without_mount_crossing(+ current,component_node.name,strict_directory_open_flags(),- dir_fd=current,)except OSError as error:+ if error.errno == errno.EXDEV:+ raise ConfinedFilesystemError(+ "confined removal parent crosses a filesystem boundary"+ ) from errorraise ConfinedFilesystemError("confined removal parent cannot be opened safely") from error@@ -742,6 +762,7 @@ class _DirectoryDescriptorCache:current = next_descriptorinfo = os.fstat(current)_require_private_directory(info, "confined removal parent")+ _require_device(info, self._root_device, "confined removal parent")self._remember(component_node, current)return currentexcept BaseException:@@ -774,6 +795,7 @@ def remove_confined_path(try:current = os.open(home, strict_directory_open_flags())anchored.append(current)+ root_device = os.fstat(current).st_dev# ``paths.ensure_data_dirs`` historically created the home with the# process umask (commonly 0755). We own the descriptor and pin it with# O_NOFOLLOW, so harden that app-created mode in place before traversing@@ -781,16 +803,25 @@ def remove_confined_path(_harden_private_directory_fd(current, "confinement root", sync=False)for component in relative.parts[:-1]:try:- next_descriptor = os.open(+ next_descriptor = _open_directory_without_mount_crossing(+ current,component,strict_directory_open_flags(),- dir_fd=current,)except FileNotFoundError:_fsync_anchored_deletion(anchored)return+ except OSError as error:+ if error.errno == errno.EXDEV:+ raise ConfinedFilesystemError(+ "confined directory crosses a filesystem boundary"+ ) from error+ raise ConfinedFilesystemError(+ "confined directory cannot be opened safely"+ ) from errorcurrent = next_descriptoranchored.append(current)+ _require_device(os.fstat(current), root_device, "confined directory")_harden_private_directory_fd(current, "confined directory", sync=False)remove_anchored_entry(current, relative.parts[-1], progress=progress)_fsync_anchored_deletion(anchored)@@ -843,6 +874,7 @@ def _remove_entry_at(expected_identity: tuple[int, int] | None = None,progress: ConfinedRemovalProgress | None = None,) -> None:+ root_device = os.fstat(parent_fd).st_devtry:initial = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)except FileNotFoundError:@@ -859,6 +891,8 @@ def _remove_entry_at(returnif not stat.S_ISDIR(initial.st_mode):raise ConfinedFilesystemError("confined removal refuses special files")+ _require_device(initial, root_device, "confined removal directory")+ root_identity = expected_identity or (initial.st_dev, initial.st_ino)root_node = _RelativeNode(None, name)stack: list[_RemovalFrame | _RelativeNode] = [root_node]@@ -882,8 +916,7 @@ def _remove_entry_at(continueif (item is root_node- and expected_identity is not None- and (before.st_dev, before.st_ino) != expected_identity+ and (before.st_dev, before.st_ino) != root_identity):raise ConfinedFilesystemError("confined entry changed during removal"@@ -897,27 +930,19 @@ def _remove_entry_at(raise ConfinedFilesystemError("confined removal refuses special files")- if item is root_node and expected_identity is not None:- _require_directory(before, "confined removal directory")- else:- _require_private_directory(- before,- "confined removal directory",- )- child_fd = os.open(+ _require_directory(before, "confined removal directory")+ _require_device(+ before,+ root_device,+ "confined removal directory",+ )+ child_fd = _open_removal_directory(+ node_parent_fd,item.name,- strict_directory_open_flags(),- dir_fd=node_parent_fd,+ before,+ root_device,)try:- opened = os.fstat(child_fd)- if (opened.st_dev, opened.st_ino) != (- before.st_dev,- before.st_ino,- ):- raise ConfinedFilesystemError(- "confined directory changed during removal"- )_harden_private_directory_fd(child_fd,"confined removal directory",@@ -963,6 +988,168 @@ def _remove_entry_at(os.close(node_parent_fd)+def _open_removal_directory(+ parent_fd: int,+ name: str,+ before: os.stat_result,+ root_device: int,+) -> int:+ try:+ descriptor = _open_directory_without_mount_crossing(+ parent_fd,+ name,+ strict_directory_open_flags(),+ )+ except OSError as error:+ if error.errno == errno.EXDEV:+ raise ConfinedFilesystemError(+ "confined removal directory crosses a filesystem boundary"+ ) from error+ if (+ error.errno not in {errno.EACCES, errno.EPERM}+ or stat.S_IMODE(before.st_mode) == 0o700+ ):+ raise ConfinedFilesystemError(+ "confined removal directory cannot be opened safely"+ ) from error+ _harden_inaccessible_removal_directory(+ parent_fd,+ name,+ before,+ root_device,+ )+ try:+ descriptor = _open_directory_without_mount_crossing(+ parent_fd,+ name,+ strict_directory_open_flags(),+ )+ except OSError as retry_error:+ if retry_error.errno == errno.EXDEV:+ raise ConfinedFilesystemError(+ "confined removal directory crosses a filesystem boundary"+ ) from retry_error+ raise ConfinedFilesystemError(+ "confined removal directory cannot be opened safely"+ ) from retry_error+ opened = os.fstat(descriptor)+ if (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino):+ os.close(descriptor)+ raise ConfinedFilesystemError("confined directory changed during removal")+ try:+ _require_directory(opened, "confined removal directory")+ _require_device(opened, root_device, "confined removal directory")+ except BaseException:+ os.close(descriptor)+ raise+ return descriptor+++def _open_directory_without_mount_crossing(+ parent_fd: int,+ name: str,+ flags: int,+) -> int:+ if sys.platform != "linux":+ return os.open(name, flags, dir_fd=parent_fd)++ how = _LinuxOpenHow(+ flags=flags,+ mode=0,+ resolve=_RESOLVE_NO_XDEV | _RESOLVE_NO_SYMLINKS | _RESOLVE_BENEATH,+ )+ libc = ctypes.CDLL(None, use_errno=True)+ descriptor = libc.syscall(+ ctypes.c_long(_LINUX_OPENAT2_SYSCALL),+ ctypes.c_int(parent_fd),+ ctypes.c_char_p(os.fsencode(name)),+ ctypes.byref(how),+ ctypes.c_size_t(ctypes.sizeof(how)),+ )+ if descriptor < 0:+ error_number = ctypes.get_errno()+ raise OSError(error_number, os.strerror(error_number), name)+ return int(descriptor)+++def _harden_inaccessible_removal_directory(+ parent_fd: int,+ name: str,+ before: os.stat_result,+ root_device: int,+) -> None:+ path_descriptor_flag = getattr(os, "O_PATH", 0)+ if not path_descriptor_flag:+ raise ConfinedFilesystemError(+ "confined removal directory cannot be opened safely"+ )++ # O_PATH pins even a mode-000 directory; procfs then applies chmod to that+ # inode instead of resolving the possibly swapped parent entry.+ try:+ anchor = _open_directory_without_mount_crossing(+ parent_fd,+ name,+ path_descriptor_flag+ | required_no_follow_flag()+ | int(getattr(os, "O_DIRECTORY", 0))+ | int(getattr(os, "O_CLOEXEC", 0)),+ )+ except OSError as error:+ if error.errno == errno.EXDEV:+ raise ConfinedFilesystemError(+ "confined removal directory crosses a filesystem boundary"+ ) from error+ raise ConfinedFilesystemError(+ "confined removal directory cannot be anchored safely"+ ) from error+ try:+ anchored = os.fstat(anchor)+ _require_removal_directory_identity(anchored, before, root_device)+ try:+ os.chmod(f"/proc/self/fd/{anchor}", 0o700)+ except (NotImplementedError, OSError, ValueError) as error:+ raise ConfinedFilesystemError(+ "confined removal directory cannot be hardened safely"+ ) from error+ _require_removal_directory_identity(+ os.fstat(anchor),+ before,+ root_device,+ require_private=True,+ )+ finally:+ os.close(anchor)++ try:+ hardened = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)+ except OSError as error:+ raise ConfinedFilesystemError(+ "confined directory changed during removal"+ ) from error+ _require_removal_directory_identity(+ hardened,+ before,+ root_device,+ require_private=True,+ )+++def _require_removal_directory_identity(+ info: os.stat_result,+ before: os.stat_result,+ root_device: int,+ *,+ require_private: bool = False,+) -> None:+ _require_directory(info, "confined removal directory")+ _require_device(info, root_device, "confined removal directory")+ if (info.st_dev, info.st_ino) != (before.st_dev, before.st_ino):+ raise ConfinedFilesystemError("confined directory changed during removal")+ if require_private:+ _require_exact_private_directory(info, "confined removal directory")++def _relative_to_home(path: Path, home: Path) -> Path:try:return path.relative_to(home)@@ -1010,6 +1197,11 @@ def _require_directory(info: os.stat_result, label: str) -> None:_require_owned(info, label)+def _require_device(info: os.stat_result, device: int, label: str) -> None:+ if info.st_dev != device:+ raise ConfinedFilesystemError(f"{label} crosses a filesystem boundary")++def _require_private_directory(info: os.stat_result, label: str) -> None:_require_directory(info, label)if stat.S_IMODE(info.st_mode) & 0o077:diff --git a/core/memory/process.py b/core/memory/process.pyindex 859df7533..64a2b66ae 100644--- a/core/memory/process.py+++ b/core/memory/process.py@@ -2330,6 +2330,7 @@ def _prepare_memory_child_directories(memory_dir / ".child-home",memory_dir / ".child-home" / ".cache",memory_dir / ".child-home" / ".config",+ memory_dir / ".child-home" / ".local",memory_dir / ".child-home" / ".local" / "share",memory_dir / ".child-home" / ".local" / "state",memory_dir / "generated",diff --git a/tests/scenarios/memory_factory_reset/catalog.yaml b/tests/scenarios/memory_factory_reset/catalog.yamlindex 35b3ec94c..03d266bab 100644--- a/tests/scenarios/memory_factory_reset/catalog.yaml+++ b/tests/scenarios/memory_factory_reset/catalog.yaml@@ -47,6 +47,15 @@ scenarios:given: A capture observes the old runtime before Factory Reset publishes a replacementwhen: The replacement gate opens after the fresh aggregate is publishedthen: The capture is rejected without writing to either runtime+ - id: MEMORY-FACTORY-005+ name: Retry deletes a same-owner inaccessible child-home tree+ status: covered+ kind: service_boundary+ layer: scenario+ test: tests/scenarios/memory_factory_reset/test_memory_factory_reset_scenarios.py::test_memory_factory_005_retry_deletes_owned_inaccessible_child_home+ given: On an O_PATH host, a durable reset retry encounters a real child-home tree containing a same-owner 0000 directory+ when: The Controller replacement gate retries Factory Reset+ then: The directory is hardened through its pinned descriptor and both mutable roots are deleted- id: MEMORY-FACTORY-101name: Invalid artifact disables resetstatus: covereddiff --git a/tests/scenarios/memory_factory_reset/test_memory_factory_reset_scenarios.py b/tests/scenarios/memory_factory_reset/test_memory_factory_reset_scenarios.pyindex 596b53eb7..cdc764ace 100644--- a/tests/scenarios/memory_factory_reset/test_memory_factory_reset_scenarios.py+++ b/tests/scenarios/memory_factory_reset/test_memory_factory_reset_scenarios.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import osfrom dataclasses import replacefrom pathlib import Pathfrom types import SimpleNamespace@@ -238,6 +239,40 @@ async def test_memory_factory_004_capture_queued_for_reset_cannot_use_fresh_runtassert fresh_module.calls == 0[email protected](not hasattr(os, "O_PATH"), reason="requires an O_PATH inode anchor")+async def test_memory_factory_005_retry_deletes_owned_inaccessible_child_home(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """MEMORY-FACTORY-005: retry hardens and deletes a real inaccessible tree."""+ _create_roots(tmp_path)+ local = tmp_path / "memory" / ".child-home" / ".local"+ (local / "share").mkdir(mode=0o700, parents=True)+ (local / "share" / "cache.db").write_bytes(b"memory")+ local.chmod(0o000)+ old = _Runtime(tmp_path)+ controller = _controller(old)+ controller.config.memory = replace(+ controller.config.memory,+ recovery_intent="factory_reset",+ )+ fresh = _FreshRuntime(tmp_path)+ monkeypatch.setattr(+ "core.memory.runtime.create_memory_runtime",+ lambda *args, **kwargs: fresh,+ )++ result = await controller._factory_reset_memory_once()++ assert result["ok"] is True+ assert result["data_deleted"] is True+ assert result["data_remaining"] is False+ assert controller.config.memory.recovery_intent is None+ assert not (tmp_path / "memory").exists()+ assert not (tmp_path / "state" / "memory").exists()++@pytest.mark.asyncioasync def test_memory_factory_101_disabled_reset_fails_closed_without_deletion(tmp_path: Path) -> None:"""MEMORY-FACTORY-101: an invalid artifact leaves both roots untouched."""diff --git a/tests/test_memory_confined_filesystem.py b/tests/test_memory_confined_filesystem.pyindex 192980962..21511cf19 100644--- a/tests/test_memory_confined_filesystem.py+++ b/tests/test_memory_confined_filesystem.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import errnoimport osimport sqlite3import stat@@ -354,6 +355,39 @@ def test_remove_confined_path_refuses_to_follow_a_swapped_directory(assert victim.read_text(encoding="utf-8") == "outside must survive"+def test_remove_confined_path_rejects_root_swap_before_directory_open(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "managed"+ target.mkdir(mode=0o700)+ held = home / "held-managed"++ from core.memory import confined_filesystem++ real_connect = confined_filesystem.sqlite3.connect+ swapped = False++ def swap_before_walk(*args, **kwargs):+ nonlocal swapped+ if not swapped:+ swapped = True+ target.rename(held)+ target.mkdir(mode=0o700)+ return real_connect(*args, **kwargs)++ monkeypatch.setattr(confined_filesystem.sqlite3, "connect", swap_before_walk)++ with pytest.raises(ConfinedFilesystemError, match="changed during removal"):+ remove_confined_path(home, target)++ assert swapped+ assert target.is_dir()+ assert held.is_dir()++def test_remove_confined_regular_file_does_not_initialize_directory_ordering(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -565,6 +599,409 @@ def test_confined_replace_and_cleanup_accept_owner_only_directory_modes(assert not target.exists()[email protected]("mode", (0o500, 0o755, 0o777))+def test_remove_confined_path_hardens_owned_directories(+ tmp_path: Path,+ mode: int,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ nested = target / "nested"+ nested.mkdir(mode=0o700)+ nested.chmod(mode)++ remove_confined_path(home, target)++ assert not target.exists()++[email protected](not hasattr(os, "O_PATH"), reason="requires an O_PATH inode anchor")+def test_remove_confined_path_hardens_an_inaccessible_owned_directory(+ tmp_path: Path,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ nested = target / "nested"+ nested.mkdir(mode=0o700)+ nested.chmod(0o000)++ remove_confined_path(home, target)++ assert not target.exists()+++def test_remove_confined_path_never_chmods_a_swapped_entry_without_an_anchor(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ locked = target / "locked"+ locked.mkdir(mode=0o700)+ locked.chmod(0o000)+ held = target / "held-locked"++ from core.memory import confined_filesystem++ real_open = confined_filesystem.os.open+ real_chmod = confined_filesystem.os.chmod+ path_chmod_called = False++ def refuse_inaccessible_directory(path, flags, *args, **kwargs):+ if path == locked.name and kwargs.get("dir_fd") is not None:+ raise PermissionError(errno.EACCES, "directory is inaccessible")+ return real_open(path, flags, *args, **kwargs)++ def swap_before_path_chmod(path, mode, *args, **kwargs):+ nonlocal path_chmod_called+ if path == locked.name and kwargs.get("dir_fd") is not None:+ path_chmod_called = True+ locked.rename(held)+ locked.mkdir(mode=0o755)+ return real_chmod(path, mode, *args, **kwargs)++ monkeypatch.delattr(confined_filesystem.os, "O_PATH", raising=False)+ monkeypatch.setattr(confined_filesystem.os, "open", refuse_inaccessible_directory)+ monkeypatch.setattr(confined_filesystem.os, "chmod", swap_before_path_chmod)+ try:+ with pytest.raises(ConfinedFilesystemError, match="cannot be opened safely"):+ remove_confined_path(home, target)+ finally:+ if held.exists():+ real_chmod(held, 0o700)+ real_chmod(locked, 0o700)++ assert not path_chmod_called+ assert stat.S_IMODE(locked.stat().st_mode) == 0o700++[email protected]("mode", (0o500, 0o755))+def test_remove_confined_path_does_not_require_procfs_for_openable_directories(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ mode: int,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ nested = target / "nested"+ nested.mkdir(mode=0o700)+ nested.chmod(mode)++ from core.memory import confined_filesystem++ fake_o_path = 1 << 30+ real_open = confined_filesystem.os.open+ real_chmod = confined_filesystem.os.chmod++ def emulate_o_path(path, flags, *args, **kwargs):+ if flags & fake_o_path:+ flags = (flags & ~fake_o_path) | os.O_RDONLY+ return real_open(path, flags, *args, **kwargs)++ def reject_procfs_chmod(path, chmod_mode, *args, **kwargs):+ if os.fspath(path).startswith("/proc/self/fd/"):+ raise FileNotFoundError(errno.ENOENT, "procfs is unavailable")+ return real_chmod(path, chmod_mode, *args, **kwargs)++ monkeypatch.setattr(confined_filesystem.os, "O_PATH", fake_o_path, raising=False)+ monkeypatch.setattr(confined_filesystem.os, "open", emulate_o_path)+ monkeypatch.setattr(confined_filesystem.os, "chmod", reject_procfs_chmod)++ remove_confined_path(home, target)++ assert not target.exists()+++def test_remove_confined_path_rejects_a_mount_boundary_before_scanning(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ mounted = target / "mounted"+ mounted.mkdir(mode=0o700)+ victim = mounted / "victim.txt"+ victim.write_text("must survive", encoding="utf-8")++ from core.memory import confined_filesystem++ real_open = confined_filesystem.os.open+ real_scandir = confined_filesystem.os.scandir+ scanned_mount = False++ def reject_mount(parent_fd, name, flags):+ if name == mounted.name:+ raise OSError(errno.EXDEV, "mount boundary")+ return real_open(name, flags, dir_fd=parent_fd)++ def record_scandir(path):+ nonlocal scanned_mount+ if isinstance(path, int):+ opened = os.fstat(path)+ mounted_info = mounted.stat()+ if (opened.st_dev, opened.st_ino) == (+ mounted_info.st_dev,+ mounted_info.st_ino,+ ):+ scanned_mount = True+ return real_scandir(path)++ monkeypatch.setattr(+ confined_filesystem,+ "_open_directory_without_mount_crossing",+ reject_mount,+ )+ monkeypatch.setattr(confined_filesystem.os, "scandir", record_scandir)++ with pytest.raises(ConfinedFilesystemError, match="filesystem boundary"):+ remove_confined_path(home, target)++ assert not scanned_mount+ assert victim.read_text(encoding="utf-8") == "must survive"++[email protected](not hasattr(os, "O_PATH"), reason="requires an O_PATH inode anchor")+def test_remove_confined_path_rejects_directory_swap_during_permission_hardening(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ locked = target / "locked"+ locked.mkdir(mode=0o700)+ (locked / "original.txt").write_text("original", encoding="utf-8")+ locked.chmod(0o000)+ held = target / "held-locked"++ from core.memory import confined_filesystem++ real_chmod = confined_filesystem.os.chmod+ swapped = False++ def swap_before_chmod(path, mode, *args, **kwargs):+ nonlocal swapped+ anchored_path = os.fspath(path).startswith("/proc/self/fd/")+ if (+ not swapped+ and (path == locked.name or anchored_path)+ and (kwargs.get("dir_fd") is not None or anchored_path)+ ):+ swapped = True+ locked.rename(held)+ locked.mkdir(mode=0o700)+ (locked / "replacement.txt").write_text("replacement", encoding="utf-8")+ locked.chmod(0o000)+ return real_chmod(path, mode, *args, **kwargs)++ monkeypatch.setattr(confined_filesystem.os, "chmod", swap_before_chmod)+ try:+ with pytest.raises(ConfinedFilesystemError, match="changed during removal"):+ remove_confined_path(home, target)+ finally:+ real_chmod(locked, 0o700)+ real_chmod(held, 0o700)++ assert swapped+ assert (locked / "replacement.txt").read_text(encoding="utf-8") == "replacement"+ assert (held / "original.txt").read_text(encoding="utf-8") == "original"++[email protected](not hasattr(os, "O_PATH"), reason="requires an O_PATH inode anchor")+def test_remove_confined_path_does_not_follow_symlink_swapped_in_during_hardening(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ locked = target / "locked"+ locked.mkdir(mode=0o700)+ locked.chmod(0o000)+ held = target / "held-locked"+ outside = tmp_path / "outside"+ outside.mkdir(mode=0o755)+ victim = outside / "victim.txt"+ victim.write_text("outside survives", encoding="utf-8")++ from core.memory import confined_filesystem++ real_chmod = confined_filesystem.os.chmod+ swapped = False++ def swap_before_chmod(path, mode, *args, **kwargs):+ nonlocal swapped+ anchored_path = os.fspath(path).startswith("/proc/self/fd/")+ if (+ not swapped+ and (path == locked.name or anchored_path)+ and (kwargs.get("dir_fd") is not None or anchored_path)+ ):+ swapped = True+ locked.rename(held)+ locked.symlink_to(outside, target_is_directory=True)+ return real_chmod(path, mode, *args, **kwargs)++ monkeypatch.setattr(confined_filesystem.os, "chmod", swap_before_chmod)+ try:+ with pytest.raises(ConfinedFilesystemError):+ remove_confined_path(home, target)+ finally:+ real_chmod(held, 0o700)++ assert swapped+ assert locked.is_symlink()+ assert stat.S_IMODE(outside.stat().st_mode) == 0o755+ assert victim.read_text(encoding="utf-8") == "outside survives"++[email protected](not hasattr(os, "O_PATH"), reason="requires an O_PATH inode anchor")+def test_remove_confined_path_rechecks_device_after_permission_hardening(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ target.chmod(0o000)++ from core.memory import confined_filesystem++ real_chmod = confined_filesystem.os.chmod+ real_stat = confined_filesystem.os.stat+ hardened = False++ def mark_hardened(path, mode, *args, **kwargs):+ nonlocal hardened+ result = real_chmod(path, mode, *args, **kwargs)+ anchored_path = os.fspath(path).startswith("/proc/self/fd/")+ if (path == target.name and kwargs.get("dir_fd") is not None) or anchored_path:+ hardened = True+ return result++ def cross_device_after_hardening(path, *args, **kwargs):+ info = real_stat(path, *args, **kwargs)+ if path == target.name and hardened:+ values = list(info)+ values[2] = info.st_dev + 1+ return os.stat_result(values)+ return info++ monkeypatch.setattr(confined_filesystem.os, "chmod", mark_hardened)+ monkeypatch.setattr(confined_filesystem.os, "stat", cross_device_after_hardening)+ try:+ with pytest.raises(ConfinedFilesystemError, match="filesystem boundary"):+ remove_confined_path(home, target)+ finally:+ target.chmod(0o700)++ assert hardened+ assert target.is_dir()++[email protected](not hasattr(os, "O_PATH"), reason="requires an O_PATH inode anchor")+def test_remove_confined_path_fails_closed_without_anchored_hardening(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ target.chmod(0o000)++ from core.memory import confined_filesystem++ real_chmod = confined_filesystem.os.chmod++ def unsupported_chmod(path, mode, *args, **kwargs):+ anchored_path = os.fspath(path).startswith("/proc/self/fd/")+ if kwargs.get("dir_fd") is not None or anchored_path:+ raise NotImplementedError("anchored chmod unavailable")+ return real_chmod(path, mode, *args, **kwargs)++ monkeypatch.setattr(confined_filesystem.os, "chmod", unsupported_chmod)+ try:+ with pytest.raises(ConfinedFilesystemError, match="cannot be hardened safely"):+ remove_confined_path(home, target)+ finally:+ real_chmod(target, 0o700)++ assert target.is_dir()+++def test_remove_anchored_entry_rejects_foreign_owned_directory(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ target.chmod(0o777)+ descriptor = os.open(home, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))+ real_uid = os.getuid()++ from core.memory import confined_filesystem++ monkeypatch.setattr(confined_filesystem.os, "getuid", lambda: real_uid + 1)+ try:+ with pytest.raises(ConfinedFilesystemError):+ remove_anchored_entry(descriptor, target.name)+ finally:+ os.close(descriptor)++ assert target.is_dir()+ assert stat.S_IMODE(target.stat().st_mode) == 0o777+++def test_remove_anchored_entry_rejects_cross_device_directory(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ target = home / "target"+ target.mkdir(mode=0o700)+ target.chmod(0o777)+ descriptor = os.open(home, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))++ from core.memory import confined_filesystem++ real_stat = confined_filesystem.os.stat++ def cross_device_stat(path, *args, **kwargs):+ info = real_stat(path, *args, **kwargs)+ if path == target.name and kwargs.get("dir_fd") == descriptor:+ values = list(info)+ values[2] = info.st_dev + 1+ return os.stat_result(values)+ return info++ monkeypatch.setattr(confined_filesystem.os, "stat", cross_device_stat)+ try:+ with pytest.raises(ConfinedFilesystemError, match="filesystem boundary"):+ remove_anchored_entry(descriptor, target.name)+ finally:+ os.close(descriptor)++ assert target.is_dir()+ assert stat.S_IMODE(target.stat().st_mode) == 0o777++def test_private_sqlite_database_prepares_and_hardens_owned_files(tmp_path: Path) -> None:home = tmp_path / "home"path = home / "state" / "journal.sqlite"diff --git a/tests/test_memory_process.py b/tests/test_memory_process.pyindex 8924561a2..2dca58061 100644--- a/tests/test_memory_process.py+++ b/tests/test_memory_process.py@@ -311,6 +311,34 @@ def test_sidecar_child_environment_is_allowlisted_and_generated_config_has_no_keassert "AVIBE_MEMORY_CALL_LOG_DB" not in environment+def test_sidecar_child_home_preparation_hardens_every_created_directory(+ tmp_path: Path,+) -> None:+ process = EverOSProcess(+ sys.executable,+ effective_home=tmp_path,+ settings=_settings(),+ )+ previous_umask = os.umask(0o022)+ try:+ process._prepare_owned_directories()+ finally:+ os.umask(previous_umask)++ child_home = tmp_path / "memory" / ".child-home"+ created = [child_home]+ created.extend(path for path in child_home.rglob("*") if path.is_dir())+ assert {path.relative_to(child_home).as_posix() for path in created} == {+ ".",+ ".cache",+ ".config",+ ".local",+ ".local/share",+ ".local/state",+ }+ assert all(stat.S_IMODE(path.stat().st_mode) == 0o700 for path in created)++def test_pinned_attachment_uri_matches_process_body_and_sidecar_guard(monkeypatch, tmp_path: Path) -> None: