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
test: de-flake CI tests that turned main red and shrink the baselines (#439)
Ruben Lütke23d1fe40e08e
diff --git a/jarvis/autostart/macos.py b/jarvis/autostart/macos.pyindex 5b0947e464..2f0374125d 100644--- a/jarvis/autostart/macos.py+++ b/jarvis/autostart/macos.py@@ -20,7 +20,7 @@ import loggingimport plistlibimport subprocessimport sys-from pathlib import Path+from pathlib import Path, PurePathfrom jarvis.core.branding import MACOS_APP_DIR_NAME as _APP_DIR_NAMEfrom jarvis.core.branding import MACOS_AUTOSTART_LABEL as _LABEL@@ -89,7 +89,7 @@ def _write_plist_atomically(path: Path, plist: dict) -> None:raise-def retarget_launch_agent(bundle: Path) -> bool:+def retarget_launch_agent(bundle: PurePath) -> bool:"""Point an existing LaunchAgent at ``bundle`` after the app moved.The entry names the app by absolute path. Whoever moves the bundle has todiff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.pyindex 67001ef652..158f91a387 100644--- a/jarvis/missions/kontrollierer/orchestrator.py+++ b/jarvis/missions/kontrollierer/orchestrator.py@@ -345,6 +345,31 @@ def _safe_read_text(path: Path) -> str:return ""+# Windows antivirus and the search indexer briefly hold files that were just+# copied into a snapshot tree, and renaming the tree's directory then fails+# with WinError 5/32 although nothing is wrong. Seen under parallel load+# (2026-10-07): the archive returned None and the worker's deliverable was not+# archived. A short bounded retry rides that out; any other error class still+# fails at once, and the final PermissionError is re-raised unchanged.+_SNAPSHOT_RENAME_RETRY_DELAYS_S: tuple[float, ...] = (+ 0.0, 0.05, 0.1, 0.2, 0.4, 0.8, 1.6,+)+++def _rename_with_retry(src: Path, dst: Path) -> None:+ last_error: PermissionError | None = None+ for delay_s in _SNAPSHOT_RENAME_RETRY_DELAYS_S:+ if delay_s:+ time.sleep(delay_s)+ try:+ src.replace(dst)+ return+ except PermissionError as exc: # transient share lock: retried, re-raised below+ last_error = exc+ if last_error is not None:+ raise last_error++def _real_diff_is_empty(diff_text: str) -> bool:"""True iff the diff carries no foreign hunks after strippingmanaged persona files.@@ -2796,17 +2821,17 @@ class Kontrollierer:# exchange flags.moved_previous = Falseif files_root.exists():- files_root.replace(previous_root)+ _rename_with_retry(files_root, previous_root)moved_previous = Truetry:- staged_root.replace(files_root)+ _rename_with_retry(staged_root, files_root)except OSError:if (moved_previousand previous_root.exists()and not files_root.exists()):- previous_root.replace(files_root)+ _rename_with_retry(previous_root, files_root)raiseif moved_previous:shutil.rmtree(previous_root, ignore_errors=True)diff --git a/jarvis/society/browser/live_runner.py b/jarvis/society/browser/live_runner.pyindex e18035d62d..3e32e7af11 100644--- a/jarvis/society/browser/live_runner.py+++ b/jarvis/society/browser/live_runner.py@@ -222,8 +222,12 @@ class Worker:if self.owns_context:await self.context.route("**/*", route_request)- # Chromium can return its first page before publishing the CDP port file.- async with asyncio.timeout(15):+ # Chromium can return its first page before publishing the CDP port+ # file. A cold first launch (fresh profile, antivirus scanning the+ # binary, a loaded ARM machine) has taken longer than 15 s, which+ # failed the start long before the caller's 90 s start budget+ # (``_START_TIMEOUT_S`` in live.py). Stay inside that budget.+ async with asyncio.timeout(60):while True:try:port = int((profile / "DevToolsActivePort").read_text().splitlines()[0])@@ -561,8 +565,12 @@ class Worker:if len(candidates) == 1:self.page = candidates[0]else:+ # Chrome updates its native caption after the page title, so+ # right after a navigation (a form submit, an upload) no tab+ # matches it yet. Visibility then decides among ALL tabs+ # instead of failing a single-tab run as "ambiguous".visible = []- for page in candidates:+ for page in candidates or list(self.tabs.values()):if await page.evaluate("document.visibilityState === 'visible'"):visible.append(page)if len(visible) == 1:diff --git a/scripts/ci/test-baseline-linux.json b/scripts/ci/test-baseline-linux.jsonindex 59b5e2fd37..e2cc044b40 100644--- a/scripts/ci/test-baseline-linux.json+++ b/scripts/ci/test-baseline-linux.json@@ -1,14 +1,6 @@{"comment": "Known test failures. Generated by scripts/ci/ratchet_tests.py update from one or more full CI runs on main (the union, so timing-sensitive tests that flip between runs are covered); entries may only be removed by hand, never added to hide a regression.","known_failures": [- "pytest::internal",- "tests.integration.test_ollama_catalog_is_current::test_runtime_default_is_not_a_year_old[embeddinggemma]",- "tests.integration.test_ollama_catalog_is_current::test_runtime_default_is_not_a_year_old[qwen3-embedding:4b]",- "tests.unit.agentic_ide.test_folders_search::test_device_name_falls_back_to_the_hostname",- "tests.unit.codex_app_server.test_transport::test_missing_dedicated_profile_is_a_login_required_capability",- "tests.unit.codex_app_server.test_transport::test_reaper_launch_failure_releases_guard_and_state",- "tests.unit.codex_app_server.test_transport::test_subscription_login_guard_covers_process_and_reaper",- "tests.unit.codex_app_server.test_transport::test_subscription_login_spawn_failure_releases_guard",- "tests.unit.pointer.test_turn::test_crop_radius_forwarded_to_default_resolver"+ "pytest::internal"]}diff --git a/scripts/ci/test-baseline-macos.json b/scripts/ci/test-baseline-macos.jsonindex 1505af802c..e289460fee 100644--- a/scripts/ci/test-baseline-macos.json+++ b/scripts/ci/test-baseline-macos.json@@ -1,7 +1,5 @@{"comment": "Known test failures. Generated by scripts/ci/ratchet_tests.py update from one or more full CI runs on main (the union, so timing-sensitive tests that flip between runs are covered); entries may only be removed by hand, never added to hide a regression.","flaky_files": [],- "known_failures": [- "tests.unit.test_bare_jarvis_starts_desktop::test_readme_still_documents_bare_jarvis_as_the_desktop_entry"- ]+ "known_failures": []}diff --git a/scripts/ci/test-baseline-windows.json b/scripts/ci/test-baseline-windows.jsonindex 351a3eab15..e289460fee 100644--- a/scripts/ci/test-baseline-windows.json+++ b/scripts/ci/test-baseline-windows.json@@ -1,28 +1,5 @@{"comment": "Known test failures. Generated by scripts/ci/ratchet_tests.py update from one or more full CI runs on main (the union, so timing-sensitive tests that flip between runs are covered); entries may only be removed by hand, never added to hide a regression.",- "flaky_files": [- "tests/missions/kontrollierer/test_capture_diff.py",- "tests/missions/kontrollierer/test_external_write_verification.py",- "tests/unit/dictation/test_polish_timeout_ramp.py",- "tests/unit/memory/wiki/test_voice_bridge_realtime.py"- ],- "known_failures": [- "tests.integration.test_ollama_catalog_is_current::test_runtime_default_is_not_a_year_old[embeddinggemma]",- "tests.integration.test_ollama_catalog_is_current::test_runtime_default_is_not_a_year_old[qwen3-embedding:4b]",- "tests.missions.test_env::test_seed_creates_real_symlink_when_privilege_available",- "tests.missions.test_job_object::test_async_context_manager_closes_on_exit",- "tests.missions.test_job_object::test_close_kills_assigned_process",- "tests.missions.test_job_object::test_ctypes_fallback_kills_assigned_process_without_pywin32",- "tests.missions.workers.test_api_agent_tools::test_command_cancellation_reaps_descendant_tree",- "tests.missions.workers.test_api_agent_tools::test_command_timeout_reaps_descendant_tree",- "tests.unit.agentic_ide.test_composer_hedge::test_a_defective_brief_teaches_nothing",- "tests.unit.agentic_ide.test_composer_hedge::test_a_delivered_brief_teaches_the_writers_threshold",- "tests.unit.audio.test_vad_bundled_model::test_pyinstaller_spec_collects_bundled_vad_asset",- "tests.unit.autostart.test_macos::test_a_current_login_item_is_left_alone",- "tests.unit.autostart.test_macos::test_a_moved_app_takes_its_login_item_along",- "tests.unit.codex_app_server.test_transport::test_exact_unix_codex_runtime_aliases_must_target_trusted_binary",- "tests.unit.core.test_dictation_paste_chord_custom::test_a_custom_chord_reports_paste_sent_and_keeps_the_clipboard",- "tests.unit.ui.test_relaunch_properties::test_relaunch_properties_stick_on_a_real_window",- "tests/missions/kontrollierer/test_capture_diff.py::<crash>"- ]+ "flaky_files": [],+ "known_failures": []}diff --git a/tests/contract/native_window_probe.py b/tests/contract/native_window_probe.pyindex cf00337895..c73467085b 100644--- a/tests/contract/native_window_probe.py+++ b/tests/contract/native_window_probe.py@@ -65,10 +65,15 @@ async def main() -> None:assert value == "Typed through the preview", valueassert native.input_hwnd != native.hwndassert badge- native.input("click", {"x": 300 * scale, "y": y * 0.72})+ # Focus the address bar through Chrome's own location command, not+ # a click at a guessed toolbar position: on a slow runner the URL+ # never reached the omnibox within the wait (CI run 37599288714).+ # The command and the characters go to the same window queue, so+ # the omnibox owns focus before the first character arrives.+ native.input("key", {"key": "Control+l"})native.input("text", {"text": "about:blank#jarvis-input-probe"})native.input("key", {"key": "Enter"})- await page.wait_for_url("about:blank#jarvis-input-probe", timeout=5000)+ await page.wait_for_url("about:blank#jarvis-input-probe", timeout=20_000)print(json.dumps({"typed": value, "badge": badge, "address": page.url}))finally:if native:diff --git a/tests/missions/kontrollierer/test_capture_diff.py b/tests/missions/kontrollierer/test_capture_diff.pyindex abe62fc5b5..a7c4facece 100644--- a/tests/missions/kontrollierer/test_capture_diff.py+++ b/tests/missions/kontrollierer/test_capture_diff.py@@ -13,54 +13,101 @@ hallucinates from a blank input.These tests exercise the helper against real on-disk git worktrees sothe assertions cover the actual behaviour of `git add -N`, `git diffHEAD`, and `git ls-files --others --exclude-standard` together.++The worktrees branch off a tiny seed repository built in the test's temp+directory, never off the host checkout: a full checkout of this repository+per test cost 10-16 s on a desktop, contended for the shared repository lock+with every other session, left `test/*` branches in the developer's repo, and+pushed the product's 10 s git caps and the CI per-file budget into timeouts on+a loaded runner. The seed carries the shape the tests rely on — a tracked+README.md and AGENTS.md, and a `/*.log` ignore rule like the host repo's."""from __future__ import annotations+import osimport shutilimport subprocessimport uuid+from collections.abc import Iterator, Mappingfrom pathlib import Pathimport pytest+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSfrom jarvis.missions.isolation.worktree import WorktreeManagerfrom jarvis.missions.kontrollierer.orchestrator import Kontrolliererfrom jarvis.missions.worker_runtime.workspace import materialize_worker_contract-PROJECT_ROOT = Path(__file__).resolve().parents[3]---def _git(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:+# Fixture-side git calls ignore the developer's or runner's global and system+# config (signing, hooks, templates, autocrlf) and carry their own identity.+_SEED_GIT_ENV = {+ **os.environ,+ "GIT_CONFIG_GLOBAL": os.devnull,+ "GIT_CONFIG_NOSYSTEM": "1",+ "GIT_AUTHOR_NAME": "Seed",+ "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Seed",+ "GIT_COMMITTER_EMAIL": "[email protected]",+}+++def _git(+ *args: str, cwd: Path | None = None, env: Mapping[str, str] | None = None+) -> subprocess.CompletedProcess[str]:return subprocess.run( # noqa: S603["git", *args],cwd=str(cwd) if cwd else None,check=False,capture_output=True,text=True,- # Worktree materialization can exceed 15 seconds while other mission- # or release sessions briefly hold the shared repository lock.- timeout=60.0,- )+ encoding="utf-8",+ env=dict(env) if env is not None else None,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ # Generous ceiling for a loaded CI runner; a healthy call on the tiny+ # seed repo returns in milliseconds.+ timeout=120.0,+ )++[email protected](scope="module")+def seed_repo(tmp_path_factory: pytest.TempPathFactory) -> Path:+ """A one-commit repository on `main` that every worktree branches off."""+ if shutil.which("git") is None:+ pytest.skip("git not in PATH")+ repo = tmp_path_factory.mktemp("capture-diff-seed")+ (repo / "README.md").write_text("# Seed repository\n", encoding="utf-8")+ (repo / "AGENTS.md").write_text("# Seed agent rules\n", encoding="utf-8")+ (repo / ".gitignore").write_text("/*.log\n", encoding="utf-8")+ for args in (+ ("-c", "init.defaultBranch=main", "init"),+ ("add", "README.md", "AGENTS.md", ".gitignore"),+ ("-c", "commit.gpgsign=false", "commit", "-m", "seed"),+ ):+ result = _git(*args, cwd=repo, env=_SEED_GIT_ENV)+ if result.returncode != 0:+ pytest.fail(f"git {' '.join(args)} failed: {result.stderr.strip()[:300]}")+ return repo@pytest.fixture-def worktree(tmp_path: Path):- """Yield a fresh git worktree branched off `main` in the host repo.+def worktree(tmp_path: Path, seed_repo: Path) -> Iterator[Path]:+ """Yield a fresh git worktree branched off the seed repo's `main`.Cleans up the worktree + temporary branch after the test, even on- failure, so the host repo's `.git/worktrees/` doesn't accumulate- dangling entries.+ failure, so the seed repo's `.git/worktrees/` stays small."""branch = f"test/capture-diff-{uuid.uuid4().hex[:8]}"wt = tmp_path / "wt"- add = _git("worktree", "add", "-b", branch, str(wt), "main", cwd=PROJECT_ROOT)+ add = _git(+ "worktree", "add", "-b", branch, str(wt), "main", cwd=seed_repo, env=_SEED_GIT_ENV+ )if add.returncode != 0:- pytest.skip(f"git worktree add failed: {add.stderr.strip()[:200]}")+ pytest.fail(f"git worktree add failed: {add.stderr.strip()[:300]}")try:yield wtfinally:- _git("worktree", "remove", "--force", str(wt), cwd=PROJECT_ROOT)- _git("branch", "-D", branch, cwd=PROJECT_ROOT)+ _git("worktree", "remove", "--force", str(wt), cwd=seed_repo, env=_SEED_GIT_ENV)+ _git("branch", "-D", branch, cwd=seed_repo, env=_SEED_GIT_ENV)@pytest.fixture@@ -130,12 +177,12 @@ _GIT_AVAILABLE = shutil.which("git") is not None@pytest.fixture-def lean_manager(tmp_path: Path) -> WorktreeManager:+def lean_manager(tmp_path: Path, seed_repo: Path) -> WorktreeManager:"""A WorktreeManager whose outputs land under tmp_path. The lean path uses`git init` (no host-repo checkout), so repo_root only needs to be a real- git repo for the manager's own bookkeeping — point it at the host repo."""+ git repo for the manager's own bookkeeping — the seed repo is one."""return WorktreeManager(- repo_root=PROJECT_ROOT, outputs_root=tmp_path / "lean-outputs"+ repo_root=seed_repo, outputs_root=tmp_path / "lean-outputs")@@ -457,6 +504,45 @@ def test_snapshot_promotion_failure_rolls_back_previous_durable_draft(assert not list(draft_artifacts.glob(".files-previous-*"))+def test_snapshot_promotion_rides_out_a_transient_share_lock(+ worktree: Path,+ kontrollierer: Kontrollierer,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An antivirus or indexer handle on a just-copied file makes the staged+ tree's rename fail with WinError 5 for a moment (reproduced under parallel+ load on Windows). The archive must retry, not drop the deliverable."""+ # The real retry schedule stays in place: the two simulated denials cost+ # 50 ms, and the remaining attempts still cover a genuine scanner lock on+ # this host's freshly copied file.+ output = worktree / "report.html"+ output.write_text("<!doctype html><p>deliverable</p>", encoding="utf-8")+ real_replace = Path.replace+ denials: list[str] = []++ def locked_twice(source: Path, target: Path) -> Path:+ if source.name.startswith(".files-next-") and len(denials) < 2:+ denials.append(source.name)+ raise PermissionError(5, "Access is denied", str(source))+ return real_replace(source, target)++ monkeypatch.setattr(Path, "replace", locked_twice)+ mission_dir = tmp_path / "mission_root"+ mission_dir.mkdir()++ artifacts = kontrollierer._archive_task_artifacts(+ worktree=worktree, mission_dir=mission_dir, task_id="share-lock",+ )++ assert len(denials) == 2+ assert artifacts is not None+ assert (artifacts / "files" / "report.html").read_text(encoding="utf-8") == (+ "<!doctype html><p>deliverable</p>"+ )+ assert not list(artifacts.glob(".files-next-*"))++# --- 2026-05-27 hardening audit: archive must round-trip non-ASCII and# gitignored deliverables, and must NOT leak materialized contract files.@@ -578,7 +664,7 @@ def _commit(cwd: Path, *paths: str, message: str) -> None:_git("add", *paths, cwd=cwd)_git("-c", "user.name=Worker", "-c", "[email protected]",- "commit", "-m", message, cwd=cwd,+ "-c", "commit.gpgsign=false", "commit", "-m", message, cwd=cwd,)diff --git a/tests/missions/kontrollierer/test_external_write_verification.py b/tests/missions/kontrollierer/test_external_write_verification.pyindex c80feaaddc..c23023c1cb 100644--- a/tests/missions/kontrollierer/test_external_write_verification.py+++ b/tests/missions/kontrollierer/test_external_write_verification.py@@ -20,6 +20,7 @@ These tests use a real on-disk git worktree plus a sibling external directoryfrom __future__ import annotationsimport json+import osimport subprocessfrom pathlib import Path@@ -32,6 +33,16 @@ from jarvis.missions.kontrollierer.orchestrator import (from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+# The fixture's git calls ignore the developer's or runner's global and system+# config (commit signing, hooks, templates), which could otherwise prompt, fail+# or slow the fixture commit down.+_FIXTURE_GIT_ENV = {+ **os.environ,+ "GIT_CONFIG_GLOBAL": os.devnull,+ "GIT_CONFIG_NOSYSTEM": "1",+}++def _git(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:return subprocess.run( # noqa: S603["git", *args],@@ -40,8 +51,11 @@ def _git(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[strcapture_output=True,text=True,encoding="utf-8",+ env=_FIXTURE_GIT_ENV,creationflags=NO_WINDOW_CREATIONFLAGS,- timeout=15.0,+ # Generous ceiling for a loaded CI runner; each call on this one-file+ # repository normally returns in milliseconds.+ timeout=120.0,)diff --git a/tests/missions/test_env.py b/tests/missions/test_env.pyindex 8793aec67e..fa14d34d9e 100644--- a/tests/missions/test_env.py+++ b/tests/missions/test_env.py@@ -290,8 +290,13 @@ def test_seed_creates_real_symlink_when_privilege_available(assert target.is_symlink(), (f"target must be a symlink, but is {target.stat()!s}")- # Read the link back -- must resolve to the source.- assert Path(os.readlink(target)).resolve() == source.resolve()+ # Read the link back -- must resolve to the source. On Windows readlink+ # returns the stored NT substitute name, which carries the extended-length+ # "\\?\" prefix that Path.resolve() keeps; it names the same path.+ link = os.readlink(target)+ if link.startswith("\\\\?\\"):+ link = link[len("\\\\?\\"):]+ assert Path(link).resolve() == source.resolve()def test_seed_eperm_keeps_target_missing(diff --git a/tests/missions/test_job_object.py b/tests/missions/test_job_object.pyindex 68dbc6c46f..b4501b1db8 100644--- a/tests/missions/test_job_object.py+++ b/tests/missions/test_job_object.py@@ -22,13 +22,47 @@ from jarvis.missions.isolation.job_object import (_IS_WIN = sys.platform == "win32"# CREATE_BREAKAWAY_FROM_JOB — the test runner itself might already be in a-# job (e.g. under VS Code / Windows Terminal), so the worker MUST be spawned-# with breakaway, otherwise AssignProcessToJobObject fails with-# ERROR_ACCESS_DENIED. The constant only ships in subprocess from Python 3.7-# onward — we take it from subprocess when present, otherwise the hex literal.+# job (VS Code, Windows Terminal, the py launcher, a CI runner). Breakaway+# keeps the sleeper out of that job when the job allows it. A job that forbids+# breakaway (the GitHub Actions Windows runner) makes CreateProcess itself fail+# with ERROR_ACCESS_DENIED, so ``_spawn_sleeper`` then spawns without the bit,+# exactly like ``create_worker_subprocess``: the sleeper stays in the runner's+# job and the test's job nests inside it (Windows 8+ nested jobs), which still+# kills the sleeper on close._CREATE_BREAKAWAY_FROM_JOB = getattr(subprocess, "CREATE_BREAKAWAY_FROM_JOB", 0x01000000)_CREATE_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)_CREATE_NEW_PROCESS_GROUP = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)+_SLEEPER_ARGV = [sys.executable, "-c", "import time; time.sleep(60)"]+# Upper bound for the OS to reap a killed sleeper. The poll loop ends as soon+# as the process is gone (usually <100 ms); the bound only matters on a loaded+# CI runner.+_REAP_TIMEOUT_S = 15.0+++def _spawn_sleeper() -> subprocess.Popen[bytes]:+ """Start a 60 s sleeper, outside the runner's job when that is allowed."""+ base_flags = _CREATE_NO_WINDOW | _CREATE_NEW_PROCESS_GROUP+ try:+ return subprocess.Popen( # noqa: S603 - controlled test argv+ _SLEEPER_ARGV, creationflags=base_flags | _CREATE_BREAKAWAY_FROM_JOB+ )+ except PermissionError:+ # The enclosing job forbids breakaway; nest instead (see above).+ return subprocess.Popen( # noqa: S603 - controlled test argv+ _SLEEPER_ARGV, creationflags=base_flags+ )+++async def _wait_reaped(proc: subprocess.Popen[bytes]) -> None:+ deadline = time.monotonic() + _REAP_TIMEOUT_S+ while time.monotonic() < deadline and proc.poll() is None: # noqa: ASYNC110+ await asyncio.sleep(0.05)+++def _kill_leftover(proc: subprocess.Popen[bytes]) -> None:+ if proc.poll() is None:+ proc.kill()+ proc.wait(timeout=_REAP_TIMEOUT_S)# --- No-op branch (all platforms) --------------------------------------------@@ -69,15 +103,9 @@ async def test_close_kills_assigned_process() -> None:psutil = pytest.importorskip("psutil")# Long-lived sleeper — runs 60s if not killed.- proc = subprocess.Popen( # noqa: ASYNC220, S603 — controlled args- [sys.executable, "-c", "import time; time.sleep(60)"],- creationflags=(- _CREATE_BREAKAWAY_FROM_JOB | _CREATE_NO_WINDOW | _CREATE_NEW_PROCESS_GROUP- ),- )+ proc = _spawn_sleeper()try:- # Wait until the subprocess actually exists- await asyncio.sleep(0.1)+ # CreateProcess has returned, so the process exists already.assert psutil.pid_exists(proc.pid), "Subprocess should have started"job = WindowsJobObject("kill-on-close-test")@@ -85,21 +113,13 @@ async def test_close_kills_assigned_process() -> None:# Closing should atomically kill the processawait job.close()- # Wait up to 2s for the OS to reap — usually <100ms- deadline = time.monotonic() + 2.0- while time.monotonic() < deadline:- if proc.poll() is not None:- break- await asyncio.sleep(0.05)-+ await _wait_reaped(proc)assert proc.poll() is not None, ("Process should have been killed by job close")finally:# Safety net in case the test logic failed- if proc.poll() is None:- proc.kill()- proc.wait(timeout=2)+ _kill_leftover(proc)@pytest.mark.skipif(not _IS_WIN, reason="Job objects are Windows-only")@@ -122,54 +142,33 @@ async def test_close_is_idempotent() -> None:@pytest.mark.skipif(not _IS_WIN, reason="Job objects are Windows-only")async def test_async_context_manager_closes_on_exit() -> None:pytest.importorskip("psutil")- proc = subprocess.Popen( # noqa: ASYNC220, S603- [sys.executable, "-c", "import time; time.sleep(60)"],- creationflags=(- _CREATE_BREAKAWAY_FROM_JOB | _CREATE_NO_WINDOW | _CREATE_NEW_PROCESS_GROUP- ),- )+ proc = _spawn_sleeper()try:- await asyncio.sleep(0.1)async with WindowsJobObject("ctx-mgr-test") as job:job.assign(proc.pid)assert not job.closed# After the with block: process must be dead- deadline = time.monotonic() + 2.0- while time.monotonic() < deadline:- if proc.poll() is not None:- break- await asyncio.sleep(0.05)+ await _wait_reaped(proc)assert proc.poll() is not Nonefinally:- if proc.poll() is None:- proc.kill()- proc.wait(timeout=2)+ _kill_leftover(proc)@pytest.mark.skipif(not _IS_WIN, reason="Job objects are Windows-only")async def test_ctypes_fallback_kills_assigned_process_without_pywin32() -> None:"""Base Windows installs retain kernel-enforced tree containment."""- proc = subprocess.Popen( # noqa: ASYNC220, S603 - controlled test argv- [sys.executable, "-c", "import time; time.sleep(60)"],- creationflags=(- _CREATE_BREAKAWAY_FROM_JOB | _CREATE_NO_WINDOW | _CREATE_NEW_PROCESS_GROUP- ),- )+ proc = _spawn_sleeper()try:job = job_module._Win32CtypesJobObjectImpl("ctypes-fallback-test", allow_breakaway=False)job.assign(proc.pid)await job.close()- deadline = time.monotonic() + 2.0- while time.monotonic() < deadline and proc.poll() is None: # noqa: ASYNC110- await asyncio.sleep(0.05)+ await _wait_reaped(proc)assert proc.poll() is not Nonefinally:- if proc.poll() is None:- proc.kill()- proc.wait(timeout=2)+ _kill_leftover(proc)@pytest.mark.skipif(not _IS_WIN, reason="Job objects are Windows-only")diff --git a/tests/missions/workers/test_api_agent_tools.py b/tests/missions/workers/test_api_agent_tools.pyindex 9346e130e9..a6bd3c3e50 100644--- a/tests/missions/workers/test_api_agent_tools.py+++ b/tests/missions/workers/test_api_agent_tools.py@@ -319,8 +319,17 @@ def _tree_script(tmp_path: Path, *, fast_leader: bool = False) -> Path:return script+# Bounds for event-driven waits below; each returns as soon as its condition+# holds. On Windows a command runs behind a PowerShell containment launcher,+# whose start-up alone took 10-20 s per command on the loaded CI runner (this+# file ran 116-233 s there against ~10 s on a desktop), so a short bound+# measures the runner, not the containment.+_TREE_START_TIMEOUT_S = 120.0+_TREE_REAP_TIMEOUT_S = 30.0++async def _wait_for_pid_file(path: Path) -> int:- deadline = time.monotonic() + 5.0+ deadline = time.monotonic() + _TREE_START_TIMEOUT_Swhile time.monotonic() < deadline:if path.is_file(): # noqa: ASYNC240 - tiny test synchronization probereturn int(@@ -332,7 +341,7 @@ async def _wait_for_pid_file(path: Path) -> int:async def _assert_pid_gone(pid: int) -> None:psutil = pytest.importorskip("psutil")- deadline = time.monotonic() + 5.0+ deadline = time.monotonic() + _TREE_REAP_TIMEOUT_Swhile time.monotonic() < deadline:if not psutil.pid_exists(pid):return@@ -343,9 +352,48 @@ async def _assert_pid_gone(pid: int) -> None:raise AssertionError(f"descendant process {pid} survived command cleanup")+class _TimeoutClockStartsWithTree:+ """Stands in for ``asyncio`` inside ``api_agent_tools`` for one command.++ The command's timeout clock normally starts when the launcher gate opens.+ On a loaded runner the launcher can take longer than any short timeout to+ start the target, so the timeout fired before the descendant under test+ existed. This proxy delays only the FIRST ``wait_for`` — the command's own+ timeout wait — until the descendant has written its pid file; the real+ timeout, kill and Job/process-group cleanup then run unchanged. Every other+ attribute is the real ``asyncio``.+ """++ def __init__(self, pid_file: Path) -> None:+ self._pid_file = pid_file+ self._armed = True++ def __getattr__(self, name: str) -> object:+ return getattr(asyncio, name)++ async def wait_for(+ self,+ aw: object,+ timeout: float | None, # noqa: ASYNC109 - mirrors asyncio.wait_for+ ) -> object:+ if self._armed:+ self._armed = False+ try:+ await _wait_for_pid_file(self._pid_file)+ except BaseException:+ close = getattr(aw, "close", None)+ if callable(close):+ close()+ raise+ return await asyncio.wait_for(aw, timeout) # type: ignore[arg-type]++@pytest.mark.asyncio-async def test_command_timeout_reaps_descendant_tree(tmp_path: Path) -> None:+async def test_command_timeout_reaps_descendant_tree(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:_tree_script(tmp_path)+ monkeypatch.setattr(aat, "asyncio", _TimeoutClockStartsWithTree(tmp_path / "child.pid"))out, err = await execute_worker_tool_async("RunCommand",{"program": "python", "args": ["spawn_tree.py"], "timeout_s": 2.0},diff --git a/tests/unit/agentic_ide/test_composer_hedge.py b/tests/unit/agentic_ide/test_composer_hedge.pyindex ef1e318ee0..89ae85173e 100644--- a/tests/unit/agentic_ide/test_composer_hedge.py+++ b/tests/unit/agentic_ide/test_composer_hedge.py@@ -29,6 +29,12 @@ def _spoken_budget_does_not_clip_hedge_tests(monkeypatch: pytest.MonkeyPatch) ->BRIEF = "## Task\nMake the wake path faster.\n\n## Done when\n- It is faster."HEDGE_BRIEF = "## Task\nMake the wake path quick.\n\n## Done when\n- It is quick."+# How long a fake writer takes when a test measures its wall clock. A writer+# that returns instantly measures 0.0 s on Windows, whose ``time.monotonic``+# ticks every 15.6 ms (GetTickCount64), and the composer rightly refuses to+# learn a zero duration. Several ticks long, so the measured figure is > 0.+_MEASURABLE_WRITE_S = 0.05+@dataclassclass _Profile:@@ -465,6 +471,7 @@ async def test_a_delivered_brief_teaches_the_writers_threshold(leaves one measured duration behind under exactly that source."""async def _compose(**_kwargs: object) -> str:+ await asyncio.sleep(_MEASURABLE_WRITE_S)return BRIEFmonkeypatch.setattr(@@ -492,6 +499,7 @@ async def test_a_defective_brief_teaches_nothing(async def _compose(*, brain: object, **_kwargs: object) -> str:if getattr(brain, "name", "") == "broken":return "ok" # far too short to be a brief — a defect, not a brief+ await asyncio.sleep(_MEASURABLE_WRITE_S)return BRIEFmonkeypatch.setattr(diff --git a/tests/unit/agentic_ide/test_folders_search.py b/tests/unit/agentic_ide/test_folders_search.pyindex 79af3395c7..accaf1198b 100644--- a/tests/unit/agentic_ide/test_folders_search.py+++ b/tests/unit/agentic_ide/test_folders_search.py@@ -90,14 +90,33 @@ def test_device_name_is_never_empty() -> None:assert device.device_name().strip()-def test_device_name_falls_back_to_the_hostname(monkeypatch: pytest.MonkeyPatch) -> None:- """Every per-OS lookup failing must still yield something readable."""[email protected]("host_platform", ["darwin", "linux", "win32"])+def test_device_name_falls_back_to_the_hostname(+ monkeypatch: pytest.MonkeyPatch, host_platform: str+) -> None:+ """Every per-OS lookup failing must still yield something readable.++ The platform is pinned and every per-OS source is made to fail, including+ the Linux ``/etc/hostname`` file, so the runner's own hostname can never+ answer instead of the fallback under test.+ """+ real_read_text = Path.read_text++ def no_etc_hostname(self: Path, *args: object, **kwargs: object) -> str:+ if self.as_posix() == "/etc/hostname":+ raise FileNotFoundError(self)+ return real_read_text(self, *args, **kwargs)+device.reset_cache()+ monkeypatch.setattr(device.sys, "platform", host_platform)monkeypatch.setattr(device, "_run", lambda argv: None)+ monkeypatch.setattr(Path, "read_text", no_etc_hostname)monkeypatch.setattr(device.platform, "node", lambda: "Rubens-MacBook-Pro.local")monkeypatch.delenv("COMPUTERNAME", raising=False)- assert device.device_name() == "Rubens MacBook Pro"- device.reset_cache()+ try:+ assert device.device_name() == "Rubens MacBook Pro"+ finally:+ device.reset_cache()def test_device_name_prefers_the_friendly_macos_name(monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unit/autostart/test_macos.py b/tests/unit/autostart/test_macos.pyindex fb738410a0..312ac5c82c 100644--- a/tests/unit/autostart/test_macos.py+++ b/tests/unit/autostart/test_macos.py@@ -7,7 +7,7 @@ only the pure plist write/parse path — exactly what we can prove anywhere.from __future__ import annotationsimport plistlib-from pathlib import Path+from pathlib import Path, PurePosixPathimport pytest@@ -115,6 +115,9 @@ def test_install_leaves_no_temp_file_when_the_plist_write_fails(_OLD_APP = "/Users/u/Applications/Personal Jarvis.app"_NEW_APP = "/Applications/Personal Jarvis.app"+# The bundle path is a macOS path on every host that runs these tests: a+# WindowsPath would render it with backslashes and never match the plist.+_bundle = PurePosixPathdef test_a_moved_app_takes_its_login_item_along(monkeypatch, tmp_path: Path) -> None:@@ -123,7 +126,7 @@ def test_a_moved_app_takes_its_login_item_along(monkeypatch, tmp_path: Path) ->monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)MacOSAutostart().install(_spec())- assert macos.retarget_launch_agent(Path(_NEW_APP)) is True+ assert macos.retarget_launch_agent(_bundle(_NEW_APP)) is Truewith (tmp_path / "com.personal-jarvis.autostart.plist").open("rb") as fh:data = plistlib.load(fh)@@ -140,14 +143,14 @@ def test_a_current_login_item_is_left_alone(monkeypatch, tmp_path: Path) -> Noneentry = tmp_path / "com.personal-jarvis.autostart.plist"before = entry.read_bytes()- assert macos.retarget_launch_agent(Path(_OLD_APP)) is False+ assert macos.retarget_launch_agent(_bundle(_OLD_APP)) is Falseassert entry.read_bytes() == beforedef test_moving_the_app_never_switches_autostart_back_on(monkeypatch, tmp_path: Path) -> None:monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)- assert macos.retarget_launch_agent(Path(_NEW_APP)) is False+ assert macos.retarget_launch_agent(_bundle(_NEW_APP)) is Falseassert not list(tmp_path.iterdir())@@ -158,7 +161,7 @@ def test_moving_the_app_never_starts_it(monkeypatch, tmp_path: Path) -> None:calls: list[tuple[str, ...]] = []monkeypatch.setattr(macos, "_launchctl", lambda *argv: calls.append(argv) or True)- macos.retarget_launch_agent(Path(_NEW_APP))+ macos.retarget_launch_agent(_bundle(_NEW_APP))assert calls == []@@ -167,4 +170,4 @@ def test_an_unreadable_login_item_does_not_fail_the_move(monkeypatch, tmp_path:monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)(tmp_path / "com.personal-jarvis.autostart.plist").write_bytes(b"not a plist")- assert macos.retarget_launch_agent(Path(_NEW_APP)) is False+ assert macos.retarget_launch_agent(_bundle(_NEW_APP)) is Falsediff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.pyindex e0b25b8c46..3c0ee7ba41 100644--- a/tests/unit/codex_app_server/test_transport.py+++ b/tests/unit/codex_app_server/test_transport.py@@ -91,6 +91,21 @@ def isolated_profile_lifecycle(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(transport, "_verify_spawn_binary", lambda _path: None)+def graphical_desktop_host(monkeypatch: pytest.MonkeyPatch) -> None:+ """Pin the host to a desktop that can host the interactive login.++ The login flow and the missing-profile status degrade on a headless Linux+ host (no DISPLAY / WAYLAND_DISPLAY, e.g. a CI runner) and on a Linux+ desktop without a terminal emulator. Tests about the desktop login flow+ must not inherit that from the machine running them; the degraded paths+ have their own dedicated tests.+ """+ monkeypatch.setattr(transport, "_headless_linux", lambda: False)+ monkeypatch.setattr(transport, "_pure_wayland_linux", lambda: False)+ monkeypatch.setattr(transport, "_linux_login_terminal_missing", lambda: False)++class FakeStdin:def __init__(self, process: FakeProcess) -> None:self.process = process@@ -1146,6 +1161,7 @@ def test_capability_revalidates_profile_after_login_status_probe(assert capability.reason == "profile changed during status"[email protected]("graphical_desktop_host")def test_missing_dedicated_profile_is_a_login_required_capability(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -1687,6 +1703,7 @@ async def test_disconnect_leaves_a_foreign_mutation_untouched(assert transport._subscription_profile_mutating is True[email protected]("graphical_desktop_host")def test_reaper_launch_failure_releases_guard_and_state(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -3438,6 +3455,13 @@ def test_exact_unix_codex_runtime_aliases_must_target_trusted_binary(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:+ if os.name != "posix":+ # Product code validates symlink aliases only on a POSIX host (Windows+ # gets ``.cmd`` wrappers instead). A Windows host that may create+ # symlinks returns ``os.readlink`` targets with the extended-length+ # path prefix, so the simulated Linux layout never matches the trusted+ # binary there.+ pytest.skip("Unix runtime aliases are only validated on a POSIX host")import jarvis.core.paths as pathsmonkeypatch.setattr(paths, "user_data_dir", lambda: tmp_path / "data")@@ -3503,6 +3527,7 @@ def test_exact_unix_codex_runtime_aliases_must_target_trusted_binary()[email protected]("graphical_desktop_host")def test_subscription_login_guard_covers_process_and_reaper(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -3597,6 +3622,7 @@ def test_subscription_login_guard_covers_process_and_reaper(assert transport._subscription_login_process is None[email protected]("graphical_desktop_host")def test_subscription_login_spawn_failure_releases_guard(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/unit/dictation/test_polish_timeout_ramp.py b/tests/unit/dictation/test_polish_timeout_ramp.pyindex 9abd886b4d..f20e127829 100644--- a/tests/unit/dictation/test_polish_timeout_ramp.py+++ b/tests/unit/dictation/test_polish_timeout_ramp.py@@ -20,14 +20,18 @@ What must stay true, and is what these tests pin:* the extra time stops at a ceiling the user owns;* a user who wants the old fixed behaviour gets it by saying so.-The client is faked, so what is asserted is the deadline the transport was-handed — not wall-clock timing, which would make this file flaky rather than-meaningful.+The client is faked and the pass's clock is frozen, so what is asserted is the+exact deadline the transport was handed — not wall-clock timing, which would+make this file flaky rather than meaningful (a loaded CI runner can spend a+few hundred milliseconds between computing the deadline and calling the+client, and the client is handed the time REMAINING)."""from __future__ import annotations+import timefrom dataclasses import dataclass, field+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -36,8 +40,8 @@ from jarvis.dictation import polishfrom jarvis.dictation.polish import polish_transcriptfrom jarvis.dictation.polish_client import POLISH_FAMILIES, PolishFamily-# The deadline is a difference of monotonic clock readings, so an exact budget-# can come back a few ULPs above its ceiling (1.2000000000007 <= 1.2 fails).+# The deadline is a difference of clock readings, so an exact budget can come+# back a few ULPs away from its value (1.2000000000007 <= 1.2 fails)._FLOAT_SLACK = 1e-9pytestmark = pytest.mark.asyncio@@ -89,7 +93,19 @@ class _FakeClient:@pytest.fixture(autouse=True)-def _fresh_breaker() -> None:+def _frozen_clock(monkeypatch: pytest.MonkeyPatch) -> None:+ """Stop the pass's monotonic clock so the remaining time IS the budget.++ Only the deadline arithmetic reads it; latency logging keeps its real+ ``perf_counter``.+ """+ monkeypatch.setattr(+ polish, "time", SimpleNamespace(monotonic=lambda: 1_000.0, perf_counter=time.perf_counter)+ )++[email protected](autouse=True)+def _fresh_breaker(_frozen_clock: None) -> None:polish.reset_polish_state()@@ -120,10 +136,9 @@ async def test_a_short_dictation_keeps_the_configured_ceiling("""deadline = await _deadline_for(monkeypatch, 20, _Cfg(polish_timeout_ms=1200))- # The walk hands the client the time REMAINING, so a few milliseconds of- # our own work are legitimately missing; what must not happen is the- # budget growing.- assert 1.0 < deadline <= 1.2 + _FLOAT_SLACK+ # The walk hands the client the time REMAINING; with the clock frozen that+ # is the whole budget, and what must not happen is the budget growing.+ assert deadline == pytest.approx(1.2, abs=_FLOAT_SLACK)async def test_a_long_dictation_is_given_more_time_than_a_short_one(@@ -142,7 +157,7 @@ async def test_a_long_dictation_is_given_more_time_than_a_short_one(# 60 words = 35 over the free allowance, 15 ms each on top of 1200 ms, and# still short of the 2000 ms cap — so this asserts the RAMP rather than# the ceiling the next test owns.- assert 1.5 < long <= 1.725 + _FLOAT_SLACK+ assert long == pytest.approx(1.725, abs=_FLOAT_SLACK)async def test_the_extra_time_stops_at_the_configured_maximum(@@ -157,7 +172,7 @@ async def test_the_extra_time_stops_at_the_configured_maximum(monkeypatch, 5000, _Cfg(polish_timeout_ms=1200, polish_timeout_max_ms=2500))- assert 2.3 < deadline <= 2.5 + _FLOAT_SLACK+ assert deadline == pytest.approx(2.5, abs=_FLOAT_SLACK)async def test_a_maximum_at_the_base_switches_the_ramp_off(@@ -173,7 +188,7 @@ async def test_a_maximum_at_the_base_switches_the_ramp_off(monkeypatch, 800, _Cfg(polish_timeout_ms=900, polish_timeout_max_ms=900))- assert 0.7 < deadline <= 0.9 + _FLOAT_SLACK+ assert deadline == pytest.approx(0.9, abs=_FLOAT_SLACK)async def test_a_maximum_below_the_base_never_shortens_the_base(@@ -190,7 +205,7 @@ async def test_a_maximum_below_the_base_never_shortens_the_base(monkeypatch, 800, _Cfg(polish_timeout_ms=1500, polish_timeout_max_ms=400))- assert 1.3 < deadline <= 1.5 + _FLOAT_SLACK+ assert deadline == pytest.approx(1.5, abs=_FLOAT_SLACK)async def test_an_explicit_override_is_never_ramped(@@ -206,7 +221,7 @@ async def test_an_explicit_override_is_never_ramped(await polish_transcript(_words(900), language="en", cfg=_Cfg(), timeout_s=0.5)- assert client.calls and 0 < client.calls[0] <= 0.5 + _FLOAT_SLACK+ assert client.calls and client.calls[0] == pytest.approx(0.5, abs=_FLOAT_SLACK)async def test_a_config_that_never_heard_of_the_maximum_still_ramps(diff --git a/tests/unit/live/test_native_live_fixes.py b/tests/unit/live/test_native_live_fixes.pyindex c54242dc0d..cb4cf13d22 100644--- a/tests/unit/live/test_native_live_fixes.py+++ b/tests/unit/live/test_native_live_fixes.py@@ -9,7 +9,6 @@ from __future__ import annotationsimport asyncioimport json-import timefrom types import SimpleNamespaceimport pytest@@ -124,15 +123,23 @@ async def _settle(session) -> None:# 1. Readiness probe before open_session ---------------------------------------+# Hang guard only, never the measured quantity: a loaded CI runner can stretch+# the session setup before the probe (data dir, ledger, prompt) past a second.+_HANG_GUARD_S = 30.0+++def test_the_refusal_budget_keeps_the_one_second_release_slo():+ """The SLO is pinned on the budget constant; the tests below prove it is used."""+ assert 0 < native._DUPLEX_PROBE_BUDGET_S <= 1.0+@both_providers@pytest.mark.asyncioasync def test_not_ready_provider_is_refused_in_its_own_words(call, make_provider):live = call(make_provider(ready=False))- began = time.monotonic()with pytest.raises(RealtimeUnavailableError) as refused:- await live.start()- assert time.monotonic() - began < 1.0+ await asyncio.wait_for(live.start(), _HANG_GUARD_S)+ assert live.provider.probes == 1assert live.provider.opened_with == [] # nothing opened, nothing billedexpected = (_LOCAL_REASON if live.provider.name == "local-voice" else native._DUPLEX_REFUSAL_FALLBACK@@ -147,12 +154,16 @@ async def test_not_ready_provider_is_refused_in_its_own_words(call, make_provide@both_providers@pytest.mark.asyncio-async def test_slow_readiness_probe_is_refused_within_a_second(call, make_provider):- live = call(make_provider(probe_delay_s=3.0))- began = time.monotonic()+async def test_slow_readiness_probe_is_refused_within_a_second(call, make_provider, monkeypatch):+ # A probe that never answers within the test is refused by the budget alone:+ # without the budget ``start`` would wait the full hour and hit the guard.+ # The budget is shrunk so the proof does not race a wall clock on a loaded+ # runner; its production value is pinned by the SLO test above.+ monkeypatch.setattr(native, "_DUPLEX_PROBE_BUDGET_S", 0.05)+ live = call(make_provider(probe_delay_s=3600.0))with pytest.raises(RealtimeUnavailableError):- await live.start()- assert time.monotonic() - began < 1.5+ await asyncio.wait_for(live.start(), _HANG_GUARD_S)+ assert live.provider.probes == 1assert live.provider.opened_with == []assert len(live.sent("error_spoken")) == 1@@ -283,7 +294,7 @@ async def test_slow_tool_releases_the_model_with_an_honest_pending_result(tool_args={"name": "search_web", "arguments_json": "{}"},))- await asyncio.wait_for(connection.tool_result_sent.wait(), 1.0)+ await asyncio.wait_for(connection.tool_result_sent.wait(), _HANG_GUARD_S)_, _, result = connection.tool_results[0]assert result["pending"] is True and result["success"] is Falseassert "still running" in result["error"]@@ -294,7 +305,7 @@ async def test_slow_tool_releases_the_model_with_an_honest_pending_result(# receipt lands after the tool body returns, which a loaded Windows CI# runner can stretch past half a second.await asyncio.wait_for(- asyncio.gather(*[job for job in session._jobs if not job.done()]), 5.0+ asyncio.gather(*[job for job in session._jobs if not job.done()]), _HANG_GUARD_S)assert gateway.finished == ["search_web"]assert not session._has_pending_work()@@ -305,7 +316,11 @@ async def test_slow_tool_releases_the_model_with_an_honest_pending_result(@both_providers@pytest.mark.asyncio-async def test_fast_tool_answers_with_its_real_result(tmp_path, make_provider):+async def test_fast_tool_answers_with_its_real_result(tmp_path, monkeypatch, make_provider):+ # "Fast" means "finishes before the deadline": the deadline is raised so a+ # loaded runner, where the receipt write alone can take seconds, cannot+ # turn the real result into a pending one.+ monkeypatch.setattr(native, "_TOOL_DEADLINE_S", _HANG_GUARD_S)session, connection, _frames = _in_call(make_provider(), tmp_path)try:await session._native_event(@@ -316,7 +331,7 @@ async def test_fast_tool_answers_with_its_real_result(tmp_path, make_provider):tool_args={"name": "search_web", "arguments_json": "{}"},))- await asyncio.wait_for(connection.tool_result_sent.wait(), 1.0)+ await asyncio.wait_for(connection.tool_result_sent.wait(), _HANG_GUARD_S)_, _, result = connection.tool_results[0]assert result["success"] is True and "pending" not in resultfinally:diff --git a/tests/unit/memory/wiki/test_conversation_observer.py b/tests/unit/memory/wiki/test_conversation_observer.pyindex 10c5e2d76c..41e8da0f8c 100644--- a/tests/unit/memory/wiki/test_conversation_observer.py+++ b/tests/unit/memory/wiki/test_conversation_observer.py@@ -18,7 +18,6 @@ from __future__ import annotationsimport asyncioimport jsonimport re-import timefrom collections.abc import AsyncIteratorfrom pathlib import Pathfrom typing import Any@@ -42,9 +41,14 @@ from jarvis.memory.wiki.voice_bridge import VoiceFactBridgeFACT_SENTENCE = "Remember that my friend Lena moved to Hamburg last month."+# Hang guard for background work, never a measured latency: a loaded CI runner+# runs this file several times slower than a laptop.+_HANG_GUARD_S = 30.0++class FakeBrain:- def __init__(self, *, sleep_s: float = 0.0) -> None:- self.sleep_s = sleep_s+ def __init__(self, *, gate: asyncio.Event | None = None) -> None:+ self.gate = gateself.call_count = 0self.completed = asyncio.Event()@@ -55,8 +59,8 @@ class FakeBrain:async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:self.call_count += 1- if self.sleep_s:- await asyncio.sleep(self.sleep_s)+ if self.gate is not None:+ await self.gate.wait()prompt = req.messages[-1].contentassert isinstance(prompt, str)focus_match = re.search(r"FOCUS USER TURN \[([^\]]+)]", prompt)@@ -104,10 +108,10 @@ def _config() -> JarvisConfig:)-def _stack(tmp_path: Path, *, brain_sleep_s: float = 0.0):+def _stack(tmp_path: Path, *, brain_gate: asyncio.Event | None = None):bus = EventBus()journal = CandidateJournal(tmp_path / "jarvis.db")- brain = FakeBrain(sleep_s=brain_sleep_s)+ brain = FakeBrain(gate=brain_gate)extractor = ConversationFactExtractor(config=_config(), journal=journal, registry=FakeRegistry(brain),)@@ -116,17 +120,11 @@ def _stack(tmp_path: Path, *, brain_sleep_s: float = 0.0):return bus, journal, None, bridge, brain-async def _drain(- journal: CandidateJournal,- *,- timeout_s: float = 2.0,- min_count: int = 1,-) -> None:- deadline = time.monotonic() + timeout_s- while time.monotonic() < deadline:- if journal.backlog_count() >= min_count:- return- await asyncio.sleep(0.02)+async def _drain(bridge: VoiceFactBridge) -> None:+ """Wait for every review the bridge started, however slow the host is."""+ async with asyncio.timeout(_HANG_GUARD_S):+ while bridge._inflight: # noqa: SLF001 - test seam: the bridge's own task set+ await asyncio.gather(*bridge._inflight, return_exceptions=True) # noqa: SLF001@pytest.mark.asyncio@@ -137,7 +135,7 @@ async def test_voice_turn_feeds_journal_not_direct_ingest(tmp_path: Path) -> Nontranscript=Transcript(text=FACT_SENTENCE, language="en", confidence=0.95),))await bus.publish(ResponseGenerated(text="Noted.", language="en"))- await _drain(journal)+ await _drain(bridge)finally:bridge.stop()@@ -152,7 +150,7 @@ async def test_chat_turn_feeds_same_journal(tmp_path: Path) -> None:try:await bus.publish(MessageSent(thread_id="t1", role="user", text=FACT_SENTENCE))await bus.publish(ResponseGenerated(text="Noted.", language="en"))- await _drain(journal)+ await _drain(bridge)finally:bridge.stop()@@ -174,7 +172,7 @@ async def test_same_text_via_both_paths_journaled_once(tmp_path: Path) -> None:))await bus.publish(MessageSent(thread_id="t1", role="user", text=FACT_SENTENCE))await bus.publish(ResponseGenerated(text="Noted.", language="en"))- await _drain(journal)+ await _drain(bridge)finally:bridge.stop()@@ -193,8 +191,9 @@ async def test_same_text_in_a_later_turn_is_reviewed_again(tmp_path: Path) -> NoMessageSent(thread_id="t1", role="user", text=FACT_SENTENCE))await bus.publish(ResponseGenerated(text="Noted.", language="en"))- await asyncio.wait_for(brain.completed.wait(), timeout=2.0)- await _drain(journal, min_count=index + 1)+ await asyncio.wait_for(brain.completed.wait(), timeout=_HANG_GUARD_S)+ await _drain(bridge)+ assert journal.backlog_count() == index + 1assert brain.call_count == index + 1finally:bridge.stop()@@ -206,19 +205,22 @@ async def test_same_text_in_a_later_turn_is_reviewed_again(tmp_path: Path) -> No@pytest.mark.asyncioasync def test_ap9_handlers_return_before_extraction_completes(tmp_path: Path) -> None:"""AP-9: publishing the turn never blocks on the LLM extraction."""- bus, journal, _curator, bridge, _brain = _stack(tmp_path, brain_sleep_s=0.5)+ # The extraction blocks until the test releases it, so a handler that+ # awaited it would never return: the publishes below would hit the guard.+ release = asyncio.Event()+ bus, journal, _curator, bridge, brain = _stack(tmp_path, brain_gate=release)try:- started = time.monotonic()- await bus.publish(TranscriptFinal(- transcript=Transcript(text=FACT_SENTENCE, language="en", confidence=0.95),- ))- await bus.publish(ResponseGenerated(text="Noted.", language="en"))- elapsed = time.monotonic() - started- assert elapsed < 0.1, f"voice path blocked for {elapsed:.3f}s on extraction"+ async with asyncio.timeout(_HANG_GUARD_S):+ await bus.publish(TranscriptFinal(+ transcript=Transcript(text=FACT_SENTENCE, language="en", confidence=0.95),+ ))+ await bus.publish(ResponseGenerated(text="Noted.", language="en"))# Extraction has not finished yet — the journal is still empty.+ assert not brain.completed.is_set()assert journal.backlog_count() == 0# ... and completes later in the background.- await _drain(journal, timeout_s=3.0)+ release.set()+ await _drain(bridge)assert journal.backlog_count() == 1finally:bridge.stop()@@ -235,7 +237,9 @@ async def test_unacknowledged_turns_are_never_reviewed(tmp_path: Path) -> None:await bus.publish(ResponseGenerated(text="Hamburg is lovely.", language="en"))await bus.publish(MessageSent(thread_id="t1", role="user", text=FACT_SENTENCE * 2))await bus.publish(ResponseGenerated(text="Tell me more!", language="en"))- await asyncio.sleep(0.3)+ # Any review the handlers started is awaited, so a wrong dispatch is+ # caught however slowly it would have run.+ await _drain(bridge)finally:bridge.stop()diff --git a/tests/unit/memory/wiki/test_voice_bridge_realtime.py b/tests/unit/memory/wiki/test_voice_bridge_realtime.pyindex a2529b2e2a..7485094dae 100644--- a/tests/unit/memory/wiki/test_voice_bridge_realtime.py+++ b/tests/unit/memory/wiki/test_voice_bridge_realtime.py@@ -21,7 +21,6 @@ from __future__ import annotationsimport asyncioimport jsonimport re-import timefrom collections.abc import AsyncIteratorfrom pathlib import Pathfrom typing import Any@@ -139,12 +138,21 @@ def _realtime_turn()-async def _drain(journal: CandidateJournal, *, timeout_s: float = 2.0) -> None:- deadline = time.monotonic() + timeout_s- while time.monotonic() < deadline:- if journal.backlog_count() > 0:- return- await asyncio.sleep(0.02)+# Hang guard for background work, never a measured latency: a loaded CI runner+# runs this file several times slower than a laptop.+_HANG_GUARD_S = 30.0+++async def _drain(bridge: VoiceFactBridge) -> None:+ """Wait for every review the bridge started, however slow the host is.++ Awaiting the bridge's own tasks replaces polling with a short deadline: a+ review that should run is always seen, and one that must not run is caught+ whenever it would have finished.+ """+ async with asyncio.timeout(_HANG_GUARD_S):+ while bridge._inflight: # noqa: SLF001 - test seam: the bridge's own task set+ await asyncio.gather(*bridge._inflight, return_exceptions=True) # noqa: SLF001async def _end_session(bus: EventBus, session_id: str = "rt-session") -> None:@@ -153,18 +161,12 @@ async def _end_session(bus: EventBus, session_id: str = "rt-session") -> None:)-async def _wait_for_calls(brain: FakeBrain, count: int, *, timeout_s: float = 2.0) -> None:- deadline = time.monotonic() + timeout_s- while brain.call_count < count and time.monotonic() < deadline: # noqa: ASYNC110- await asyncio.sleep(0.02)--@pytest.mark.asyncioasync def test_acknowledged_realtime_turn_is_reviewed_during_the_call(tmp_path: Path) -> None:bus, journal, _registry, bridge, brain = _stack(tmp_path)try:await bus.publish(_realtime_turn(SHORT_FACT, "Noted."))- await _drain(journal)+ await _drain(bridge)finally:bridge.stop()@@ -182,7 +184,7 @@ async def test_unacknowledged_realtime_turns_are_never_reviewed(tmp_path: Path)await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay, will do!"))await bus.publish(_realtime_turn("I own a yacht.", "", turn_id="rt-turn-2"))await _end_session(bus)- await asyncio.sleep(0.3)+ await _drain(bridge)finally:bridge.stop()@@ -197,10 +199,10 @@ async def test_session_end_runs_nothing_after_an_acknowledged_turn(tmp_path: Patbus, journal, _registry, bridge, brain = _stack(tmp_path)try:await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted.", turn_id="turn-a"))- await _wait_for_calls(brain, 1)+ await _drain(bridge)await _end_session(bus)await _end_session(bus)- await asyncio.sleep(0.3)+ await _drain(bridge)finally:bridge.stop()@@ -214,7 +216,7 @@ async def test_pipeline_tier_turn_is_ignored(tmp_path: Path) -> None:bus, journal, _registry, bridge, brain = _stack(tmp_path)try:await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted.", tier="flash"))- await asyncio.sleep(0.3)+ await _drain(bridge)finally:bridge.stop()@@ -228,8 +230,7 @@ async def test_same_realtime_turn_delivered_twice_is_reviewed_once(tmp_path: Pattry:await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))- await _wait_for_calls(brain, 1)- await asyncio.sleep(0.2)+ await _drain(bridge)finally:bridge.stop()@@ -242,7 +243,7 @@ async def test_empty_user_text_is_ignored(tmp_path: Path) -> None:bus, journal, _registry, bridge, brain = _stack(tmp_path)try:await bus.publish(_realtime_turn("", "Noted."))- await asyncio.sleep(0.2)+ await _drain(bridge)finally:bridge.stop()@@ -268,7 +269,7 @@ async def test_acknowledged_turn_receives_bounded_same_session_context(tmp_path:turn_id="turn-b",))- await _wait_for_calls(brain, 1)+ await _drain(bridge)finally:bridge.stop()@@ -292,9 +293,7 @@ async def test_subscription_wait_holds_the_save_and_never_bills_a_key()try:await bus.publish(_realtime_turn(SHORT_FACT, "Noted."))- deadline = time.monotonic() + 2.0- while bridge.waiting_count == 0 and time.monotonic() < deadline: # noqa: ASYNC110- await asyncio.sleep(0.02)+ await _drain(bridge)assert bridge.waiting_count == 1assert registry.instantiated == [], "no keyed provider may be touched"assert brain.call_count == 0diff --git a/tests/unit/pointer/test_turn.py b/tests/unit/pointer/test_turn.pyindex 111a4cb79d..038b701b2c 100644--- a/tests/unit/pointer/test_turn.py+++ b/tests/unit/pointer/test_turn.py@@ -8,10 +8,17 @@ the cursor AND an element is resolved — otherwise ("", None), so unrelated turfrom __future__ import annotations+import pytest+from jarvis.core.protocols import ImageBlockfrom jarvis.pointer.context import PointerContextfrom jarvis.pointer.turn import resolve_turn_pointerfrom jarvis.vision.pointer_types import PointerElement+from tests.fakes.fake_capabilities import (+ fake_linux_capabilities,+ fake_macos_capabilities,+ fake_windows_capabilities,+)def _ctx(available=True, **kw):@@ -102,7 +109,14 @@ async def test_headless_host_fast_skips_before_thread_dispatch(monkeypatch) -> Nassert called["resolver"] is False-async def test_crop_radius_forwarded_to_default_resolver(monkeypatch) -> None:+ "desktop_capabilities",+ [fake_windows_capabilities, fake_macos_capabilities, fake_linux_capabilities],+)+async def test_crop_radius_forwarded_to_default_resolver(+ monkeypatch, desktop_capabilities+) -> None:+ import jarvis.platform.capabilities as caps_modimport jarvis.pointer.turn as turn_modseen: dict[str, object] = {}@@ -112,6 +126,9 @@ async def test_crop_radius_forwarded_to_default_resolver(monkeypatch) -> None:seen["crop_radius"] = crop_radiusreturn _ctx(element=PointerElement(name="x", role="Button"))+ # Pin a desktop with a cursor: on a headless host (CI runner, VPS) the real+ # probe fast-skips before the default resolver, which this test is about.+ monkeypatch.setattr(caps_mod, "detect_capabilities", desktop_capabilities)monkeypatch.setattr(turn_mod, "resolve_pointer_context_async", fake_default)await resolve_turn_pointer(diff --git a/tests/unit/test_bare_jarvis_starts_desktop.py b/tests/unit/test_bare_jarvis_starts_desktop.pyindex e06df09e9d..123dad6e22 100644--- a/tests/unit/test_bare_jarvis_starts_desktop.py+++ b/tests/unit/test_bare_jarvis_starts_desktop.py@@ -10,6 +10,7 @@ OS, since nothing about the dispatch is platform-specific."""from __future__ import annotations+import reimport sysfrom pathlib import Path@@ -134,9 +135,23 @@ def test_readme_still_documents_bare_jarvis_as_the_desktop_entry() -> None:if not readme.is_file():pytest.skip("README absent (slim checkout)")text = readme.read_text(encoding="utf-8")- assert "jarvis # full desktop" in text, (- "README no longer advertises bare `jarvis` as the desktop entry — "- "if that changed on purpose, update this test and __main__.main()"+ # Read the documented COMMAND, not the prose around it: a rewrite that+ # changes the wording or the column of the comment must not fail the+ # suite, only one that drops bare `jarvis` or sends it somewhere else.+ blocks = re.findall(r"```(?:bash|sh|shell|console|powershell)?\n(.*?)```", text, re.S)+ bare = [+ line.partition("#")[2].strip().lower()+ for block in blocks+ for line in block.splitlines()+ if line.partition("#")[0].strip() == "jarvis"+ ]+ assert bare, (+ "README no longer documents bare `jarvis` as a command — if the desktop "+ "entry changed on purpose, update this test and __main__.main()"+ )+ assert not any("headless" in comment for comment in bare), (+ "README describes bare `jarvis` as headless, but __main__.main() starts "+ "the desktop app")diff --git a/tests/unit/ui/test_relaunch_properties.py b/tests/unit/ui/test_relaunch_properties.pyindex 53801f9581..50a582b266 100644--- a/tests/unit/ui/test_relaunch_properties.py+++ b/tests/unit/ui/test_relaunch_properties.py@@ -65,8 +65,10 @@ def test_relaunch_properties_stick_on_a_real_window() -> None:"""Stamp a real Tk window and read the properties back from the shell."""tk = pytest.importorskip("tkinter")pywintypes = pytest.importorskip("pywintypes")- propsys_mod = pytest.importorskip("win32com.propsys")- propsys = propsys_mod.propsys+ # Import the extension module itself: ``win32com.propsys`` is a package+ # whose ``propsys`` attribute only exists once something else imported the+ # submodule, which made this test pass or fail by collection order.+ propsys = pytest.importorskip("win32com.propsys.propsys")try:root = tk.Tk()diff --git a/tests/unit/workspace/test_launch_picks.py b/tests/unit/workspace/test_launch_picks.pyindex 3079489b1b..db639f8acf 100644--- a/tests/unit/workspace/test_launch_picks.py+++ b/tests/unit/workspace/test_launch_picks.py@@ -187,16 +187,22 @@ async def test_live_models_answers_within_budget_while_a_slow_cli_keeps_loading() -> None:"""A cold ``agy models`` took over a minute on a real box; the picker mustnot wait for it. The fast readers answer, the slow one is left out (its- curated fallback stands) and finishes in the background."""+ curated fallback stands) and finishes in the background.++ Proven by behaviour, not wall-clock: the slow read cannot finish before the+ test releases it, so an answer at all means the picker did not wait for+ it. The budget is wide enough for the fast readers' pool threads to start+ on a loaded runner; the timeout is only a hang guard.+ """+ import asyncioimport threading- import timefrom jarvis.agent_chat import runner_clirelease = threading.Event()def slow_agy() -> list[dict[str, str]]:- release.wait(5.0)+ release.wait(60.0)return [{"id": "late"}]monkeypatch.setattr(runner_cli, "read_agy_models", slow_agy)@@ -208,11 +214,9 @@ async def test_live_models_answers_within_budget_while_a_slow_cli_keeps_loading("_installed",lambda r: r in {"agy-cli", "codex-cli", "grok-cli", "opencode-cli"},)- monkeypatch.setattr(launch_picks, "_LIVE_MODELS_BUDGET_S", 0.2)+ monkeypatch.setattr(launch_picks, "_LIVE_MODELS_BUDGET_S", 2.0)try:- started = time.monotonic()- out = await launch_picks.live_models()- assert time.monotonic() - started < 2.0+ out = await asyncio.wait_for(launch_picks.live_models(), 30.0)assert out == {"codex-cli": [{"id": "gpt"}], "opencode-cli": []}finally:release.set()@@ -222,17 +226,23 @@ async def test_live_models_does_not_wait_again_for_a_read_an_earlier_request_stamonkeypatch: pytest.MonkeyPatch,) -> None:"""The slow read left running by one picker open must not cost the next- open its budget again; the second request answers at once."""+ open its budget again; the second request answers at once.++ Proven by behaviour, not wall-clock: the second request runs with a budget+ longer than the slow read itself, so waiting for the read again (or+ starting a second one) would return its late rows instead of ``{}``.+ """import threading- import timefrom jarvis.agent_chat import runner_clirelease = threading.Event()+ read_started = threading.Event()calls = []def slow_agy() -> list[dict[str, str]]:calls.append(1)+ read_started.set()release.wait(5.0)return [{"id": "late"}]@@ -241,9 +251,11 @@ async def test_live_models_does_not_wait_again_for_a_read_an_earlier_request_stamonkeypatch.setattr(launch_picks, "_LIVE_MODELS_BUDGET_S", 0.2)try:assert await launch_picks.live_models() == {}- started = time.monotonic()+ # The read runs in a pool thread; on a busy runner it may not have+ # begun within the first request's budget. Wait for it explicitly.+ assert read_started.wait(5.0)+ monkeypatch.setattr(launch_picks, "_LIVE_MODELS_BUDGET_S", 30.0)assert await launch_picks.live_models() == {}- assert time.monotonic() - started < 0.15assert len(calls) == 1 # joined, not started twicefinally:release.set()