The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: a bug and some tests
Maciej Lisiewski84b944effb47
diff --git a/agent/activity_tracking.py b/agent/activity_tracking.pyindex 984b6d8fbe1..67a4a4f3bf8 100644--- a/agent/activity_tracking.py+++ b/agent/activity_tracking.py@@ -107,7 +107,9 @@ class ActivityTrackingMixin:now_mono = time.monotonic()last_mono = getattr(self, "_session_activity_last_persist_mono", 0.0)- if (now_mono - last_mono) < SESSION_ACTIVITY_HEARTBEAT_MIN_INTERVAL_SECONDS:+ # 0.0 is the never-persisted / reset sentinel and always writes through: CLOCK_MONOTONIC is+ # roughly host uptime, so on a freshly booted VM ``now_mono`` itself can be under the interval.+ if last_mono and (now_mono - last_mono) < SESSION_ACTIVITY_HEARTBEAT_MIN_INTERVAL_SECONDS:returnself._session_activity_last_persist_mono = now_monotry:diff --git a/tests/agent/test_session_activity_persist.py b/tests/agent/test_session_activity_persist.pyindex c235608cd17..0e98eafbeec 100644--- a/tests/agent/test_session_activity_persist.py+++ b/tests/agent/test_session_activity_persist.py@@ -77,6 +77,24 @@ def test_touch_activity_accepts_named_provenance(monkeypatch):)+def test_first_stamp_persists_while_monotonic_clock_is_below_interval(monkeypatch):+ """CLOCK_MONOTONIC is roughly host uptime: on a freshly booted VM it can sit below the 60s+ persist interval. The never-persisted / reset sentinel (0.0) must still write through."""+ agent = _agent_with_db()+ monkeypatch.setattr(run_agent.time, "time", lambda: 1_700_000_000.0)+ monkeypatch.setattr(run_agent.time, "monotonic", lambda: 5.0)+ monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)++ agent._touch_activity("starting API call #1")++ agent._session_db.touch_session_activity.assert_called_once_with(+ "sess-1",+ 1_700_000_000.0,+ description="starting API call #1",+ provenance=ActivityProvenance.UNKNOWN,+ )++def test_touch_activity_persist_errors_are_swallowed(monkeypatch):agent = _agent_with_db()agent._session_db.touch_session_activity.side_effect = RuntimeError("db locked")diff --git a/tests/gateway/test_managed_worker_background_output.py b/tests/gateway/test_managed_worker_background_output.pyindex d222b7d7439..87264f5431a 100644--- a/tests/gateway/test_managed_worker_background_output.py+++ b/tests/gateway/test_managed_worker_background_output.py@@ -97,6 +97,9 @@ def test_next_managed_turn_reads_the_previous_workers_background_output(tmp_pathhome, user = tmp_path / 'state', tmp_path / 'user'home.mkdir(mode=0o700)user.mkdir()+ # The terminal backend spawns `bash -lic`; Ubuntu's /etc/bash.bashrc prints a sudo hint on stdout+ # for sudo-group users whose HOME has no ~/.hushlogin (CI runners are in that group).+ (user / '.hushlogin').touch()peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)threading.Thread(target=peer.serve_forever, daemon=True).start()url = f'http://127.0.0.1:{peer.server_port}/v1'diff --git a/tests/gateway/test_profile_serve_signature.py b/tests/gateway/test_profile_serve_signature.pyindex 85c6b4dc990..f9da5602e7f 100644--- a/tests/gateway/test_profile_serve_signature.py+++ b/tests/gateway/test_profile_serve_signature.py@@ -4,6 +4,7 @@ import osimport shutilfrom gateway.run_profile_reconcile import profile_serve_signature+from tests.waiting import wait_for_ctime_tickdef test_profile_serve_signature_changes_on_replacement_with_pinned_mtime(tmp_path):@@ -12,6 +13,7 @@ def test_profile_serve_signature_changes_on_replacement_with_pinned_mtime(tmp_pabefore = profile_serve_signature(tmp_path)assert profile_serve_signature(tmp_path) == before # unchanged file: stablest = cfg.stat()+ wait_for_ctime_tick(tmp_path, st.st_ctime_ns)other = tmp_path / "other"other.write_text("y" * 64, encoding="utf-8")shutil.copy2(other, cfg)diff --git a/tests/gateway/test_session_events_overflow.py b/tests/gateway/test_session_events_overflow.pyindex 56f261bdab7..00565c581ae 100644--- a/tests/gateway/test_session_events_overflow.py+++ b/tests/gateway/test_session_events_overflow.py@@ -11,8 +11,10 @@ class Peer:def __init__(self, gate=None):self.frames = queue.Queue()self.gate = gate+ self.entered = threading.Event()def write(self, frame):+ self.entered.set()if self.gate is not None:self.gate.wait()self.frames.put(frame)@@ -48,6 +50,11 @@ async def test_overflowed_subscriber_is_detached_and_told_to_resume(tmp_path):delivered = []for n in range(total):live.event_stream.publish('s', {'n': n}, event_type='message.delta')+ if n == 0:+ # The drain thread takes everything queued as ONE batch: wait until it holds+ # frame 0 alone, blocked in write, so frames 1.. fill the mailbox to the cap+ # instead of riding along in a late-starting thread's first batch.+ assert await asyncio.to_thread(slow.entered.wait, 5), 'stalled writer never started'# Pace the healthy reader by receipt so only the stalled peer's backlog grows.delivered.append(await asyncio.to_thread(healthy.frames.get, True, 5))# The healthy viewer saw the whole turn; the stalled one lost its subscriptiondiff --git a/tests/hermes_cli/test_cli_mcp_config_watch.py b/tests/hermes_cli/test_cli_mcp_config_watch.pyindex 43ea412d857..fc47a4e06cb 100644--- a/tests/hermes_cli/test_cli_mcp_config_watch.py+++ b/tests/hermes_cli/test_cli_mcp_config_watch.py@@ -1,6 +1,7 @@"""Tests for automatic MCP reload when config.yaml mcp_servers section changes."""from unittest.mock import MagicMock, patch+from tests.waiting import wait_for_ctime_tickfrom utils import file_signature@@ -222,6 +223,7 @@ def test_pinned_mtime_same_size_replacement_triggers_reload(tmp_path):obj, cfg_file = _make_cli(tmp_path, mcp_servers={"bb": {"command": "b"}})cfg_file.write_text("mcp_servers:\n bb: {command: b}\n")obj._config_sig = file_signature(cfg_file.stat())+ wait_for_ctime_tick(tmp_path, cfg_file.stat().st_ctime_ns)other = tmp_path / "other.yaml"other.write_text("mcp_servers:\n aa: {command: a}\n")shutil.copy2(other, cfg_file)diff --git a/tests/tools/test_browser_snapshot_threshold.py b/tests/tools/test_browser_snapshot_threshold.pyindex 40dfba60fde..4eef44f9f45 100644--- a/tests/tools/test_browser_snapshot_threshold.py+++ b/tests/tools/test_browser_snapshot_threshold.py@@ -1,6 +1,7 @@"""Behavior tests for config-driven browser snapshot thresholds."""import json+import osfrom unittest.mock import Mockimport pytest@@ -27,10 +28,14 @@ def isolated_snapshot_threshold(tmp_path, monkeypatch):def _write_threshold(hermes_home, value):- (hermes_home / "config.yaml").write_text(+ # Atomic replace, like the real config writers: an in-place same-size rewrite within one coarse+ # kernel timestamp tick keeps (mtime, size, ino, ctime), so read_raw_config's cache can't see it.+ tmp = hermes_home / "config.yaml.tmp"+ tmp.write_text(f"browser:\n snapshot_threshold: {value}\n",encoding="utf-8",)+ os.replace(tmp, hermes_home / "config.yaml")def _long_snapshot(chars: int) -> str:diff --git a/tests/tools/test_model_tools.py b/tests/tools/test_model_tools.pyindex 888761302d3..348fbe03602 100644--- a/tests/tools/test_model_tools.py+++ b/tests/tools/test_model_tools.py@@ -542,12 +542,14 @@ def test_tool_defs_cache_key_sees_config_replacement_with_pinned_mtime(tmp_path)import shutilfrom model_tools import _tool_defs_cache_key+ from tests.waiting import wait_for_ctime_tickcfg = tmp_path / "config.yaml"cfg.write_text("mcp_servers:\n aa: {command: a}\n", encoding="utf-8")with patch("hermes_cli.config.get_config_path", return_value=cfg):before = _tool_defs_cache_key(None, None, False)st = cfg.stat()+ wait_for_ctime_tick(tmp_path, st.st_ctime_ns)other = tmp_path / "other.yaml"other.write_text("mcp_servers:\n bb: {command: b}\n", encoding="utf-8")shutil.copy2(other, cfg)diff --git a/tests/tui_gateway/test_change_watcher_sessions.py b/tests/tui_gateway/test_change_watcher_sessions.pyindex 3d697c412d1..793060e3eb3 100644--- a/tests/tui_gateway/test_change_watcher_sessions.py+++ b/tests/tui_gateway/test_change_watcher_sessions.py@@ -1,6 +1,7 @@from __future__ import annotationsimport sqlite3+import timefrom tui_gateway import server@@ -59,3 +60,22 @@ def test_sessions_signature_changes_for_session_metadata_updates(tmp_path, monkeconn.close()assert server._sessions_sig() != before+++def test_sessions_signature_sees_a_commit_inside_the_same_mtime_tick(tmp_path, monkeypatch):+ """Filesystem timestamps tick coarsely (~4 ms; whole seconds on some filesystems), and SQLite+ commits in place: a commit in the tick of the previous read leaves the DB/WAL mtime unchanged."""+ db_path = tmp_path / "state.db"+ _seed_store(db_path)+ monkeypatch.setattr(server, "_watcher_home", lambda: tmp_path)+ monkeypatch.setattr(server, "_served_profile_homes", [])+ frozen_mtime = time.time_ns()+ monkeypatch.setattr(server, "_newest_mtime_ns", lambda _paths: frozen_mtime)++ before = server._sessions_sig()+ conn = sqlite3.connect(db_path)+ conn.execute("UPDATE sessions SET title = 'Renamed' WHERE id = 'session-1'")+ conn.commit()+ conn.close()++ assert server._sessions_sig() != beforediff --git a/tests/tui_gateway/test_skin_watcher_profile_scope.py b/tests/tui_gateway/test_skin_watcher_profile_scope.pyindex 693ebe5d524..e09612813cb 100644--- a/tests/tui_gateway/test_skin_watcher_profile_scope.py+++ b/tests/tui_gateway/test_skin_watcher_profile_scope.py@@ -7,6 +7,8 @@ outside the TUI (``hermes -p work config set display.skin …``) must still repa"""from __future__ import annotations+import os+import pytestfrom hermes_constants import reset_hermes_home_override, set_hermes_home_override@@ -31,7 +33,12 @@ def _skins(peer):def _write_skin(home, name):- (home / "config.yaml").write_text(f"display:\n skin: {name}\n", encoding="utf-8")+ # Atomic replace, like the real config writers: skin names share lengths (ares/mono), and an+ # in-place same-size rewrite inside one coarse kernel timestamp tick keeps (mtime, size, ino,+ # ctime), so the server's raw-config cache would serve the previous skin.+ tmp = home / "config.yaml.tmp"+ tmp.write_text(f"display:\n skin: {name}\n", encoding="utf-8")+ os.replace(tmp, home / "config.yaml")@pytest.fixturediff --git a/tests/waiting.py b/tests/waiting.pyindex 02e9255c748..2156ed6b0f3 100644--- a/tests/waiting.py+++ b/tests/waiting.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport asyncioimport timefrom collections.abc import Callable+from pathlib import Pathfrom typing import TypeVarT = TypeVar("T")@@ -45,6 +46,23 @@ def wait_until(predicate: Callable[[], T], timeout: float = DEFAULT_TIMEOUT,time.sleep(interval)+def wait_for_ctime_tick(directory: Path, after_ns: int, timeout: float = DEFAULT_TIMEOUT) -> None:+ """Block until the filesystem timestamp clock on ``directory``'s fs has passed ``after_ns``.++ Kernels without multigrain timestamps stamp inodes from a coarse, tick-granular clock (~4 ms),+ so an in-place rewrite inside the tick of an earlier write keeps ctime too and no stat-based+ signature can see it. Call this before a ``cp -p`` / pinned-mtime replacement test rewrites a+ file whose ``st_ctime_ns`` was ``after_ns``. A ``.ctime-probe`` file is left in ``directory``.+ """+ probe = Path(directory) / ".ctime-probe"++ def _ticked() -> bool:+ probe.touch()+ return probe.stat().st_ctime_ns > after_ns++ wait_until(_ticked, timeout=timeout, what="filesystem ctime clock to advance")++async def async_wait_until(predicate: Callable[[], T], timeout: float = DEFAULT_TIMEOUT,interval: float = DEFAULT_INTERVAL, what: str | None = None) -> T:"""``wait_until`` for a coroutine: yields to the event loop between polls."""diff --git a/tui_gateway/change_watcher.py b/tui_gateway/change_watcher.pyindex 147534dfdd0..20f87ccfabd 100644--- a/tui_gateway/change_watcher.py+++ b/tui_gateway/change_watcher.py@@ -184,8 +184,8 @@ _SESSION_SIGNATURE_FIELDS = ()# path -> (database/WAL mtime, session-table digest). The mtime guard keeps the# normal 0.5 s watch pass stat-only; SQLite is read only after another process-# actually commits.-_sessions_db_sig_cache: dict[str, tuple[int | None, tuple | None]] = {}+# actually commits (and for ``_RACY_MTIME_WINDOW_NS`` after it, see _settled_mtime).+_sessions_db_sig_cache: dict[str, tuple[object, tuple | None]] = {}def _session_db_content_sig(db_path: Path):@@ -241,11 +241,26 @@ def _session_db_content_sig(db_path: Path):if conn is not None:conn.close()- _sessions_db_sig_cache[cache_key] = (mtime, signature)+ _sessions_db_sig_cache[cache_key] = (_settled_mtime(mtime), signature)return signature+# Filesystem timestamps come from a coarse clock (~4 ms ticks; whole seconds on some filesystems) and+# SQLite commits in place, so a commit landing in the tick of a read leaves the DB/WAL mtime unchanged.+# A digest read while the mtime is that fresh must not become a cache hit ("racily clean", as in git's+# index): it is cached under a key no mtime equals, so the next tick re-reads the rows.+_RACY_MTIME_WINDOW_NS = 2_000_000_000+_RACY_MTIME = object()+++def _settled_mtime(mtime):+ """``mtime`` when it is old enough to trust as a cache key, else a never-matching sentinel."""+ if mtime is None or time.time_ns() - mtime < _RACY_MTIME_WINDOW_NS:+ return _RACY_MTIME+ return mtime++def _sessions_sig():"""Session-table content across the active and served profile stores.