The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: synchronize observable state and reuse prepared PM fixtures
ethernetb265e8767845
diff --git a/tests/cron/test_fire_claim_lost_after_delivery.py b/tests/cron/test_fire_claim_lost_after_delivery.pyindex 9d913dbbf8f..fe658c2ed6a 100644--- a/tests/cron/test_fire_claim_lost_after_delivery.py+++ b/tests/cron/test_fire_claim_lost_after_delivery.py@@ -10,7 +10,6 @@ actual on-disk ``last_status`` the health watchdog reads, not a mock's call list"""import threading-import timeimport pytest@@ -169,8 +168,15 @@ class _HeartbeatThreadMisses:def __init__(self, real, misses: int, *, steal: bool = False):self._real, self._left, self._steal = real, misses, stealself.missed = 0+ self._samples = 0+ self.processed = threading.Event()def __call__(self, job_id, *, expected_owner):+ if threading.current_thread().name == "cron-fire-claim-heartbeat":+ self._samples += 1+ if self._samples > 2:+ # Reaching the next poll proves the confirmation was accepted without latching.+ self.processed.set()if threading.current_thread().name == "cron-fire-claim-heartbeat" and self._left:self._left -= 1self.missed += 1@@ -188,21 +194,31 @@ class _HeartbeatThreadMisses:def _drive_heartbeat_thread(monkeypatch, *, misses, steal=False):"""run_one_job with the REAL fire-claim heartbeat thread sampling every 10 ms; ``run_job``- finishes with a complete response once the heartbeat has taken its armed samples."""+ finishes after the heartbeat has processed its confirmation, not merely sampled it."""import cron.scheduler as schedjob = _claimed_job()hb = _HeartbeatThreadMisses(sched.heartbeat_fire_claim, misses, steal=steal)delivered, run_cancel = [], []+ start_heartbeat = sched._start_heartbeat_thread++ def observed_heartbeat(loop_fn, name, fail_log):+ def run():+ try:+ loop_fn()+ finally:+ # A confirmed loss exits the loop only after setting the real cancel latch.+ hb.processed.set()++ return start_heartbeat(run, name, fail_log)def fake_run_job(job, **kwargs):- deadline = time.monotonic() + 5- while hb.missed < misses and time.monotonic() < deadline:- time.sleep(0.01)- time.sleep(0.1) # let the heartbeat's confirm sample land+ # Deadlock guard only: store I/O and thread scheduling have no 100 ms upper bound.+ assert hb.processed.wait(timeout=30), "heartbeat never processed its confirmation"run_cancel.append(kwargs["cancel_event"].is_set())return True, "output text", "the report", None+ monkeypatch.setattr(sched, "_start_heartbeat_thread", observed_heartbeat)monkeypatch.setattr(sched, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.01)monkeypatch.setattr(sched, "_FIRE_CLAIM_MISS_CONFIRM_SECONDS", 0.01, raising=False)monkeypatch.setattr(sched, "heartbeat_fire_claim", hb)diff --git a/tests/gateway/test_approve_deny_commands.py b/tests/gateway/test_approve_deny_commands.pyindex 8733097337c..178e66d2105 100644--- a/tests/gateway/test_approve_deny_commands.py+++ b/tests/gateway/test_approve_deny_commands.py@@ -324,45 +324,35 @@ class TestBlockingApprovalE2E:def test_blocking_approval_uses_canonical_timeout(self, approval_config, monkeypatch):"""Gateway waits use approvals.timeout, without a second timeout knob."""from tools import approval as approval_module- from tools.approval import check_all_command_guards, register_gateway_notify, resolve_gateway_approval, unregister_gateway_notify+ from tools.approval import check_all_command_guards, register_gateway_notify, unregister_gateway_notifyfrom tools.approval_context import reset_current_session_key, set_current_session_keymonkeypatch.setattr(approval_module, "_YOLO_MODE_FROZEN", False)session_key = "e2e-timeout"- register_gateway_notify(session_key, lambda d: None)-- result_holder = [None]-- def agent_thread():- token = set_current_session_key(session_key)- os.environ["HERMES_GATEWAY_SESSION"] = "1"- os.environ["HERMES_EXEC_ASK"] = "1"- os.environ["HERMES_SESSION_KEY"] = session_key- try:- with patch(- "tools.approval_context._get_approval_config",- return_value=approval_config,- ):- result_holder[0] = check_all_command_guards(- "rm -rf /important", "local"- )- finally:- os.environ.pop("HERMES_GATEWAY_SESSION", None)- os.environ.pop("HERMES_EXEC_ASK", None)- os.environ.pop("HERMES_SESSION_KEY", None)- reset_current_session_key(token)-- t = threading.Thread(target=agent_thread)- t.start()- t.join(timeout=1)- if t.is_alive():- resolve_gateway_approval(session_key, "deny")- t.join(timeout=5)-- assert result_holder[0]["approved"] is False- assert result_holder[0]["outcome"] == "timeout"- assert "timed out" in result_holder[0]["message"]- unregister_gateway_notify(session_key)+ notified = []+ register_gateway_notify(session_key, notified.append)+ monkeypatch.setenv("HERMES_GATEWAY_SESSION", "1")+ monkeypatch.setenv("HERMES_EXEC_ASK", "1")+ monkeypatch.setenv("HERMES_SESSION_KEY", session_key)+ token = set_current_session_key(session_key)+ try:+ # Zero expires in the real poll loop. A timed join followed by /deny+ # races pre-approval hooks and changes the outcome being tested.+ with patch(+ "tools.approval_context._get_approval_config",+ return_value=approval_config,+ ):+ result = check_all_command_guards("rm -rf /important", "local")++ assert len(notified) == 1+ assert result["approved"] is False+ assert result["user_consent"] is False+ assert result["outcome"] == "timeout"+ assert "timed out" in result["message"]+ assert approval_module.list_gateway_approvals(session_key) == []+ finally:+ reset_current_session_key(token)+ unregister_gateway_notify(session_key)def test_parallel_subagent_approvals(self):"""Multiple threads can block concurrently and be resolved independently."""diff --git a/tests/gateway/test_matrix_plugin_setup.py b/tests/gateway/test_matrix_plugin_setup.pyindex 14403141fde..09b98f1a770 100644--- a/tests/gateway/test_matrix_plugin_setup.py+++ b/tests/gateway/test_matrix_plugin_setup.py@@ -3,14 +3,13 @@The interactive_setup wizard lazy-imports its CLI helpers from``hermes_cli.config`` (get_env_value / save_env_value / remove_env_value),``hermes_cli.cli_output`` (prompt / prompt_yes_no / print_*), and-``pm`` (mautrix ensure_import). We patch each at its source module so-the wizard runs without touching pip or the network. Covers the home-channel+``pm`` (Matrix sync_venv). We patch each at its source module so+the wizard runs without provisioning dependencies. Covers the home-channelclear-on-blank behavior added in the follow-up to PR #58421."""import hermes_cli.config as config_modimport hermes_cli.cli_output as cli_output_modimport pm as pm_mod-import pm.extras as pm_extras_modfrom plugins.platforms.matrix.adapter import interactive_setup@@ -31,10 +30,8 @@ def _patch_setup_io(monkeypatch, prompts, yes_no_responses, saved, removed, exis)for name in ("print_header", "print_info", "print_success", "print_warning"):monkeypatch.setattr(cli_output_mod, name, lambda *_a, **_kw: None)- # Block the auto-install path so the test never invokes pip.- monkeypatch.setattr(pm_extras_mod, "missing", lambda extra: ())- monkeypatch.setattr(pm_mod, "ensure_import", lambda *a, **kw: None)- monkeypatch.setattr(pm_extras_mod, "ensure_import", lambda *a, **kw: None)+ # Setup explicitly syncs dependencies; lazy-import patches do not intercept it.+ monkeypatch.setattr(pm_mod, "sync_venv", lambda *a, **kw: None)# Matrix prompts (after the E2EE yes_no): allowed_users, home_channel.diff --git a/tests/gateway/test_turn_lease.py b/tests/gateway/test_turn_lease.pyindex ded1dfec1cc..38b234f771c 100644--- a/tests/gateway/test_turn_lease.py+++ b/tests/gateway/test_turn_lease.py@@ -213,11 +213,17 @@ async def test_full_dispatch_rejects_lease_timeout_without_running_goal_hook(runner._run_agent = pytest.failrunner._post_turn_goal_continuation = AsyncMock()+ acquire = AsyncMock(wraps=runner._turn_leases.acquire)+ monkeypatch.setattr(runner._turn_leases, "acquire", acquire)try:- response = await asyncio.wait_for(runner._handle_message(_event()), timeout=1)+ # Dispatch includes admission, thread hops and cleanup outside the lease+ # wait. Bound hangs here; assert the actual lease budget separately.+ response = await asyncio.wait_for(runner._handle_message(_event()), timeout=10)finally:assert runner._turn_leases.release(holder) is True+ acquire.assert_awaited_once()+ assert acquire.await_args_list[0].kwargs["timeout"] == 0.02assert isinstance(response, str)assert "not processed" in response.lower()assert "resend" in response.lower()diff --git a/tests/hermes_cli/test_profiles_sidebar_cache.py b/tests/hermes_cli/test_profiles_sidebar_cache.pyindex 4abdafdff2f..38839dafb77 100644--- a/tests/hermes_cli/test_profiles_sidebar_cache.py+++ b/tests/hermes_cli/test_profiles_sidebar_cache.py@@ -3,15 +3,19 @@import inspectimport tempfileimport threading-import timeimport unittestfrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Path+from types import SimpleNamespacefrom unittest import mockfrom hermes_cli.web_routers import profiles+# These guard deadlocks, not response latency on a contended CI worker.+_THREAD_TIMEOUT = 30++class SidebarCacheTests(unittest.TestCase):def setUp(self):patcher = mock.patch.object(profiles, "_SIDEBAR_CACHE_TTL_SECONDS", 5.0)@@ -20,6 +24,24 @@ class SidebarCacheTests(unittest.TestCase):profiles._sidebar_profile_cache_clear()self.addCleanup(profiles._sidebar_profile_cache_clear)+ def _concurrent_scans(self, scan, workers, entered, release):+ ready = threading.Barrier(workers)++ def request():+ ready.wait(timeout=_THREAD_TIMEOUT)+ return scan()++ # Expiry has its own test. A descheduled contender must not age out this burst.+ with mock.patch.object(profiles, "time", SimpleNamespace(monotonic=lambda: 100.0)), \+ ThreadPoolExecutor(max_workers=workers) as pool:+ try:+ futures = [pool.submit(request) for _ in range(workers)]+ self.assertTrue(entered.wait(timeout=_THREAD_TIMEOUT))+ finally:+ # Also unblock the scan when setup/assertions fail, before pool shutdown joins it.+ release.set()+ return [future.result(timeout=_THREAD_TIMEOUT) for future in futures]+def test_profile_cache_uses_db_and_wal_fingerprint_and_defensive_copies(self):with tempfile.TemporaryDirectory() as root:db_path = Path(root) / "state.db"@@ -83,15 +105,10 @@ class SidebarCacheTests(unittest.TestCase):with calls_lock:calls += 1entered.set()- self.assertTrue(release.wait(timeout=2))+ self.assertTrue(release.wait(timeout=_THREAD_TIMEOUT))return {"profile": profile, "rows": []}- with ThreadPoolExecutor(max_workers=workers) as pool:- futures = [pool.submit(scan, "default") for _ in range(workers)]- self.assertTrue(entered.wait(timeout=1))- time.sleep(0.05)- release.set()- results = [future.result(timeout=2) for future in futures]+ results = self._concurrent_scans(lambda: scan("default"), workers, entered, release)self.assertEqual(calls, 1)self.assertEqual(results, [{"profile": "default", "rows": []}] * workers)@@ -176,6 +193,9 @@ class SidebarCacheTests(unittest.TestCase):# /api/profiles/projects/tree fans out over every profile's state.db; desktop# background sync + sidebar refreshes overlap identical requests. One scan must# serve the whole burst, and no two callers may share the same payload object.+ # The route imports this lazily; cold import time is setup, not scan concurrency.+ from tui_gateway import server # noqa: F401+workers = 8entered = threading.Event()release = threading.Event()@@ -187,17 +207,13 @@ class SidebarCacheTests(unittest.TestCase):with scans_lock:scans += 1entered.set()- self.assertTrue(release.wait(timeout=2))+ self.assertTrue(release.wait(timeout=_THREAD_TIMEOUT))return Nonewith mock.patch.object(profiles, "_profile_targets", return_value=[("default", Path("/nonexistent"))]), \- mock.patch.object(profiles, "_read_profile_db", side_effect=fake_read), \- ThreadPoolExecutor(max_workers=workers) as pool:- futures = [pool.submit(profiles.get_profiles_projects_tree) for _ in range(workers)]- self.assertTrue(entered.wait(timeout=1))- time.sleep(0.05)- release.set()- results = [future.result(timeout=2) for future in futures]+ mock.patch.object(profiles, "_read_profile_db", side_effect=fake_read):+ results = self._concurrent_scans(+ profiles.get_profiles_projects_tree, workers, entered, release)self.assertEqual(scans, 1)self.assertEqual(len({id(r) for r in results}), workers)diff --git a/tests/scripts/test_bundle_native.py b/tests/scripts/test_bundle_native.pyindex 28a23c09791..fcd52f2e38e 100644--- a/tests/scripts/test_bundle_native.py+++ b/tests/scripts/test_bundle_native.py@@ -27,7 +27,7 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_patfrom pm.lock import Factsfrom pm.registry import get_packagefrom pm.store import tree_digest- from tests.pm._fixtures import _wheel+ from tests.pm._fixtures import _wheel, stage_host_pythonmonkeypatch.setattr(Path, "home", lambda: tmp_path / "home")monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))@@ -37,15 +37,15 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_patpython_package = get_package("python")python_entry = python_package.store_entry(lock.version("python"), target)source_python = python_package.binary(canonical / python_entry, target)+ assert source_python is not Nonetarget_python = output / "tools" / source_python.relative_to(canonical)source_python.parent.mkdir(parents=True)- # PM seals a payload-owned base interpreter, not an external venv launcher.- # Windows carries its stdlib beside the executable; POSIX PM pythons are- # RELOCATABLE builds that resolve sys.prefix relative to their own- # tree — a bare ELF copy falls back to the compile-time /install prefix- # and cannot even create its venv. Stage the full toolchain, mirroring- # the store layout the payload's tools/ directory promises.- if os.name == "nt":+ # Keep a real payload-owned interpreter and stdlib. The Linux fixture+ # excludes unused SDK libraries and duplicate executable aliases, which+ # otherwise dominate each of the repeated admission digests below.+ if sys.platform == "linux":+ stage_host_python(source_python)+ elif os.name == "nt":shutil.copytree(Path(sys.base_prefix), source_python.parent, dirs_exist_ok=True)else:shutil.copytree(Path(getattr(sys, "_base_executable")).resolve().parents[1],diff --git a/tests/tools/test_approval.py b/tests/tools/test_approval.pyindex 2fe7ed65a6a..63cdb392ac4 100644--- a/tests/tools/test_approval.py+++ b/tests/tools/test_approval.py@@ -1736,58 +1736,52 @@ class TestApprovalTimeoutIsNotConsent:self._force_short_timeout(monkeypatch, seconds=2)notified = []- mod.register_gateway_notify(self.SESSION_KEY, lambda data: notified.append(data))- result_holder = {}- thread = threading.Thread(- target=lambda: result_holder.setdefault(- "result", mod.check_all_command_guards("rm -rf .git", "local")- )- )- thread.start()- for _ in range(200):- if notified:- break- time.sleep(0.005)+ def notify(data):+ # The real queue entry is already pending here. Inspect/respond at+ # publication, without racing thread startup or the approval deadline.+ notified.append(data)+ request_id = data["request_id"]+ assert request_id+ assert mod.list_gateway_approvals(self.SESSION_KEY) == [data]+ assert mod.ack_gateway_approval(self.SESSION_KEY, request_id) is True+ assert mod.list_gateway_approvals(self.SESSION_KEY) == [data]+ assert mod.resolve_gateway_approval(+ self.SESSION_KEY, "once", request_id=request_id+ ) == 1++ mod.register_gateway_notify(self.SESSION_KEY, notify)+ result = mod.check_all_command_guards("rm -rf .git", "local")- request_id = notified[0]["request_id"]- assert request_id- assert mod.list_gateway_approvals(self.SESSION_KEY) == [notified[0]]- assert mod.ack_gateway_approval(self.SESSION_KEY, request_id) is True- assert mod.resolve_gateway_approval(- self.SESSION_KEY, "once", request_id=request_id- ) == 1- thread.join(timeout=5)- assert result_holder["result"]["approved"] is True+ assert len(notified) == 1+ assert result["approved"] is True+ assert mod.list_gateway_approvals(self.SESSION_KEY) == []def test_stale_request_id_cannot_resolve_current_approval(self, monkeypatch):from tools import approval as modself._force_short_timeout(monkeypatch, seconds=2)notified = []- mod.register_gateway_notify(self.SESSION_KEY, lambda data: notified.append(data))- result_holder = {}- thread = threading.Thread(- target=lambda: result_holder.setdefault(- "result", mod.check_all_command_guards("rm -rf .git", "local")- )- )- thread.start()- for _ in range(200):- if notified:- break- time.sleep(0.005)- request_id = notified[0]["request_id"]- assert mod.resolve_gateway_approval(- self.SESSION_KEY, "once", request_id="stale-request"- ) == 0- assert mod.list_gateway_approvals(self.SESSION_KEY)- assert mod.resolve_gateway_approval(- self.SESSION_KEY, "deny", request_id=request_id- ) == 1- thread.join(timeout=5)- assert result_holder["result"]["approved"] is False+ def notify(data):+ notified.append(data)+ assert mod.resolve_gateway_approval(+ self.SESSION_KEY, "once", request_id="stale-request"+ ) == 0+ assert mod.list_gateway_approvals(self.SESSION_KEY) == [data]+ assert mod.resolve_gateway_approval(+ self.SESSION_KEY, "deny", request_id=data["request_id"]+ ) == 1++ mod.register_gateway_notify(self.SESSION_KEY, notify)+ result = mod.check_all_command_guards("rm -rf .git", "local")++ assert len(notified) == 1+ assert result["approved"] is False+ assert result["user_consent"] is False+ # Callback assertions are caught as notify_failed; require the actual denial.+ assert result["outcome"] == "denied"+ assert mod.list_gateway_approvals(self.SESSION_KEY) == []# =========================================================================diff --git a/tests/tools/test_delegate_liveness_timeout.py b/tests/tools/test_delegate_liveness_timeout.pyindex 1c36a6df9bf..13022ff5511 100644--- a/tests/tools/test_delegate_liveness_timeout.py+++ b/tests/tools/test_delegate_liveness_timeout.py@@ -16,6 +16,8 @@ import threadingimport timefrom types import SimpleNamespace+import pytest+from tools import delegate_tool_CAP_SECONDS = 0.4@@ -115,15 +117,32 @@ def test_frozen_child_is_still_abandoned_when_the_cap_elapses(monkeypatch):def test_frozen_child_is_warned_once_at_80_percent_of_the_window(monkeypatch):- """Atom 2A of #116001: a stalling child hears about the closing window while it can still wrap up."""- child = _SlowButLiveChild(total_seconds=1.2, advance=False, initial_calls=3)- started = time.monotonic()+ """A stalling child hears about the closing window while it can still wrap up."""+ from tools import delegate_tool_child_run as child_run++ now = 0.0+ steers = []++ def advance(timeout):+ nonlocal now+ now += timeout++ # Only the budget clock/wait are virtual: executor setup and OS scheduling+ # must not consume the tiny warning window. Other threads keep real time.+ monkeypatch.setattr(child_run, "time", SimpleNamespace(monotonic=lambda: now))+ monkeypatch.setattr(child_run, "_LIVENESS_POLL_SECONDS", _CAP_SECONDS / 10)+ child = SimpleNamespace(+ get_activity_summary=lambda: {"api_call_count": 3},+ steer=lambda text: steers.append((now, text)),+ )+ settled = threading.Event()+ monkeypatch.setattr(settled, "wait", advance)+ run = child_run._ChildRun(child, None, 0, "frozen child", None, None)- entry = _run(child, monkeypatch)+ run.wait_liveness_aware(settled, None, _CAP_SECONDS)- assert entry["status"] == "timeout", entry- assert len(child.steers) == 1, child.steers- warned_at, text = child.steers[0]+ assert now == _CAP_SECONDS+ assert len(steers) == 1, steers+ warned_at, text = steers[0]assert "[delegation budget warning]" in text and f"{_CAP_SECONDS:.0f}s inactivity window" in text, text- # Fired inside the window (after ~80% of it, before the kill), not at the timeout itself.- assert 0.8 * _CAP_SECONDS - 0.05 <= warned_at - started < _CAP_SECONDS, (warned_at - started, _CAP_SECONDS)+ assert warned_at == pytest.approx(0.8 * _CAP_SECONDS)diff --git a/tests/tools/test_plugin_guard.py b/tests/tools/test_plugin_guard.pyindex f10f87798ac..56d3368f0e3 100644--- a/tests/tools/test_plugin_guard.py+++ b/tests/tools/test_plugin_guard.py@@ -12,6 +12,10 @@ from pathlib import Pathimport pytest+from tests.hermes_cli.plugin_worker_support import (+ isolated_python as isolated_python,+ plugin_world as plugin_world,+)from tools.plugin_guard import (scan_plugin,should_allow_plugin_install,@@ -341,6 +345,12 @@ class TestRuntimeSelfTestTokens:class TestInstallIntegration:"""E2E through _install_plugin_core with a real git clone."""+ @pytest.fixture(autouse=True)+ def _offline_pm(self, plugin_world):+ # Keep real worker publication without provisioning tools per temporary home.+ # Preserve the original installs' absent-config selection semantics.+ (plugin_world.home / "config.yaml").unlink()+@staticmethoddef _make_git_repo(repo_root: Path, files: dict[str, str]):import shutil as _shutil