The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: one invariant per bounded cache (LSP docs/baselines, tool-call logger, fuzzy roots, hindsight turns)
teknium1396013b17e35
diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.pyindex 55a1a37063d..20236b0a4e6 100644--- a/plugins/memory/hindsight/__init__.py+++ b/plugins/memory/hindsight/__init__.py@@ -1085,13 +1085,10 @@ class HindsightMemoryProvider(MemoryProvider):# Advance the watermark only after the delta is queued so a later retain# doesn't re-ship turns already handed to the writer.if update_mode == "append":- # Every buffered turn has now been shipped (the retain content was- # snapshotted into the closure above). Append retains only ever read- # the un-retained tail — sync_turn slices from the watermark and- # flush-on-switch flushes what's left — so drop the retained turns- # instead of letting the buffer grow for the whole session. Overwrite- # mode is deliberately untouched: it resends the full session each- # retain and must keep every turn.+ # The job above holds its own copy, and append retains (here and flush-on-switch) only+ # ever read the un-retained tail — so drop shipped turns instead of pinning every turn+ # of a never-ending session (#62950). Overwrite mode resends the whole session and+ # must keep them all.self._session_turns.clear()self._last_retained_turn_count = 0diff --git a/tests/agent/lsp/test_client_e2e.py b/tests/agent/lsp/test_client_e2e.pyindex 8d954593eeb..f24e276b991 100644--- a/tests/agent/lsp/test_client_e2e.py+++ b/tests/agent/lsp/test_client_e2e.py@@ -143,3 +143,30 @@ async def test_shutdown_never_signals_a_server_that_honours_exit(tmp_path: Path)assert signals == []assert proc.returncode == 0+++async def test_docs_cache_is_lru_bounded_and_reopens_evicted(tmp_path: Path, monkeypatch):+ """`_docs` never exceeds MAX_TRACKED_FILES; an evicted file is didClose'd and re-didOpen'ed+ (version 0) with diagnostics flowing again, so the cap is invisible to callers."""+ import agent.lsp.client as client_mod++ monkeypatch.setattr(client_mod, "MAX_TRACKED_FILES", 3)+ files = [tmp_path / f"f{i}.py" for i in range(5)]+ for f in files:+ f.write_text("print('hi')\n")++ client = _client(tmp_path, "errors")+ await client.start()+ try:+ for f in files:+ await client.open_file(str(f), language_id="python")+ assert len(client._docs) == 3+ assert str(files[0]) not in client._docs # least recently touched went first+ version = await client.open_file(str(files[0]), language_id="python")+ assert version == 0 # fresh didOpen, not a didChange against dropped state+ assert len(client._docs) == 3+ await client.wait_for_diagnostics(str(files[0]), version, mode="document")+ assert client.diagnostics_for(str(files[0]))+ finally:+ await client.shutdown()diff --git a/tests/agent/lsp/test_manager_locking.py b/tests/agent/lsp/test_manager_locking.pyindex da7e5d42d4d..be310e3d2e1 100644--- a/tests/agent/lsp/test_manager_locking.py+++ b/tests/agent/lsp/test_manager_locking.py@@ -57,3 +57,18 @@ def test_reused_multiroot_client_attaches_outside_state_lock(monkeypatch):result = asyncio.run(service._get_or_spawn("/repo/worktree-b/example.py"))assert result is client+++def test_delta_baseline_is_capped_by_write_recency():+ """Baselines beyond _DELTA_BASELINE_CAP evict the path written longest ago, and rewriting a+ path refreshes it instead of aging it out ahead of paths never touched again."""+ service = LSPService(enabled=False, wait_mode="document", wait_timeout=0.1,+ install_strategy="manual", idle_timeout=0)+ cap = manager._DELTA_BASELINE_CAP+ for i in range(cap):+ service._set_delta_baseline(f"/repo/f{i}.py", [])+ service._set_delta_baseline("/repo/f0.py", [{"message": "rewritten"}])+ service._set_delta_baseline("/repo/new.py", [])+ assert len(service._delta_baseline) == cap+ assert "/repo/f1.py" not in service._delta_baseline+ assert service._delta_baseline["/repo/f0.py"] == [{"message": "rewritten"}]diff --git a/tests/gateway/test_tool_log_mode.py b/tests/gateway/test_tool_log_mode.pyindex 1ce04a04160..03c6dc1a5fe 100644--- a/tests/gateway/test_tool_log_mode.py+++ b/tests/gateway/test_tool_log_mode.py@@ -86,3 +86,37 @@ async def test_write_tool_log_writes_and_rotates_handler(tmp_path, monkeypatch):await asyncio.sleep(0) # keep the asyncio marker honest+++async def test_write_tool_log_shares_one_logger_across_turns(tmp_path, monkeypatch):+ """Two turns with distinct queues register no new Logger (loggerDict is process-lifetime) and+ every line lands in tool_calls.log exactly once through the shared handler."""+ import logging++ import gateway.run as gateway_run+ from gateway.run_turn import GatewayTurnMixin++ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)+ shared = logging.getLogger("hermes.tool_calls")+ for h in list(shared.handlers):+ shared.removeHandler(h)+ h.close()+ before = set(logging.Logger.manager.loggerDict)+ queues = []+ try:+ for i in range(2):+ q: queue.Queue = queue.Queue()+ queues.append(q) # kept alive: distinct id()s, the shape the per-turn name leaked on+ q.put(f"2026-09-18 10:00:0{i} terminal: \"echo {i}\"")+ task = asyncio.ensure_future(GatewayTurnMixin._run_agent_write_tool_log(None, q))+ await asyncio.sleep(0.05)+ task.cancel()+ await task # the writer swallows the cancel after draining+ assert set(logging.Logger.manager.loggerDict) - before <= {"hermes.tool_calls"}+ lines = (tmp_path / "logs" / "tool_calls.log").read_text(encoding="utf-8").splitlines()+ assert [l.split()[-1] for l in lines] == ['0"', '1"']+ finally:+ for h in list(shared.handlers):+ shared.removeHandler(h)+ h.close()diff --git a/tests/plugins/memory/test_hindsight_provider.py b/tests/plugins/memory/test_hindsight_provider.pyindex b4315539e37..93a429464e5 100644--- a/tests/plugins/memory/test_hindsight_provider.py+++ b/tests/plugins/memory/test_hindsight_provider.py@@ -1756,3 +1756,24 @@ class TestMultiplexBackgroundScope:t.join(timeout=5)assert created == ["p1-secret"]assert "Daemon started successfully" in (home / "logs" / "hindsight-embed.log").read_text()+++def test_append_mode_trims_retained_turns_without_dropping_any(provider, monkeypatch):+ """Append retains ship only the delta, so retained turns leave `_session_turns` (a never-ending+ session no longer pins every turn) while every turn is still shipped exactly once."""+ provider._auto_retain = True+ provider._retain_every_n_turns = 3+ monkeypatch.setattr(provider, "_ensure_writer", lambda: None)+ monkeypatch.setattr(provider, "_register_atexit", lambda: None)+ monkeypatch.setattr(provider, "_resolve_retain_target", lambda doc: ("doc", "append"))+ shipped: list[str] = []+ monkeypatch.setattr(provider, "_make_turn_retain_job",+ lambda turns, **kw: (lambda: shipped.extend(turns)))+ provider._retain_queue = MagicMock(put=lambda job: job())++ for i in range(7):+ provider.sync_turn(f"user {i}", f"assistant {i}")++ assert len(provider._session_turns) == 1 # only the un-retained tail (turn 7)+ assert provider._last_retained_turn_count == 0+ assert len(shipped) == 6 and len(set(shipped)) == 6diff --git a/tests/tui_gateway/test_slash_fuzzy.py b/tests/tui_gateway/test_slash_fuzzy.pyindex 287019d91bd..648602f1ca6 100644--- a/tests/tui_gateway/test_slash_fuzzy.py+++ b/tests/tui_gateway/test_slash_fuzzy.py@@ -118,3 +118,28 @@ def test_rank_slash_completions_ties_break_on_usage_then_name():score_of=lambda item: 1.0,)assert [item["text"] for item in ranked] == ["/alpha", "/beta"]+++def test_repo_file_cache_sweeps_expired_roots_on_write(tmp_path, monkeypatch):+ """A root queried once and never again is dropped by the next write past its TTL — the TTL+ used to be checked only on read, pinning every worktree listing for the process lifetime."""+ import time++ import tui_gateway.server as server++ now = [1000.0]+ monkeypatch.setattr(time, "monotonic", lambda: now[0])+ roots = []+ for i in range(3):+ root = tmp_path / f"wt{i}"+ root.mkdir()+ (root / "a.py").write_text("")+ roots.append(str(root))+ server._fuzzy_cache.clear()+ server._list_repo_files(roots[0])+ now[0] += server._FUZZY_CACHE_TTL_S / 2+ server._list_repo_files(roots[1]) # still fresh when the next write happens+ now[0] += server._FUZZY_CACHE_TTL_S / 2 + 0.1 # roots[0] expired, roots[1] not+ server._list_repo_files(roots[2])+ assert set(server._fuzzy_cache) == {roots[1], roots[2]}+ server._fuzzy_cache.clear()