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
test(conftest): refuse writes under the real Avibe home (#2350)
Call White4de0663f50ff
diff --git a/pyproject.toml b/pyproject.tomlindex 918f25bb0..5eb618317 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -169,6 +169,8 @@ markers = ["uses_real_paths: opt out of the autouse home/config isolation so the test can exercise real path resolvers (must remain read-only)","no_sqlite_template: opt out of the pre-migrated SQLite template for migration/bootstrap tests","allow_foreign_signals(reason): opt out of the autouse guard that refuses os.kill/os.killpg to processes the test did not start (state the reason)",+ "real_web_push_sender: opt out of the autouse stub that keeps the delayed Web Push sender from outliving a test, for tests that drive the sender directly",+ "real_catalog_refresh: opt out of the autouse stub that keeps the remote model catalog and models.dev refreshes from outliving a test, for tests that drive a refresh directly",][dependency-groups]diff --git a/tests/conftest.py b/tests/conftest.pyindex d3c6b705d..402f58d20 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -13,10 +13,13 @@ The post-install bookkeeping in ``vibe.api._run_install_command`` thencalled ``load_config()`` / ``cfg.save()`` against the real config.json andpersisted the fixture path, surfacing in the UI after the next restart.-Isolation mechanism: we set ``HOME``, XDG config/data/cache/state homes, and-``AVIBE_HOME`` to a per-test tmp directory, and patch-``pathlib.Path.home`` to match. This means ``config.paths.get_vibe_remote_dir``-runs as written — only its env-var-set branch is exercised under isolation, and+Isolation mechanism: when pytest loads this file, before any product module is+imported, ``HOME``, the XDG homes, ``AVIBE_HOME``, ``CODEX_HOME``,+``CLAUDE_CONFIG_DIR`` and ``pathlib.Path.home`` move to a throwaway session home+for the whole run, and each test then swaps in its own tmp home on top of that.+The real home is never the ambient one, not even between tests, so work that+outlives its test lands in the session home. ``config.paths.get_vibe_remote_dir``+therefore runs as written — only its env-var-set branch is exercised under isolation, andthe function itself is never replaced, so the suite still catches regressions inpath-resolution logic while Python helpers, subprocesses, and ``expanduser("~")``do not see the developer's real home.@@ -45,6 +48,7 @@ from __future__ import annotationsimport astimport errno+import importlibimport inspectimport osimport re@@ -53,7 +57,12 @@ import signalimport sqlite3import subprocessimport sys+import tempfile+import threading+import tracebackimport unittest+import urllib.parse+import urllib.requestimport warningsfrom contextlib import closing, contextmanagerfrom functools import wraps@@ -68,6 +77,85 @@ from tests.fake_pid_helpers import PID_LIMITREAL_USER_HOME = Path.home()_SQLITE_DEFAULT_STATE_MODULES: dict[Path, bool] = {}+# The variables that name a home, and the caller identity an Agent-launched+# pytest inherits from the live conversation. Tests must opt in to that context+# explicitly, or unrelated Harness/session assertions bind themselves to the+# live Agent session.+_HOME_ENV = (+ "HOME",+ "XDG_CONFIG_HOME",+ "XDG_DATA_HOME",+ "XDG_CACHE_HOME",+ "XDG_STATE_HOME",+ "AVIBE_HOME",+ "CODEX_HOME",+ "CLAUDE_CONFIG_DIR",+)+_CALLER_ENV = (+ "AVIBE_SESSION_ID",+ "AVIBE_CALLER_SESSION_PROOF",+ "AVIBE_RUN_ID",+ "AVIBE_NATIVE_SESSION_ID",+ "AVIBE_CALLER_SOURCE",+ "AVIBE_CALLER_BACKEND",+ "AVIBE_CALLER_PLATFORM",+ "AVIBE_CALLER_USER_ID",+ "AVIBE_CALLER_CHANNEL_ID",+ "AVIBE_CALLER_SESSION_KEY",+ "AVIBE_CALLER_MESSAGE_ID",+ "AVIBE_CALLER_WORKSPACE_ID",+ "AVIBE_CALLER_REMOTE",+ "AVIBE_CALLER_RESOURCE_CONTEXT",+ "VIBE_INTERNAL_DISPATCH_SOCKET",+ "VIBE_CURRENT_EXECUTABLE",+ "AVIBE_SKILL_WORKING_DIR",+ "AVIBE_SKILL_PROJECT_BASE",+ "AVIBE_SKILL_HOME",+ "AVIBE_SKILL_CODEX_HOME",+ "AVIBE_SKILL_CLAUDE_HOME",+ "AVIBE_SKILL_CLAUDE_CLI_PATH",+ "AVIBE_SKILL_XDG_CONFIG_HOME",+ "AVIBE_BUILTIN_SKILLS_ROOT",+ "AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID",+ # A pytest started from a desktop Runtime's terminal would otherwise act as+ # that Runtime, and every stop, restart and start refuses or claims by its id.+ "AVIBE_DESKTOP_RUNTIME_ID",+ "AVIBE_DESKTOP_RUNTIME_ROOT",+)+# What the run started with, for `uses_real_paths` tests and the tripwire.+_AMBIENT_ENV = {name: os.environ.get(name) for name in (*_HOME_ENV, *_CALLER_ENV)}+_REAL_PATH_HOME = Path.__dict__["home"]+++def _home_env(home: Path) -> dict[str, str]:+ return {+ "HOME": str(home),+ "XDG_CONFIG_HOME": str(home / ".config"),+ "XDG_DATA_HOME": str(home / ".local" / "share"),+ "XDG_CACHE_HOME": str(home / ".cache"),+ "XDG_STATE_HOME": str(home / ".local" / "state"),+ "AVIBE_HOME": str(home / ".avibe"),+ # Codex and Claude Code keep credentials under these, not under HOME.+ "CODEX_HOME": str(home / ".codex"),+ "CLAUDE_CONFIG_DIR": str(home / ".claude"),+ }+++# Isolation by construction: from here on the run's own home is a throwaway one,+# before any product module is imported, through collection, session fixtures+# and the gaps between tests. Per-test isolation swaps a test's home in and back+# to this one, never to the real one, so work that outlives its test -- the+# delayed Web Push thread that once migrated a developer's real database --+# resolves this home. Only `uses_real_paths` tests see the real values, for their+# own duration. Removed at `pytest_unconfigure`.+_SESSION_HOME = Path(tempfile.mkdtemp(prefix="avibe-pytest-home-")).resolve()+# Expanded against the real HOME while it is still the ambient one.+_AMBIENT_AVIBE_HOME = os.path.expanduser(_AMBIENT_ENV["AVIBE_HOME"]) if _AMBIENT_ENV["AVIBE_HOME"] else None+for _name in _CALLER_ENV:+ os.environ.pop(_name, None)+os.environ.update(_home_env(_SESSION_HOME))+Path.home = classmethod(lambda cls: _SESSION_HOME)+def pytest_configure(config):# A desktop caller is also whoever runs from a private tree's interpreter,@@ -213,59 +301,22 @@ def sqlite_schema_db_factory(sqlite_db_factory, _sqlite_schema_template_factory)@pytest.fixture(autouse=True)def _isolate_vibe_remote_home(request, tmp_path, monkeypatch):if request.node.get_closest_marker("uses_real_paths"):+ # The real values, for this test only; it must stay read-only.+ monkeypatch.setattr(Path, "home", _REAL_PATH_HOME)+ for name, value in _AMBIENT_ENV.items():+ if value is None:+ monkeypatch.delenv(name, raising=False)+ else:+ monkeypatch.setenv(name, value)return- monkeypatch.delenv("AVIBE_HOME", raising=False)- # Agent-launched pytest processes inherit the active conversation's caller- # identity. Tests must opt in to that context explicitly or unrelated- # Harness/session assertions can bind themselves to the live Agent session.- for name in (- "AVIBE_SESSION_ID",- "AVIBE_CALLER_SESSION_PROOF",- "AVIBE_RUN_ID",- "AVIBE_NATIVE_SESSION_ID",- "AVIBE_CALLER_SOURCE",- "AVIBE_CALLER_BACKEND",- "AVIBE_CALLER_PLATFORM",- "AVIBE_CALLER_USER_ID",- "AVIBE_CALLER_CHANNEL_ID",- "AVIBE_CALLER_SESSION_KEY",- "AVIBE_CALLER_MESSAGE_ID",- "AVIBE_CALLER_WORKSPACE_ID",- "AVIBE_CALLER_REMOTE",- "AVIBE_CALLER_RESOURCE_CONTEXT",- "VIBE_INTERNAL_DISPATCH_SOCKET",- "VIBE_CURRENT_EXECUTABLE",- "AVIBE_SKILL_WORKING_DIR",- "AVIBE_SKILL_PROJECT_BASE",- "AVIBE_SKILL_HOME",- "AVIBE_SKILL_CODEX_HOME",- "AVIBE_SKILL_CLAUDE_HOME",- "AVIBE_SKILL_CLAUDE_CLI_PATH",- "AVIBE_SKILL_XDG_CONFIG_HOME",- "AVIBE_BUILTIN_SKILLS_ROOT",- "AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID",- # A pytest started from a desktop Runtime's terminal would otherwise- # act as that Runtime, and every stop, restart and start refuses or- # claims by its id.- "AVIBE_DESKTOP_RUNTIME_ID",- "AVIBE_DESKTOP_RUNTIME_ROOT",- ):- monkeypatch.delenv(name, raising=False)isolated_home = tmp_path / "home"monkeypatch.setattr(Path, "home", lambda: isolated_home)- monkeypatch.setenv("HOME", str(isolated_home))- monkeypatch.setenv("XDG_CONFIG_HOME", str(isolated_home / ".config"))- monkeypatch.setenv("XDG_DATA_HOME", str(isolated_home / ".local" / "share"))- monkeypatch.setenv("XDG_CACHE_HOME", str(isolated_home / ".cache"))- monkeypatch.setenv("XDG_STATE_HOME", str(isolated_home / ".local" / "state"))- monkeypatch.setenv("AVIBE_HOME", str(isolated_home / ".avibe"))+ # Tests that manage these themselves (e.g. the ``get_codex_home``+ # env-precedence tests) override them with their own monkeypatch calls,+ # which run after this fixture.+ for name, value in _home_env(isolated_home).items():+ monkeypatch.setenv(name, value)monkeypatch.setenv("AVIBE_ALLOW_DEV_STATE_MIGRATION", "1")- # Keep Codex / Claude Code credential writes off the developer's real- # home. Tests that manage these env vars themselves (e.g. the- # ``get_codex_home`` env-precedence tests) override these via their own- # monkeypatch calls, which run after this fixture.- monkeypatch.setenv("CODEX_HOME", str(isolated_home / ".codex"))- monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(isolated_home / ".claude"))@pytest.fixture(autouse=True)@@ -284,6 +335,69 @@ def _reset_latest_version_cache():latest_version_cache._MEMORY.clear() # noqa: SLF001+def _module_this_test_can_import(name: str):+ """``name``, or None where this file's own ``sys.modules`` stubs keep it from importing.++ Several test files replace packages such as ``modules.agents`` with partial+ stubs at import time; a module that cannot import under them cannot start a+ background worker in that file either, so there is nothing to stub.+ """++ try:+ return importlib.import_module(name)+ except ImportError:+ return None++[email protected](autouse=True)+def _no_background_web_push(request: pytest.FixtureRequest, monkeypatch) -> list[dict] | None:+ """Keep the delayed Web Push sender off a thread that outlives its test.++ Persisting a notifiable Workbench message schedules+ ``_send_to_enabled_subscriptions`` on a daemon thread that sleeps+ ``WEB_PUSH_NOTIFICATION_DELAY_SECONDS`` and only then resolves the state+ paths. By then the test that scheduled it has usually ended; one such thread+ woke while the next test's home isolation was half applied, resolved the+ developer's real home and migrated its database. Scheduling still runs, and+ the payloads that would have been pushed are returned, so a test that asserts+ on them requests this fixture. ``real_web_push_sender`` opts out a test that+ drives the sender itself.+ """++ if request.node.get_closest_marker("real_web_push_sender"):+ return None+ web_push_notifications = _module_this_test_can_import("core.web_push_notifications")+ if web_push_notifications is None:+ return None+ pushed: list[dict] = []+ monkeypatch.setattr(web_push_notifications, "_send_to_enabled_subscriptions", pushed.append)+ return pushed++[email protected](autouse=True)+def _no_background_catalog_refresh(request: pytest.FixtureRequest, monkeypatch) -> None:+ """Keep the remote catalog refreshes off threads that outlive their test.++ Reading the backend model catalog or the models.dev catalog from a fresh home+ finds its cache stale and starts a daemon thread that fetches over the network+ and only then resolves the state directory to write the cache, usually after+ the test has ended -- the same shape as the Web Push sender, and the real-home+ tripwire caught both writing the developer's state. Each scheduler reports+ that no refresh started. ``real_catalog_refresh`` opts out a test that drives+ the refresh itself.+ """++ if request.node.get_closest_marker("real_catalog_refresh"):+ return+ for name, scheduler in (+ ("vibe.backend_model_catalog", "schedule_remote_catalog_refresh"),+ ("vibe.models_dev_catalog", "_refresh_in_background"),+ ):+ module = _module_this_test_can_import(name)+ if module is not None:+ monkeypatch.setattr(module, scheduler, lambda: False)++@pytest.fixture(autouse=True)def _seed_sqlite_state_template(request: pytest.FixtureRequest,@@ -681,6 +795,219 @@ def _foreign_signal_guard(request, tmp_path):pytest.fail("signals and lookups this test may not make were blocked:\n" + "\n".join(guard.violations))+# The developer's real Avibe state: both homes under REAL_USER_HOME, plus the+# custom home AVIBE_HOME names when pytest starts with one, each spelled as+# written and as resolved, because the legacy name is usually a symlink to the+# current one. Fixed when pytest loads this file, before any test replaces HOME,+# AVIBE_HOME or `Path.home`; teardown restores them, so work that outlives a test+# resolves exactly these. The SQLite migration guard cannot stand in for this:+# every test runs with its opt-in flag set and with `Path.home` naming the test's+# own home, so under pytest neither of its checks can recognise the real database.+_REAL_STATE_HOMES = [REAL_USER_HOME / ".avibe", REAL_USER_HOME / ".vibe_remote"]+if _AMBIENT_AVIBE_HOME:+ _REAL_STATE_HOMES.append(Path(_AMBIENT_AVIBE_HOME))+_REAL_STATE_ROOTS = tuple(+ sorted(+ {+ spelling+ for home in _REAL_STATE_HOMES+ for spelling in (os.path.abspath(home), os.path.realpath(home))+ }+ )+)+_WRITE_OPEN_FLAGS = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_TRUNC+_REPO_ROOT = str(Path(__file__).resolve().parents[1])+# Every path-mutating audit event CPython raises, mapped to the arguments that+# name a path it writes, each with the index of its dir_fd (None when the event+# carries none). shutil's copy, move and chown helpers end in these events or in+# `open`; only rmtree is listed itself, because its fd-based walk names entries+# relative to descriptors. `open` and `sqlite3.connect` depend on their mode.+_WRITE_EVENTS = {+ "os.mkdir": ((0, 2),),+ "os.rmdir": ((0, 1),),+ "os.remove": ((0, 1),),+ "os.rename": ((0, 2), (1, 3)),+ "os.symlink": ((1, 2),),+ "os.link": ((1, 3),),+ "os.chmod": ((0, 2),),+ "os.chown": ((0, 3),),+ "os.utime": ((0, 3),),+ "os.truncate": ((0, None),),+ "os.chflags": ((0, None),),+ "os.setxattr": ((0, None),),+ "os.removexattr": ((0, None),),+ "shutil.rmtree": ((0, 1),),+}+_TRIPWIRE_EVENTS = frozenset({"open", "sqlite3.connect", *_WRITE_EVENTS})+# Events that act on a final symlink itself rather than on what it names.+_LINK_LEVEL_EVENTS = frozenset(+ {"os.mkdir", "os.rmdir", "os.remove", "os.rename", "os.symlink", "os.link", "shutil.rmtree"}+)+# What the audit arguments carry for a dir_fd the caller did not pass.+_NO_DIR_FD = (None, -1)+# Every refused write in this run, in order. A daemon thread or a broad `except`+# can swallow the refusal itself; this record is what fails the session.+_real_home_writes: list[str] = []+_tripwire_busy = threading.local()+++def _descriptor_path(fd: int) -> str | None:+ """The directory an open descriptor names, where the platform can say."""++ try:+ if sys.platform == "darwin":+ import fcntl++ return os.fsdecode(fcntl.fcntl(fd, fcntl.F_GETPATH, bytes(1024)).split(b"\0", 1)[0])+ return os.readlink(f"/proc/self/fd/{fd}")+ except (OSError, AttributeError):+ return None+++def _under_real_state(path, dir_fd=None, *, follows: bool = True) -> str | None:+ if isinstance(path, int):+ return None # a descriptor: its own open was checked by name+ text = os.fsdecode(path)+ if not os.path.isabs(text) and dir_fd not in _NO_DIR_FD:+ directory = _descriptor_path(dir_fd)+ if directory is None:+ return None+ text = os.path.join(directory, text)+ absolute = os.path.abspath(text)+ # Resolved as well, so an alias -- a symlink elsewhere into a protected home --+ # is recognised; an operation on a link itself resolves only its directory.+ head, tail = os.path.split(absolute)+ resolved = os.path.realpath(absolute) if follows else os.path.join(os.path.realpath(head), tail)+ for spelling in (absolute, resolved):+ if any(spelling == root or spelling.startswith(root + os.sep) for root in _REAL_STATE_ROOTS):+ return absolute+ return None+++def _sqlite_write_target(database) -> str | None:+ text = os.fsdecode(database)+ if not text.startswith("file:"):+ return _under_real_state(text)+ uri = urllib.parse.urlsplit(text)+ query = urllib.parse.parse_qs(uri.query)+ # Only an immutable open writes nothing: `mode=ro` on a WAL database can still+ # create its `-shm` sidecar.+ if query.get("immutable") == ["1"]:+ return None+ return _under_real_state(urllib.request.url2pathname(uri.path))+++def _real_state_writes(event: str, args: tuple) -> list[str]:+ if event == "open":+ path, mode, flags = args+ if isinstance(flags, int):+ writes = bool(flags & _WRITE_OPEN_FLAGS)+ else:+ writes = any(letter in (mode or "") for letter in "wax+")+ targets = [_under_real_state(path)] if writes else []+ elif event == "sqlite3.connect":+ targets = [_sqlite_write_target(args[0])]+ else:+ follows = event not in _LINK_LEVEL_EVENTS+ targets = [+ # shutil.rmtree carries its dir_fd only from Python 3.12.+ _under_real_state(+ args[at], args[fd_at] if fd_at is not None and fd_at < len(args) else None, follows=follows+ )+ for at, fd_at in _WRITE_EVENTS[event]+ ]+ return [target for target in targets if target is not None]+++def _describe_real_home_write(event: str, written: list[str]) -> str:+ frames = [+ f"{frame.filename}:{frame.lineno} in {frame.name}"+ for frame in traceback.extract_stack()+ if frame.filename.startswith(_REPO_ROOT) and frame.filename != __file__+ ]+ return (+ f"{event} {', '.join(written)} from thread {threading.current_thread().name} during "+ f"{os.environ.get('PYTEST_CURRENT_TEST', 'no test')}: {'; '.join(frames[-6:]) or 'no repository frame'}"+ )+++def _real_home_tripwire(event: str, args: tuple) -> None:+ """Refuse any write under the developer's real Avibe home, from any thread.++ An audit hook rather than a fixture, so it holds between tests, during+ collection and in threads that outlive the test that started them -- the+ window per-test isolation cannot reach. Reads stay allowed, including+ ``uses_real_paths`` tests and ``immutable=1`` SQLite URIs. Child processes+ are outside it: each pytest child loads+ its own copy of this file, and other children inherit the test's home. The+ one write it cannot place is ``os.open`` relative to a ``dir_fd``, whose+ audit event omits the descriptor; creating that directory chain still trips.+ """++ if event not in _TRIPWIRE_EVENTS or getattr(_tripwire_busy, "active", False):+ return+ # Reading source for the description opens files, which re-enters this hook.+ _tripwire_busy.active = True+ try:+ try:+ written = _real_state_writes(event, args)+ except (TypeError, ValueError, OSError):+ return # not a path this hook can name, such as a cwd that no longer exists+ if not written:+ return+ message = _describe_real_home_write(event, written)+ _real_home_writes.append(message)+ _fail_running_session()+ finally:+ _tripwire_busy.active = False+ # A BaseException, so a product `except Exception` around the write cannot+ # swallow it; the session-end check covers anything broader.+ pytest.fail(f"refused a write under the real Avibe home: {message}")+++sys.addaudithook(_real_home_tripwire)+++_REPORTED_WRITES = pytest.StashKey[int]()+_running_session: pytest.Session | None = None+++def _fail_running_session() -> None:+ # pytest overwrites the status once the tests have run, so+ # `pytest_unconfigure` marks it again; a refusal after that point is+ # marked here, until pytest returns.+ session = _running_session+ if session is not None and session.exitstatus in (pytest.ExitCode.OK, pytest.ExitCode.NO_TESTS_COLLECTED):+ session.exitstatus = pytest.ExitCode.TESTS_FAILED+++def pytest_sessionstart(session: pytest.Session) -> None:+ global _running_session+ _running_session = session+++def pytest_terminal_summary(terminalreporter) -> None:+ written = list(_real_home_writes)+ terminalreporter.config.stash[_REPORTED_WRITES] = len(written)+ if written:+ terminalreporter.section("writes under the real Avibe home were refused", red=True)+ for message in written:+ terminalreporter.line(message, red=True)++[email protected](trylast=True)+def pytest_unconfigure(config: pytest.Config) -> None:+ # The session home and the tripwire stay in place until the process exits:+ # daemon threads can outlive this hook, and restoring the real values here+ # would hand them the real home again. Only a write during interpreter+ # shutdown, after pytest has returned its status, is refused without failing.+ shutil.rmtree(_SESSION_HOME, ignore_errors=True)+ for message in _real_home_writes[config.stash.get(_REPORTED_WRITES, 0) :]:+ sys.stderr.write(f"refused a write under the real Avibe home: {message}\n")+ if _real_home_writes:+ _fail_running_session()++@pytest.fixturedef hold_migration_lock_elsewhere():"""Hold a migration lock path from a thread that is genuinely not the caller.diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.pyindex fb0d2002e..26cd29f6d 100644--- a/tests/e2e/conftest.py+++ b/tests/e2e/conftest.py@@ -14,9 +14,16 @@ import pytestimport urllib.requestimport urllib.error+from tests.conftest import REAL_USER_HOMEfrom tests.e2e.drivers.model_hub_app import ModelHubTestAppfrom tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream+# The root conftest gives the whole run a throwaway HOME. These Docker-backed+# fixtures keep the developer's Docker client contexts and credential helpers,+# which the CLI would otherwise look for in that empty home and find none.+if not os.environ.get("DOCKER_CONFIG") and (REAL_USER_HOME / ".docker").is_dir():+ os.environ["DOCKER_CONFIG"] = str(REAL_USER_HOME / ".docker")+# E2E tests connect to the Vibe container on this portE2E_PORT = int(os.environ.get("VIBE_E2E_PORT", "15123"))E2E_BASE_URL = f"http://127.0.0.1:{E2E_PORT}"diff --git a/tests/test_backend_failure_retry.py b/tests/test_backend_failure_retry.pyindex 87d82d742..0d925d861 100644--- a/tests/test_backend_failure_retry.py+++ b/tests/test_backend_failure_retry.py@@ -19,13 +19,6 @@ from tests.test_ui_session_stream import _accepted_dispatch, _make_session, isolfrom tests.ui_server_test_helpers import csrf_headers[email protected](autouse=True)-def _isolate_web_push(monkeypatch):- # Real notice persistence is in scope; asynchronous external push delivery- # is not. Do not let its worker outlive a test's temporary state directory.- monkeypatch.setattr("core.web_push_notifications.maybe_notify_inbox_message", lambda *_args: None)--def _restart_failure_notice(tmp_path, *, backend, delivery="ready"):"""Recover an accepted Turn through the real notice dispatcher and storage."""from core.message_dispatcher import ConsolidatedMessageDispatcherdiff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.pyindex 59d68c362..7174f1931 100644--- a/tests/test_backend_model_catalog.py+++ b/tests/test_backend_model_catalog.py@@ -1093,6 +1093,7 @@ def test_an_explicitly_listed_remote_row_can_revive_a_retired_model():assert "claude-opus-4" in {entry["id"] for entry in merged}[email protected]_catalog_refreshdef test_snapshot_returns_immediately_while_remote_refresh_runs(monkeypatch, tmp_path):refresh_started = threading.Event()release_refresh = threading.Event()diff --git a/tests/test_conftest_real_home_tripwire.py b/tests/test_conftest_real_home_tripwire.pynew file mode 100644index 000000000..a0879e2f1--- /dev/null+++ b/tests/test_conftest_real_home_tripwire.py@@ -0,0 +1,320 @@+"""A write under the developer's real Avibe home fails the run, whoever makes it.++The incident this guards: a Web Push daemon thread outlived the test that+scheduled it, woke while the per-test home isolation was undone between two+tests, and migrated the developer's real ``~/.avibe/state/vibe.sqlite``. The+migration guard could not see it -- conftest sets its opt-in flag and patches+``Path.home`` for every test -- and the thread swallowed every exception, so the+run stayed green. The tripwire in ``tests/conftest.py`` refuses such a write and+fails the session even when the writer swallows the refusal.++Each inner run loads the real ``tests/conftest.py`` as a plugin. ``pytester``+points ``HOME`` at its own temporary directory, which the inner run therefore+takes for the developer's home: nothing here can reach the actual one.+"""++from __future__ import annotations++import os+import sqlite3+import stat+from pathlib import Path++import pytest++pytest_plugins = ("pytester",)++REPO_ROOT = Path(__file__).resolve().parents[1]++# Every write shape the tripwire refuses, each from a daemon thread whose handler+# swallows whatever the write raises -- the incident's shape exactly.+_BACKGROUND_WRITES = """+import os+import sqlite3+import threading+from pathlib import Path++HOME = Path(__HOME__)+++def _in_a_swallowing_daemon_thread(write):+ def run():+ try:+ write()+ except BaseException:+ pass++ thread = threading.Thread(target=run, daemon=True)+ thread.start()+ thread.join()+++def _migrate():+ with sqlite3.connect(HOME / ".avibe" / "state" / "vibe.sqlite") as conn:+ conn.execute("create table leaked (x)")+++def test_sqlite_connect():+ _in_a_swallowing_daemon_thread(_migrate)+++def test_write_mode_open():+ _in_a_swallowing_daemon_thread(lambda: (HOME / ".avibe" / "config" / "config.json").write_text("leaked"))+++def test_mkdir():+ _in_a_swallowing_daemon_thread(lambda: (HOME / ".avibe" / "leaked").mkdir())+++def test_rename():+ config = HOME / ".avibe" / "config"+ _in_a_swallowing_daemon_thread(lambda: os.rename(config / "config.json", config / "leaked.json"))+++def test_legacy_home():+ _in_a_swallowing_daemon_thread(lambda: (HOME / ".vibe_remote" / "leaked.txt").write_text("leaked"))+++def test_symlink():+ _in_a_swallowing_daemon_thread(lambda: os.symlink(HOME / ".avibe", HOME / ".avibe" / "leaked-link"))+++def test_hard_link():+ config = HOME / ".avibe" / "config"+ _in_a_swallowing_daemon_thread(lambda: os.link(config / "config.json", config / "leaked-link.json"))+++def test_chmod():+ _in_a_swallowing_daemon_thread(lambda: os.chmod(HOME / ".avibe" / "config" / "config.json", 0o777))+++def test_cwd_relative_path():+ previous = os.getcwd()+ os.chdir(HOME / ".avibe")+ try:+ _in_a_swallowing_daemon_thread(lambda: os.mkdir("leaked-relative"))+ finally:+ os.chdir(previous)+++def test_dir_fd_relative_path():+ state = os.open(HOME / ".avibe" / "state", os.O_RDONLY)+ try:+ _in_a_swallowing_daemon_thread(lambda: os.mkdir("leaked-at", dir_fd=state))+ finally:+ os.close(state)+++def test_symlinked_alias():+ # The alias lives outside the protected homes and names one of them.+ (HOME / "alias").symlink_to(HOME / ".avibe")+ _in_a_swallowing_daemon_thread(lambda: (HOME / "alias" / "leaked.txt").write_text("leaked"))+++def test_custom_home():+ _in_a_swallowing_daemon_thread(lambda: (HOME / "custom-home" / "leaked.txt").write_text("leaked"))+++def test_sqlite_read_only_mode():+ # `mode=ro` on a WAL database can still create its `-shm` sidecar.+ database = (HOME / ".avibe" / "state" / "other.sqlite").as_uri()+ _in_a_swallowing_daemon_thread(lambda: sqlite3.connect(f"{database}?mode=ro", uri=True))+"""++_READS = """+import sqlite3+from pathlib import Path++HOME = Path(__HOME__)+++def test_reads_stay_allowed():+ assert (HOME / ".avibe" / "config" / "config.json").read_text() == "{}"+ database = (HOME / ".avibe" / "state" / "vibe.sqlite").as_uri()+ with sqlite3.connect(f"{database}?immutable=1", uri=True) as conn:+ assert conn.execute("select count(*) from sqlite_master").fetchone() == (0,)+"""+++# A daemon thread that finishes after the last test: while the session reports,+# or while pytest unconfigures -- after every other unconfigure hook has run.+_LATE_WRITE_CONFTEST = """+from pathlib import Path++import pytest+++def _write():+ try:+ (Path(__HOME__) / ".avibe" / "late.txt").write_text("leaked")+ except BaseException:+ pass++[email protected](trylast=True)+def pytest_terminal_summary():+ if __WHEN__ == "reporting":+ _write()++[email protected](wrapper=True)+def pytest_unconfigure():+ result = yield+ if __WHEN__ == "unconfiguring":+ _write()+ return result+"""+++# A worker that outlives its test and resolves the home only once that test has+# torn down -- the incident's Web Push thread, made deterministic: the hook below+# runs after every fixture of the test is finalized, then lets the worker go.+_OUTLIVING_WORKER_CONFTEST = """+import threading+from pathlib import Path++import pytest++released = threading.Event()+++def resolve_the_home_after_teardown():+ released.wait(10)+ from config import paths++ state = paths.get_state_dir()+ Path(__OUT__).write_text(f"{Path.home()}\\n{state}\\n")+ state.mkdir(parents=True, exist_ok=True)+ (state / "written-after-teardown.txt").write_text("leaked")+++worker = threading.Thread(target=resolve_the_home_after_teardown, daemon=True)+++def outliving_worker():+ worker.start()+++def pytest_runtest_logfinish(nodeid):+ released.set()+ worker.join(10)+"""+++def stand_in_home(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> Path:+ """The inner run's real home: pytester's ``HOME``, seeded like an installed Avibe.++ The inner run also starts with ``AVIBE_HOME`` naming a custom home beside it.+ """++ monkeypatch.setenv("PYTHONPATH", str(REPO_ROOT))+ home = pytester.path+ (home / "custom-home").mkdir()+ # In tilde form, which only the real HOME expands to the custom home.+ monkeypatch.setenv("AVIBE_HOME", "~/custom-home")+ (home / ".avibe" / "config").mkdir(parents=True)+ (home / ".avibe" / "state").mkdir()+ (home / ".vibe_remote").mkdir()+ (home / ".avibe" / "config" / "config.json").write_text("{}")+ sqlite3.connect(home / ".avibe" / "state" / "vibe.sqlite").close()+ return home+++def _run(pytester: pytest.Pytester, home: Path, source: str) -> pytest.RunResult:+ pytester.makepyfile(test_inner=source.replace("__HOME__", repr(str(home))))+ return pytester.runpytest_subprocess("-p", "tests.conftest", "-p", "no:cacheprovider")+++def test_a_swallowed_background_write_under_the_real_home_fails_the_run(+ pytester: pytest.Pytester, stand_in_home: Path+) -> None:+ seeded_mode = stat.S_IMODE((stand_in_home / ".avibe" / "config" / "config.json").stat().st_mode)+ result = _run(pytester, stand_in_home, _BACKGROUND_WRITES)++ # Every inner test passes: only the session-level check can fail this run.+ result.assert_outcomes(passed=13)+ assert result.ret == pytest.ExitCode.TESTS_FAILED, result.stdout.str()+ output = result.stdout.str()+ for event, path in [+ ("sqlite3.connect", ".avibe/state/vibe.sqlite"),+ ("open", ".avibe/config/config.json"),+ ("os.mkdir", ".avibe/leaked"),+ ("os.rename", ".avibe/config/config.json"),+ ("open", ".vibe_remote/leaked.txt"),+ ("os.symlink", ".avibe/leaked-link"),+ ("os.link", ".avibe/config/leaked-link.json"),+ ("os.chmod", ".avibe/config/config.json"),+ ("os.mkdir", ".avibe/leaked-relative"),+ ("open", "alias/leaked.txt"),+ ("open", "custom-home/leaked.txt"),+ ("sqlite3.connect", ".avibe/state/other.sqlite"),+ ]:+ assert f"{event} {stand_in_home / path}" in output, output+ # A descriptor names its directory as resolved.+ assert f"os.mkdir {os.path.realpath(stand_in_home / '.avibe' / 'state')}/leaked-at" in output, output++ # Refused, not merely reported: the home is exactly as it was seeded.+ config = stand_in_home / ".avibe" / "config" / "config.json"+ assert config.read_text() == "{}"+ assert stat.S_IMODE(config.stat().st_mode) == seeded_mode+ for leaked in (+ ".avibe/leaked",+ ".avibe/config/leaked.json",+ ".vibe_remote/leaked.txt",+ ".avibe/leaked-link",+ ".avibe/config/leaked-link.json",+ ".avibe/leaked-relative",+ ".avibe/state/leaked-at",+ ".avibe/leaked.txt",+ "custom-home/leaked.txt",+ ".avibe/state/other.sqlite",+ ):+ assert not os.path.lexists(stand_in_home / leaked), leaked+ with sqlite3.connect(f"{(stand_in_home / '.avibe' / 'state' / 'vibe.sqlite').as_uri()}?mode=ro", uri=True) as conn:+ assert conn.execute("select name from sqlite_master").fetchall() == []++[email protected]("when", ["reporting", "unconfiguring"])+def test_a_write_after_the_last_test_still_fails_the_run(+ pytester: pytest.Pytester, stand_in_home: Path, when: str+) -> None:+ conftest = _LATE_WRITE_CONFTEST.replace("__HOME__", repr(str(stand_in_home)))+ pytester.makeconftest(conftest.replace("__WHEN__", repr(when)))+ result = _run(pytester, stand_in_home, "def test_nothing():\n pass\n")++ result.assert_outcomes(passed=1)+ assert result.ret == pytest.ExitCode.TESTS_FAILED, result.stdout.str() + result.stderr.str()+ if when == "reporting":+ assert f"open {stand_in_home / '.avibe' / 'late.txt'}" in result.stderr.str()+ assert not (stand_in_home / ".avibe" / "late.txt").exists()+++def test_work_outliving_its_test_lands_in_the_session_home(+ pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Between isolations the run's home is a throwaway one, never the real one."""++ monkeypatch.setenv("PYTHONPATH", str(REPO_ROOT))+ monkeypatch.delenv("AVIBE_HOME") # the stand-in real home is the default one+ real_home = pytester.path+ out = pytester.path / "resolved.txt"+ pytester.makeconftest(_OUTLIVING_WORKER_CONFTEST.replace("__OUT__", repr(str(out))))+ pytester.makepyfile(test_inner="def test_starts_a_worker(outliving_worker):\n pass\n")++ result = pytester.runpytest_subprocess("-p", "tests.conftest", "-p", "no:cacheprovider")++ result.assert_outcomes(passed=1)+ assert result.ret == pytest.ExitCode.OK, result.stdout.str() + result.stderr.str()+ resolved_home, resolved_state = out.read_text().splitlines()+ assert not Path(resolved_home).is_relative_to(real_home), resolved_home+ assert not Path(resolved_state).is_relative_to(real_home), resolved_state+ assert not (real_home / ".avibe").exists()+++def test_reading_the_real_home_does_not_trip_it(pytester: pytest.Pytester, stand_in_home: Path) -> None:+ result = _run(pytester, stand_in_home, _READS)++ result.assert_outcomes(passed=1)+ assert result.ret == pytest.ExitCode.OK, result.stdout.str()diff --git a/tests/test_harness_failure_retry.py b/tests/test_harness_failure_retry.pyindex 114faac54..83c7d8296 100644--- a/tests/test_harness_failure_retry.py+++ b/tests/test_harness_failure_retry.py@@ -26,11 +26,6 @@ from tests.test_ui_session_stream import _make_session, isolated_state # noqa:from tests.ui_server_test_helpers import csrf_headers[email protected](autouse=True)-def _isolate_web_push(monkeypatch):- monkeypatch.setattr("core.web_push_notifications.maybe_notify_inbox_message", lambda *_args: None)--def _harness_restart_notice(tmp_path, *, backend="codex", target="same", linked=True):"""Real Run/Delivery/Turn settlement, owed-notice drain, and message storage."""scope_id, session_id = _make_session(tmp_path, agent_backend=backend)diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.pyindex 69ef68f25..0d3f89572 100644--- a/tests/test_harness_failure_visibility.py+++ b/tests/test_harness_failure_visibility.py@@ -1884,7 +1884,6 @@ def test_a_sent_notice_is_not_listed_again(tmp_path: Path) -> None:def test_a_session_less_definition_now_reaches_the_workspace_inbox(tmp_path: Path,- monkeypatch,) -> None:"""The INVERSION of a pin this branch used to carry, kept so the reversal is legible.@@ -1909,7 +1908,6 @@ def test_a_session_less_definition_now_reaches_the_workspace_inbox(from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_IDcontroller, _dispatcher, _touched = _live_turn_dispatcher()- _no_background_web_push(monkeypatch)_migrated_state_db()sqlite, requests = _store(tmp_path)@@ -4534,30 +4532,10 @@ def _workbench_session(return scope_id-def _no_background_web_push(monkeypatch) -> list[dict]:- """Keep the Web Push fan-out off the DAEMON THREAD, on the calling thread's DB.-- Persisting an avibe inbox row schedules ``_send_to_enabled_subscriptions`` on a- daemon thread that sleeps ``WEB_PUSH_NOTIFICATION_DELAY_SECONDS`` and only then- opens its own connection — long after the test's isolated home is gone, so it- raises ``no such table: messages`` into an unhandled-thread warning attributable- to no test. Scheduling is still exercised; only the delayed send is stubbed.-- Returns the payloads that WOULD have been pushed.- """-- import core.web_push_notifications as web_push_notifications-- pushed: list[dict] = []- monkeypatch.setattr(- web_push_notifications, "_send_to_enabled_subscriptions", pushed.append- )- return pushed--def test_a_workbench_addressed_notice_lands_as_a_durable_inbox_row(tmp_path: Path,monkeypatch,+ _no_background_web_push,) -> None:"""HFR-079 — the workbench rungs of D5's ladder were never reachable at all.@@ -4589,7 +4567,7 @@ def test_a_workbench_addressed_notice_lands_as_a_durable_inbox_row(from core.delivery_evidence import ACK_EVIDENCE_RECEIPTfrom storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID- pushed = _no_background_web_push(monkeypatch)+ pushed = _no_background_web_pushcontroller, _dispatcher, touched = _live_turn_dispatcher()controller.agent_auth_service = _ForbiddenAuthService()scope_id = _workbench_session("sesWork", project="proj-notice")@@ -4671,7 +4649,6 @@ def test_a_workbench_addressed_notice_lands_as_a_durable_inbox_row(def test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id(tmp_path: Path,- monkeypatch,) -> None:"""HFR-079 — the trap a bare parser swap walks straight into.@@ -4744,7 +4721,6 @@ def test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id(from storage.db import get_cached_sqlite_enginefrom storage.messages_service import get_inbox_session- _no_background_web_push(monkeypatch)controller, _dispatcher, _touched = _live_turn_dispatcher()# The schema, but deliberately NO session row for ``sesGone`` yet: the binding# points at a session that has been deleted.@@ -4863,7 +4839,6 @@ def test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id(def test_a_background_session_notice_is_rerouted_to_the_workspace_inbox(tmp_path: Path,- monkeypatch,) -> None:"""A hidden bound session cannot acknowledge a user-visible failure notice."""@@ -4872,7 +4847,6 @@ def test_a_background_session_notice_is_rerouted_to_the_workspace_inbox(from storage.db import get_cached_sqlite_enginefrom storage.messages_service import get_inbox_session- _no_background_web_push(monkeypatch)controller, _dispatcher, _touched = _live_turn_dispatcher()_workbench_session("sesBackgroundNotice",@@ -4931,7 +4905,7 @@ def _workspace_notice_session_rows() -> list[dict]:def test_a_caller_less_cli_definition_still_delivers_its_failure_notice(tmp_path: Path,- monkeypatch,+ _no_background_web_push,) -> None:"""D5 rung (5), owed by name at plan ``docs/plans/harness-run-reliability.md:3216``.@@ -4966,7 +4940,7 @@ def test_a_caller_less_cli_definition_still_delivers_its_failure_notice(from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_IDfrom vibe.cli import _definition_creation_metadata_from_caller- pushed = _no_background_web_push(monkeypatch)+ pushed = _no_background_web_pushcontroller, _dispatcher, _touched = _live_turn_dispatcher()# The real workbench schema, and deliberately NO session row and NO project# scope of any kind: the workspace session must be created by the notice path.@@ -5047,13 +5021,11 @@ def test_a_caller_less_cli_definition_still_delivers_its_failure_notice(def test_workspace_notification_session_is_created_once_and_reused(tmp_path: Path,- monkeypatch,) -> None:"""Repeated workspace notices reuse one retained Session history owner."""from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID- _no_background_web_push(monkeypatch)controller, _dispatcher, _touched = _live_turn_dispatcher()_migrated_state_db()@@ -5103,7 +5075,6 @@ def test_workspace_notification_session_is_created_once_and_reused(def test_an_archived_workspace_notice_session_heals_instead_of_swallowing_the_notice(tmp_path: Path,- monkeypatch,) -> None:"""The one state "lazy recreation" does NOT cover, and it fails SILENTLY.@@ -5141,7 +5112,6 @@ def test_an_archived_workspace_notice_session_heals_instead_of_swallowing_the_nofrom storage.messages_service import get_inbox_sessionfrom storage.models import agent_sessions- _no_background_web_push(monkeypatch)controller, _dispatcher, _touched = _live_turn_dispatcher()_migrated_state_db()@@ -5219,7 +5189,7 @@ def test_an_archived_workspace_notice_session_heals_instead_of_swallowing_the_nodef test_an_archived_ordinary_session_is_rerouted_instead_of_acked_into(tmp_path: Path,- monkeypatch,+ _no_background_web_push,) -> None:"""HFR-079, subordinate — the SAME hole for an ordinary session, opposite remedy.@@ -5272,7 +5242,7 @@ def test_an_archived_ordinary_session_is_rerouted_instead_of_acked_into(from storage.messages_service import get_inbox_sessionfrom storage.models import agent_sessions- pushed = _no_background_web_push(monkeypatch)+ pushed = _no_background_web_pushcontroller, _dispatcher, _touched = _live_turn_dispatcher()archived_scope_id = _workbench_session("sesArchived", project="proj-archived", status="archived"@@ -12100,7 +12070,6 @@ def _execution_service(tmp_path: Path, controller, sqlite, requests):def test_a_watch_that_outlives_its_delivery_target_dies_visibly(tmp_path: Path,- monkeypatch,capsys,) -> None:"""HFR-094, subordinate — #1060's four-step terminal case, driven end to end.@@ -12142,7 +12111,6 @@ def test_a_watch_that_outlives_its_delivery_target_dies_visibly(from vibe import clifrom vibe.i18n import t as i18n_t- _no_background_web_push(monkeypatch)_migrated_state_db()_workbench_session("sesd46nxp3cz5", project="proj-lane-b")@@ -12581,7 +12549,6 @@ def test_a_forever_watch_repeating_the_field_failure_notifies_once(import core.failure_notices as failure_noticesfrom core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore- _no_background_web_push(monkeypatch)_migrated_state_db()_workbench_session("sesGoneForever", project="proj-forever")@@ -12828,7 +12795,6 @@ def _session_transcript(session_id: str) -> list[tuple[str, str]]:def test_an_agent_run_pinned_to_the_reserved_session_dispatches_no_turn(tmp_path: Path,- monkeypatch,) -> None:"""HFR-094, subordinate — the CLI lane the composer guard could not reach.@@ -12853,7 +12819,6 @@ def test_an_agent_run_pinned_to_the_reserved_session_dispatches_no_turn(no assistant reply."""- _no_background_web_push(monkeypatch)_migrated_state_db()reserved = _reserved_notice_session()before = _session_transcript(reserved)@@ -12929,7 +12894,6 @@ def test_a_task_pinned_to_the_reserved_session_is_paused_never_rebound(from tests.test_scheduled_tasks import _binding_env, _binding_service- _no_background_web_push(monkeypatch)_binding_env(tmp_path, monkeypatch)_migrated_state_db()reserved = _reserved_notice_session()@@ -13404,7 +13368,6 @@ def _avibe_sends(controller) -> list[str]:def test_a_walk_whose_preferred_rungs_all_fail_lands_in_the_workspace_inbox(tmp_path: Path,- monkeypatch,) -> None:"""Subordinate to HFR-079 — a non-empty ladder of undeliverable rungs must notdead-letter in silence, and must not wait six attempts to say so.@@ -13441,7 +13404,6 @@ def test_a_walk_whose_preferred_rungs_all_fail_lands_in_the_workspace_inbox(from core.delivery_evidence import ACK_EVIDENCE_RECEIPTfrom storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID- _no_background_web_push(monkeypatch)controller, _dispatcher, _touched = _live_turn_dispatcher()# The real schema, and deliberately NO row for ``sesGone`` and no reserved# workspace session: both absences are the premise.@@ -13507,7 +13469,6 @@ def test_a_walk_whose_preferred_rungs_all_fail_lands_in_the_workspace_inbox(def test_a_healthy_preferred_rung_never_reaches_the_workspace_inbox(tmp_path: Path,- monkeypatch,) -> None:"""The ORDERING property, which is what makes the mandatory rung safe to makemandatory.@@ -13538,7 +13499,6 @@ def test_a_healthy_preferred_rung_never_reaches_the_workspace_inbox(from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID- _no_background_web_push(monkeypatch)_migrated_state_db()assert _workspace_notice_session_rows() == [], "the premise: no reserved row yet"@@ -13641,7 +13601,6 @@ def test_an_archived_session_ladder_holds_exactly_one_workspace_rung(def test_replaying_the_workspace_walk_reuses_the_persisted_receipt(tmp_path: Path,- monkeypatch,) -> None:"""Subordinate to HFR-079/HFR-075 — restart cannot duplicate the workspace card.@@ -13672,7 +13631,6 @@ def test_replaying_the_workspace_walk_reuses_the_persisted_receipt(from storage.background import NOTICE_PENDINGfrom storage.db import get_cached_sqlite_engine- _no_background_web_push(monkeypatch)controller, _dispatcher, _touched = _live_turn_dispatcher()_migrated_state_db()@@ -13746,7 +13704,6 @@ def test_replaying_the_workspace_walk_reuses_the_persisted_receipt(def test_an_unwritable_workspace_inbox_still_dead_letters_visibly(tmp_path: Path,- monkeypatch,) -> None:"""Subordinate to HFR-079 — the residual, asserted rather than described.@@ -13770,7 +13727,6 @@ def test_an_unwritable_workspace_inbox_still_dead_letters_visibly(from core import failure_noticesfrom storage.background import NOTICE_FAILED, NOTICE_PENDING- _no_background_web_push(monkeypatch)controller, _dispatcher, _touched = _live_turn_dispatcher()_migrated_state_db()@@ -14157,7 +14113,6 @@ def test_a_captured_origin_lights_up_the_scope_and_owner_dm_rungs(tmp_path: Pathdef test_the_workspace_card_carries_the_creation_origin(tmp_path: Path,- monkeypatch,) -> None:"""The half of the gate that is about the WORKSPACE notice, not the owner DM.@@ -14181,7 +14136,6 @@ def test_the_workspace_card_carries_the_creation_origin(from storage.background import NOTICE_SENTfrom vibe.i18n import t as i18n_t- _no_background_web_push(monkeypatch)controller, _dispatcher, _touched = _live_turn_dispatcher()_migrated_state_db()diff --git a/tests/test_model_hub_local_error_details.py b/tests/test_model_hub_local_error_details.pyindex dc3776605..94c382687 100644--- a/tests/test_model_hub_local_error_details.py+++ b/tests/test_model_hub_local_error_details.py@@ -489,7 +489,6 @@ def test_local_details_authorized_in_history_and_live_events()published = []monkeypatch.setattr(message_mirror, "_publish_session_message", published.append)- monkeypatch.setattr("core.web_push_notifications.maybe_notify_inbox_message", lambda *_args: None)message_mirror.persist_agent_message(MessageContext(user_id="U1", channel_id="C1", platform="avibe",diff --git a/tests/test_models_dev_catalog.py b/tests/test_models_dev_catalog.pyindex 59d8551c9..7ce7f4cec 100644--- a/tests/test_models_dev_catalog.py+++ b/tests/test_models_dev_catalog.py@@ -467,6 +467,7 @@ def test_cached_catalog_read_does_not_wait_on_a_foreground_fetch(monkeypatch, tmassert read == [_catalog()][email protected]_catalog_refreshdef test_first_catalog_read_reports_one_fetch_in_flight_until_it_fails(monkeypatch, tmp_path):"""MH-PRICE-014: With no cached copy, readers start one fetch and say one is coming; after a failure they do not."""@@ -491,9 +492,16 @@ def test_first_catalog_read_reports_one_fetch_in_flight_until_it_fails(monkeypatreader.join(timeout=5)assert models_dev_catalog.load_models_dev_catalog_with_date() == ({}, None, True)release.set()- for thread in threading.enumerate():- if thread.name == "models-dev-refresh":- thread.join(timeout=5)++ def join_refreshes():+ for thread in threading.enumerate():+ if thread.name == "models-dev-refresh":+ thread.join(timeout=5)++ join_refreshes()assert fetches == ["models-dev-refresh"]# The fetch failed: the next read retries it, but no longer promises prices.assert models_dev_catalog.load_models_dev_catalog_with_date() == ({}, None, False)+ # That retry runs on its own thread: it must finish while this test's fetch+ # and cache path are still patched, not after teardown restores the real ones.+ join_refreshes()diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.pyindex c0dcce563..7d22b17df 100644--- a/tests/test_web_push_notifications.py+++ b/tests/test_web_push_notifications.py@@ -11,6 +11,10 @@ from storage.settings_service import upsert_scopefrom vibe import remote_accessfrom vibe.authorization import AuthorizationContext, context_from_session_payload+# These tests call the sender synchronously and stub `threading.Thread` wherever+# they schedule it, so no delayed thread outlives them.+pytestmark = pytest.mark.real_web_push_sender+@pytest.fixture(autouse=True)def _clear_recent_delivery_dispositions():