The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main (#30: 54 commits to 1744a19e0df) into feat/unified-gateway-runtime
Teknium607a23e858a2
diff --cc hermes_state_messages.pyindex 40f7484e914,19908aed180..b7798506ac1--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@@ -1877,11 -1876,11 +1877,11 @@@ class SessionMessagesMixin# Decode for the prompt-buffer prefill without a second fallible DB operation.target_row["content"] = self._decode_content(target_row.get("content"))return {"rewound_count": len(rewound), "target_message": target_row, "new_head_id": new_head_id,- **({"replacement_message_id": replacement and replacement["_row_id"],- "replacement_message_uid": replacement and message_uid_or_none(replacement)}+ **({"replacement_message_id": replacement_message_id,+ "replacement_message_uid": replacement_message_uid}if preserve_compaction_handoff else {})}- def message_count(self, session_id: str = None) -> int:+ def message_count(self, session_id: str | None = None) -> int:"""Count messages, optionally for a specific session."""sql = "SELECT COUNT(*) FROM messages" + (" WHERE session_id = ?" if session_id else "")return self._read_one(sql, (session_id,) if session_id else ())[0]diff --cc tests/agent/test_kanban_turn_recovery.pyindex 06ee9e5dcf2,522a133cc4f..ee77480812a--- a/tests/agent/test_kanban_turn_recovery.py+++ b/tests/agent/test_kanban_turn_recovery.py@@@ -499,154 -476,183 +499,154 @@@ def owner_worker(tmp_path, clear_kanbanseen["n"] += 1return result- def _run_conversation(self, *, user_message, conversation_history):- entered.append(user_message)- return self._next()-- def chat(self, query, images=None):- entered.append(query)- result = self._next()- self._last_turn_result = result- # Mirror production: chat() returns the settled turn's rendered response —- # for a failed turn that IS the provider error text.- return result.get("final_response", "") if isinstance(result, dict) else ""+ frame = {"text": "work", "policy": {"kanban_json": json.dumps(context)}}- # route plumbing- def _claim_active_session(self, surface, *, stderr=False):- return True+ def run() -> int:+ session_kanban.run_worker_turns(_Agent(), frame, [])+ return session_kanban.worker_exit_code(path, context)- def _ensure_runtime_credentials(self):- return True+ return run, entered, context- def _resolve_turn_agent_config(self, effective_query):- return {"signature": "same-route", "model": None, "runtime": None,- "request_overrides": None}+ return install- def _init_agent(self, **kwargs):- return True- def _show_security_advisories(self):- pass+def test_recovers_in_place(owner_worker):+ run, entered, context = owner_worker([_failed(), _success()], recovery=2)- def _print_exit_summary(self, clear_screen=True):- ui.append("summary")-- monkeypatch.setattr(cli_mod, "HermesCLI", _Feed)- monkeypatch.setattr(cli_mod.atexit, "register", lambda *a, **k: None)- monkeypatch.setattr(cli_mod, "_finalize_single_query", lambda fake_cli: None)- monkeypatch.setattr(cli_mod, "_collect_query_images", lambda q, img: (q, []))- monkeypatch.setattr(cli_mod, "_collect_kanban_task_images", lambda imgs: [])- return cli_mod, entered, ui+ assert run() == 0 # settled successfully+ assert len(entered) == 2 # the failed turn, then the recovery turn+ assert "Do NOT start over" in entered[1]+ assert context["task_id"] in entered[1] and "t_foreign" not in entered[1]- return _install+def test_budget_exhausted_stops_and_releases(owner_worker):+ """Bounded, then released: the loop stops at the cap, and the exhausted transient wall+ still reaches the dispatcher as the neutral code."""+ run, entered, _ = owner_worker(_failed, recovery=1) # never recovers-def _drive(cli_mod, driver) -> int:- """Run one one-shot query on ``driver`` and return the exit code it raised."""- kwargs: dict = {"query": "hello", "toolsets": "terminal"}- if driver == "chat":- kwargs.update(quiet=False, oneshot=True)- else:- kwargs.update(quiet=True)- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(**kwargs)- return exc_info.value.code+ assert run() == KANBAN_RATE_LIMIT_EXIT_CODE+ assert len(entered) == 2 # original + one recovery attempt-def live_claim(monkeypatch):- """The board proof is a separate contract (unit-tested above); the call-site tests run- against a worker that owns its run unless the test overrides it."""- import agent.kanban_turn_recovery as rec+ ("script", "code"),+ [+ pytest.param([None], 1, id="nothing-settled"),+ pytest.param([_partial()], 1, id="denial-unfinished-turn"),+ pytest.param([_failed(reason="rate_limit")], KANBAN_RATE_LIMIT_EXIT_CODE, id="quota-wall"),+ pytest.param([_failed(reason="billing")], KANBAN_RATE_LIMIT_EXIT_CODE, id="billing-wall"),+ pytest.param([_failed(reason="upstream_rate_limit")], KANBAN_RATE_LIMIT_EXIT_CODE,+ id="upstream-quota-wall"),+ ],+)+def test_single_turn_route_outcomes(script, code, owner_worker):+ """Every row takes exactly ONE model turn, so what is under test is what the worker does+ AFTER that turn: the neutral release for a quota wall (#48000-class boundary, including+ the aggregator's upstream 429) versus an honest 1 for a turn that is not retry authority+ (partial / nothing-settled) rather than a silent rc=0."""+ run, entered, _ = owner_worker(list(script))++ assert run() == code+ assert len(entered) == 1- monkeypatch.setattr(rec, "worker_claim_is_live", lambda: True)- return rec+def test_non_worker_frame_is_never_recovered(clear_kanban_env, monkeypatch):+ """A turn whose frame carries no kanban claim is not a worker, even inside an owner+ process whose environment names a task: one model entry, result returned untouched."""+ from gateway import session_kanban-def goal_spy(monkeypatch):- """Spy on BOTH goal continuation loops at the cli-module seam. The loops are- pre-existing (their status check sees only run identity, not the claim lease); the- invariant under test is the call-site veto this PR adds."""- import cli as cli_mod+ clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_foreign")+ entered: list[str] = []+ failed = _failed()- calls: list = []- monkeypatch.setattr(cli_mod, "_run_kanban_goal_loop_q",- lambda c, resp: calls.append((resp, "quiet")))- monkeypatch.setattr(cli_mod, "_run_kanban_goal_loop_chat",- lambda c, resp: calls.append((resp, "chat")))- return calls+ class _Agent:+ def run_conversation(self, message, conversation_history=None):+ entered.append(message)+ return failed+ frame = {"text": "hello", "policy": {}}+ assert session_kanban.run_worker_turns(_Agent(), frame, []) is failed+ assert entered == ["hello"][email protected]("driver", DRIVERS)-def test_recovers_in_place(driver, cli_harness, live_claim, monkeypatch):- import agent.kanban_turn_recovery as rec- _worker_env(monkeypatch, recovery=2)- monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- cli_mod, entered, _ui = cli_harness(driver, [_failed(), _success()])+def test_claim_denial_stops_before_model_reentry(owner_worker, caplog):+ """A worker whose run/claim proof fails (lease lapsed, not yet reaped) gets no recovery+ nudge, says so, and still leaves the dispatcher its neutral release."""+ import logging- assert _drive(cli_mod, driver) == 0 # settled successfully- assert len(entered) == 2 # the failed turn, then the recovery turn- assert "Do NOT start over" in entered[1]- assert "t_probe" in entered[1]+ run, entered, _ = owner_worker([_failed()], expires=1)+ with caplog.at_level(logging.WARNING, logger="agent.kanban_turn_recovery"):+ assert run() == KANBAN_RATE_LIMIT_EXIT_CODE+ assert len(entered) == 1+ assert "no longer holds a live run/claim" in caplog.text[email protected]("driver", DRIVERS)-def test_budget_exhausted_stops_and_releases(driver, cli_harness, live_claim, monkeypatch):- """Bounded, then released: the loop stops at the cap, and the exhausted transient wall- still reaches the dispatcher as the neutral code."""- import agent.kanban_turn_recovery as rec+def test_worker_client_reports_the_owner_exit_and_reply(owner_worker, monkeypatch, capsys):+ """The dispatcher-spawned process is the client half: it exits with the code the owner+ booked for this exact attempt, ends its log with the attempt's reply, and writes the+ exit trailer the dead-worker sweep reads — so an exhausted wall still releases as 75."""+ from contextlib import asynccontextmanager- _worker_env(monkeypatch, recovery=1)- monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- cli_mod, entered, _ui = cli_harness(driver, _failed) # never recovers+ from hermes_cli import gateway_client, kanban_worker_client+ from hermes_cli.quiet_single_query import KANBAN_WORKER_EXIT_TRAILER- run, entered, context = owner_worker(_failed, recovery=1)- assert _drive(cli_mod, driver) == KANBAN_RATE_LIMIT_EXIT_CODE- assert len(entered) == 2 # original + one recovery attempt++ run, _entered, context = owner_worker(_failed, recovery=1)+ assert run() == KANBAN_RATE_LIMIT_EXIT_CODE+ submitted = []+ class _Owner:+ async def rpc(self, method, **params):+ submitted.append(method)+ assert method == "kanban.run" and params["task_id"] == context["task_id"]+ return {"session_id": "s1", "receipt": {"status": "terminal", "admission_id": "a1"}}-def _single_turn_cases():- """One row per single-turn outcome on either route: ``(env, script, exit code)``. Every- row takes exactly ONE model turn, so what is under test is what the route does AFTER- that turn: the neutral release for a quota wall (#48000-class boundary, including the- aggregator's upstream 429) versus an honest 1 for a turn that is not retry authority- (partial / nothing-settled) or for a run that is not a worker at all."""- neutral = KANBAN_RATE_LIMIT_EXIT_CODE- return [- pytest.param({}, [None], 1, id="nothing-settled"),- pytest.param({}, [_partial()], 1, id="denial-unfinished-turn"),- pytest.param({}, [_failed(reason="rate_limit")], neutral, id="quota-wall"),- pytest.param({}, [_failed(reason="billing")], neutral, id="billing-wall"),- pytest.param({}, [_failed(reason="upstream_rate_limit")], neutral,- id="upstream-quota-wall"),- pytest.param({"task": " "}, [_failed(reason="rate_limit")], 1,- id="blank-task-id-is-not-a-worker"),- pytest.param({"task": None}, [_failed()], 1, id="non-worker-failed"),- pytest.param({"task": None}, [None], 1, id="non-worker-unsettled"),- ]+ @asynccontextmanager+ async def _connect():+ yield _Owner()+ monkeypatch.setattr(gateway_client, "connect_gateway", _connect)+ monkeypatch.delenv("HERMES_TUI_GATEWAY_URL", raising=False)+ for key, value in (("HERMES_KANBAN_BOARD", "default"), ("HERMES_KANBAN_TASK", context["task_id"]),+ ("HERMES_KANBAN_RUN_ID", str(context["run_id"])),+ ("HERMES_KANBAN_CLAIM_LOCK", context["claim_lock"]),+ ("HERMES_KANBAN_DB", context["db"])):+ monkeypatch.setenv(key, value)+ capsys.readouterr()[email protected]("driver", DRIVERS)[email protected](("env", "script", "code"), _single_turn_cases())-def test_single_turn_route_outcomes(driver, env, script, code, cli_harness, live_claim,- monkeypatch):- """One representative end-to-end denial per driver, plus the quota-wall release and the- non-worker rows. An unfinished, non-failed turn is not retry authority (the unit table- above pins interrupt / terminal settlement / partial as well), so exactly one model turn- is taken and the exit is the honest code rather than a silent rc=0; ``task=None`` means- no worker env at all, and a blank id is not a worker either (its wall is NOT- neutralized into 75 — raw env truthiness would)."""- if "task" in env:- if env["task"] is None:- monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)- monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)- else:- _worker_env(monkeypatch, task=env["task"])- else:- _worker_env(monkeypatch)- cli_mod, entered, _ui = cli_harness(driver, list(script))-- assert _drive(cli_mod, driver) == code- assert len(entered) == 1+ assert kanban_worker_client.main() == KANBAN_RATE_LIMIT_EXIT_CODE+ out, err = capsys.readouterr()+ assert submitted == ["kanban.run"] # the client never re-enters the model itself+ assert "API call failed" in out+ assert f"{KANBAN_WORKER_EXIT_TRAILER}{KANBAN_RATE_LIMIT_EXIT_CODE}" in err[email protected]("driver", DRIVERS)-def test_claim_denial_stops_before_model_reentry(driver, cli_harness, capsys, monkeypatch):- """A worker whose run/claim proof fails gets no recovery nudge, says so, and still- leaves the dispatcher its neutral release."""- import agent.kanban_turn_recovery as rec+async def test_non_worker_one_shot_prints_its_exit_summary(capsys):+ """Smoke pin kept from the pre-gateway file: a plain failed ``chat -q`` run exits 1 after+ printing the turn's text and its stderr ``session_id`` summary, and takes exactly one+ admission — recovery is never a client-side resubmit."""+ import asyncio- _worker_env(monkeypatch)- monkeypatch.setattr(rec, "worker_claim_is_live", lambda: False)- cli_mod, entered, _ui = cli_harness(driver, [_failed()])+ from hermes_cli.gateway_chat_view import GatewayChatView- assert _drive(cli_mod, driver) == KANBAN_RATE_LIMIT_EXIT_CODE- assert len(entered) == 1- assert "no longer holds a live run/claim" in capsys.readouterr().err+ submitted = []+ class _Owner:+ events: asyncio.Queue = asyncio.Queue()-def test_non_quiet_route_prints_its_exit_summary(cli_harness, live_claim, monkeypatch):- """Smoke pin kept from the pre-trim file: a plain (non-worker) failed `chat -q` run still- prints its exit summary before exiting 1 — the non-quiet tail exits unconditionally, so- the summary has to be printed on the way out."""- monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)- cli_mod, entered, ui = cli_harness("chat", [_failed()])+ async def rpc(self, method, **params):+ submitted.append(method)+ self.events.put_nowait({"method": "event", "params": {+ "type": "message.complete", "session_id": "stored", "admission_id": "mine",+ "payload": {"text": "API call failed after 3 retries", "outcome": "failed"}}})+ return {"admission_id": "mine"}- assert _drive(cli_mod, "chat") == 1- assert entered == ["hello"] # no recovery outside a worker- assert "summary" in ui+ view = GatewayChatView(_Owner(), {"stored_session_id": "stored"}, quiet=True)+ assert await asyncio.wait_for(view.run("hello", oneshot=True), 2) == 1+ out, err = capsys.readouterr()+ # One admission, never a resubmit; the settled-result read (prompt.receipt) is read-only.+ assert submitted.count("prompt.submit") == 1 and set(submitted) <= {"prompt.submit", "prompt.receipt"}+ assert "API call failed" in out and "session_id: stored" in err# ── goal mode: a refused recovery stops ALL model entry (one table) ──diff --cc tests/cron/test_preflight_config.pyindex d3786345381,9b27e9aff1d..4912f05be70--- a/tests/cron/test_preflight_config.py+++ b/tests/cron/test_preflight_config.py@@@ -136,8 -134,9 +136,8 @@@ class TestMissingProviderKeyBlockswith cron_jobs.use_cron_store(tmp_path):cron_jobs.save_jobs([job])- fake_db = MagicMock()for _tick in range(2):- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ fresh = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])with patch("cron.scheduler._hermes_home", tmp_path), \patch("cron.scheduler_delivery._resolve_origin", return_value=None), \patch("hermes_cli.env_loader.load_hermes_dotenv"), \@@@ -178,11 -178,10 +178,11 @@@raise AuthError("no key")return {**_RUNTIME, "provider": "openrouter"}- job = _job()+ # Unpinned: a job carrying its own model is pinned (#100437) and gets no chain.+ job = _job(model=None)with cron_jobs.use_cron_store(tmp_path):cron_jobs.save_jobs([job])- success, output, final_response, error, agent_constructed = \+ success, _output, _final_response, error, agent_constructed = \_run_job_patched(job, tmp_path, resolve=resolve)assert agent_constructed is True@@@ -268,8 -266,9 +268,8 @@@ class TestOptOutwith cron_jobs.use_cron_store(tmp_path):cron_jobs.save_jobs([job])- fake_db = MagicMock()for _tick in range(2):- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ fresh = next(j for j in cron_jobs.load_jobs() if j["id"] == job["id"])with patch("cron.scheduler._hermes_home", tmp_path), \patch("cron.scheduler_delivery._resolve_origin", return_value=None), \patch("hermes_cli.env_loader.load_hermes_dotenv"), \diff --cc tests/cron/test_scheduler.pyindex eb0eca11585,f0b92f72adc..d8efa2e854c--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@@ -1356,7 -1334,7 +1356,7 @@@ class TestRunJobSkillBackedmock_agent_cls.return_value = mock_agenttry:- success, output, final_response, error = _run_owned_job(job, tmp_path, fake_db)- success, _output, final_response, error = run_job(job)++ success, _output, final_response, error = _run_owned_job(job, tmp_path, fake_db)finally:clear_env_passthrough()@@@ -1579,7 -1556,7 +1579,7 @@@ class TestRunJobWakeGatewith patch.object(sched_script, "_run_job_script",return_value=(True, '{"wakeAgent": false}')), \patch("run_agent.AIAgent") as agent_cls:- success, doc, final, err = _run_owned_job(self._make_job(), tmp_path)- success, _doc, final, err = scheduler.run_job(self._make_job())++ success, _doc, final, err = _run_owned_job(self._make_job(), tmp_path)assert success is Trueassert err is None@@@ -1600,7 -1577,7 +1600,7 @@@with patch.object(sched_script, "_run_job_script",return_value=(True, script_output)), \patch("run_agent.AIAgent", return_value=agent) as agent_cls:- success, doc, final, err = _run_owned_job(self._make_job(), tmp_path)- success, _doc, _final, err = scheduler.run_job(self._make_job())++ success, _doc, _final, err = _run_owned_job(self._make_job(), tmp_path)agent_cls.assert_called_once()# The script output should be visible in the prompt passed todiff --cc tests/cron/test_sessiondb_init_hang.pyindex 0cb9780c4f4,c5a9b8de14e..64a409f5435--- a/tests/cron/test_sessiondb_init_hang.py+++ b/tests/cron/test_sessiondb_init_hang.py@@@ -7,160 -23,335 +7,160 @@@ local writer or an agent without persisimport concurrent.futuresimport threadingimport time+from types import SimpleNamespacefrom unittest.mock import MagicMock, patch-from cron.scheduler import run_job--# Hold the real class: patching cron.scheduler.concurrent.futures.ThreadPoolExecutor-# also replaces concurrent.futures.ThreadPoolExecutor (same module object).-_REAL_TPE = concurrent.futures.ThreadPoolExecutor--_RUNTIME = {- "api_key": "test-key",- "base_url": "https://example.invalid/v1",- "provider": "openrouter",- "api_mode": "chat_completions",-}---def _session_db_executor(timeouts: list, *, instant_timeout: bool = True):- """Wrap ``ThreadPoolExecutor`` so SessionDB's ``result(timeout=...)`` is observable.-- ``run_job`` is the only caller that passes a timeout to ``Future.result`` on- this path (``submit(SessionDB).result(timeout=...)``). Other pools used by- ``tick`` / the agent inactivity watchdog call ``result()`` with no timeout- and are left alone. When ``instant_timeout`` is True, the timed wait raises- immediately instead of sleeping — the production hang path without a clock.- """-- def factory(max_workers=1, *args, **kwargs):- real = _REAL_TPE(max_workers=max_workers)- orig_submit = real.submit-- def submit(fn, *a, **k):- fut = orig_submit(fn, *a, **k)- orig_result = fut.result-- def result(*ra, **rk):- timeout = ra[0] if ra else rk.get("timeout")- if timeout is not None:- timeouts.append(timeout)- if instant_timeout:- raise concurrent.futures.TimeoutError()- return orig_result(*ra, **rk)-- fut.result = result- return fut-- real.submit = submit- return real-- return factory---class TestSessionDbInitTimeout:- def test_sessiondb_init_preserves_multiplex_profile_context(- self, tmp_path, monkeypatch- ):- """The timeout worker must construct SessionDB under the active profile."""- from hermes_constants import (- get_hermes_home,- reset_hermes_home_override,- set_hermes_home_override,- )-- default_home = tmp_path / "default"- profile_home = tmp_path / "profiles" / "jobsearch"- monkeypatch.setenv("HERMES_HOME", str(default_home))- observed_homes = []- fake_db = MagicMock()-- def make_session_db(*args, **kwargs):- observed_homes.append(get_hermes_home())- return fake_db-- job = {"id": "profile-sessiondb", "name": "test", "prompt": "hello"}- profile_token = set_hermes_home_override(profile_home)+import pytest++from cron import scheduler+from gateway import session_cron+++def owner_run(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ db = MagicMock(db_path=tmp_path / "state.db")+ db.get_compression_tip.return_value = None+ owner = SimpleNamespace(db=db)+ job = {"id": "owner-db", "name": "test", "prompt": "hello"}+ execution_id = "owner-fire"+ token = session_cron._execution.set((owner, "owner-session", job["id"], execution_id))+ monkeypatch.setattr(scheduler, "_hermes_home", tmp_path)+ monkeypatch.setattr(scheduler, "_reload_dotenv_and_publish_delivery_target", lambda *_: None)+ monkeypatch.setattr(scheduler, "_resolve_cron_agent_setup", lambda *_: scheduler._CronAgentSetup(+ model="test", runtime={"provider": "test"}))+ with patch("run_agent.AIAgent") as agent_cls:+ agent_cls.return_value.run_conversation.return_value = {"final_response": "ok"}try:- with patch("cron.scheduler._hermes_home", None), \- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \- patch("hermes_cli.env_loader.load_hermes_dotenv"), \- patch("hermes_cli.env_loader.reset_secret_source_cache"), \- patch("hermes_state_registry.acquire", side_effect=make_session_db), \- patch(- "hermes_cli.runtime_provider.resolve_runtime_provider",- return_value=_RUNTIME,- ), \- patch("run_agent.AIAgent") as mock_agent_cls:- mock_agent = MagicMock()- mock_agent.run_conversation.return_value = {"final_response": "ok"}- mock_agent_cls.return_value = mock_agent-- success, _output, final_response, error = run_job(job)+ yield owner, job, execution_id, agent_clsfinally:- reset_hermes_home_override(profile_token)-- assert success is True- assert error is None- assert final_response == "ok"- assert observed_homes == [profile_home]-- def test_run_job_does_not_hang_when_sessiondb_init_wedges(self, tmp_path, monkeypatch):- """run_job proceeds without a session store when SessionDB init times out."""- monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.2")- job = {"id": "wedged-sessiondb", "name": "test", "prompt": "hello"}- timeouts: list = []-- with patch("cron.scheduler._hermes_home", tmp_path), \- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \- patch("hermes_cli.env_loader.load_hermes_dotenv"), \- patch("hermes_cli.env_loader.reset_secret_source_cache"), \- patch("hermes_state_registry.acquire"), \- patch(- "hermes_cli.runtime_provider.resolve_runtime_provider",- return_value=_RUNTIME,- ), \- patch("run_agent.AIAgent") as mock_agent_cls, \- patch(- "cron.scheduler.concurrent.futures.ThreadPoolExecutor",- side_effect=_session_db_executor(timeouts),- ):- mock_agent = MagicMock()- mock_agent.run_conversation.return_value = {"final_response": "ok"}- mock_agent_cls.return_value = mock_agent-- success, _output, final_response, _error = run_job(job)-- # Env-resolved bound was passed to Future.result — not the 10s default,- # and not an unbounded call.- assert timeouts == [0.2]- assert success is True- assert final_response == "ok"- assert mock_agent_cls.call_args.kwargs["session_db"] is None--- def test_timeout_resolved_from_config_yaml(self, tmp_path, monkeypatch):- """cron.session_db_timeout_seconds in config.yaml is respected when- the env var is not set — the canonical config-first resolution path."""- import hermes_yaml as yaml-+ session_cron._execution.reset(token)+++def test_sessiondb_init_preserves_multiplex_profile_context(owner_run, tmp_path):+ from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override++ owner, job, execution_id, agent_cls = owner_run+ profile_home = tmp_path / "profiles" / "jobsearch"+ owner.db.db_path = profile_home / "state.db"+ observed = []++ def acquire(path):+ observed.append((path, get_hermes_home()))+ return owner.db++ token = set_hermes_home_override(profile_home)+ try:+ with patch("hermes_state_registry.acquire", side_effect=acquire):+ success, _, response, error = scheduler.run_job(job, execution_id=execution_id)+ finally:+ reset_hermes_home_override(token)+ assert (success, response, error) == (True, "ok", None)+ assert observed == [(profile_home / "state.db", profile_home)]+ assert agent_cls.call_args.kwargs["session_db"] is owner.db++[email protected]("setting", ["env", "config"])+def test_run_job_does_not_hang_when_sessiondb_init_wedges(owner_run, tmp_path, monkeypatch, setting):+ owner, job, execution_id, agent_cls = owner_run+ if setting == "env":+ monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.02")+ else:monkeypatch.delenv("HERMES_CRON_SESSION_DB_TIMEOUT", raising=False)- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- (tmp_path / "config.yaml").write_text(- yaml.safe_dump({"cron": {"session_db_timeout_seconds": 0.2}})- )- job = {"id": "config-timeout", "name": "test", "prompt": "hello"}- timeouts: list = []-- with patch("cron.scheduler._hermes_home", tmp_path), \- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \- patch("hermes_cli.env_loader.load_hermes_dotenv"), \- patch("hermes_cli.env_loader.reset_secret_source_cache"), \- patch("hermes_state_registry.acquire"), \- patch(- "hermes_cli.runtime_provider.resolve_runtime_provider",- return_value=_RUNTIME,- ), \- patch("run_agent.AIAgent") as mock_agent_cls, \- patch(- "cron.scheduler.concurrent.futures.ThreadPoolExecutor",- side_effect=_session_db_executor(timeouts),- ):- mock_agent = MagicMock()- mock_agent.run_conversation.return_value = {"final_response": "ok"}- mock_agent_cls.return_value = mock_agent-- success, _output, _final_response, _error = run_job(job)-- # Config value was passed through — not the 10s default.- assert timeouts == [0.2]- assert success is True- assert mock_agent_cls.call_args.kwargs["session_db"] is None---class TestDispatchGuardReleasedAfterHang:- """End-to-end: the real bug symptom was every later tick silently- skipping the job forever. Confirm the fix actually clears that path."""-- def test_guard_is_released_and_job_refires_after_sessiondb_hang(self, tmp_path, monkeypatch):- import cron.scheduler as sched-- monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.2")- sched._parallel_pools.clear()- sched._parallel_pool_max_workers.clear()- sched._running_job_ids.clear()-- job = {- "id": "guard-sessiondb-hang",- "name": "guard-sessiondb-hang",- "prompt": "hello",- "schedule": "every 5m",- "enabled": True,- "next_run_at": "2020-01-01T00:00:00",- "deliver": "local",- }- timeouts: list = []-+ (tmp_path / "config.yaml").write_text("cron:\n session_db_timeout_seconds: 0.02\n")+ entered, release, closed = threading.Event(), threading.Event(), threading.Event()+ owner.db.close.side_effect = closed.set++ def acquire(_path):+ entered.set()+ release.wait(10)+ return owner.db++ try:+ with patch("hermes_state_registry.acquire", side_effect=acquire):+ started = time.monotonic()+ success, _, response, error = scheduler.run_job(job, execution_id=execution_id)+ elapsed = time.monotonic() - started+ assert entered.is_set()+ assert elapsed < 5+ assert not success and response == "" and error and "TimeoutError" in error+ agent_cls.assert_not_called()+ owner.db.close.assert_not_called()+ release.set()+ assert closed.wait(5), "late borrowed reference was leaked"+ owner.db.close.assert_called_once()+ finally:+ release.set()+ assert closed.wait(5)++[email protected]("failure", ["wrong-store", "acquire-error"])+def test_owner_store_failure_never_runs_unpersisted_agent(owner_run, failure):+ owner, job, execution_id, agent_cls = owner_run+ wrong_db = MagicMock()+ with patch("hermes_state_registry.acquire", return_value=wrong_db,+ side_effect=OSError("store unavailable") if failure == "acquire-error" else None):+ success, _, response, error = scheduler.run_job(job, execution_id=execution_id)+ assert not success and response == ""+ assert error and ("canonical owner store" if failure == "wrong-store" else "store unavailable") in error+ agent_cls.assert_not_called()+ owner.db.close.assert_not_called()+ assert wrong_db.close.call_count == (1 if failure == "wrong-store" else 0)+++def test_guard_is_released_and_job_refires_after_sessiondb_hang(owner_run, monkeypatch):- owner, job, _, agent_cls = owner_run++ owner, _job, _, agent_cls = owner_run+ monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.02")+ from cron import jobs++ release = threading.Event()+ closed = threading.Event()+ owner.db.close.side_effect = closed.set+ calls = []++ def acquire(_path):+ calls.append(True)+ if len(calls) == 1:+ release.wait(10)+ return owner.db++ # The scheduler dispatches through the authority; emulate only transport and+ # execution admission, retaining the real guard and run_job lifecycle.+ def admitted(fired, **kwargs):+ token = session_cron._execution.set((owner, "owner-session", fired["id"], kwargs["execution_id"]))try:- with patch("cron.scheduler._hermes_home", tmp_path), \- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \- patch("hermes_cli.env_loader.load_hermes_dotenv"), \- patch("hermes_cli.env_loader.reset_secret_source_cache"), \- patch("hermes_state_registry.acquire"), \- patch(- "hermes_cli.runtime_provider.resolve_runtime_provider",- return_value=_RUNTIME,- ), \- patch("run_agent.AIAgent") as mock_agent_cls, \- patch(- "cron.scheduler.concurrent.futures.ThreadPoolExecutor",- side_effect=_session_db_executor(timeouts),- ), \- patch.object(sched, "get_due_jobs", return_value=[job]), \- patch.object(sched, "claim_job_for_fire", return_value=True), \- patch.object(sched, "save_job_output", return_value="/tmp/out"), \- patch.object(sched, "mark_job_run"), \- patch.object(sched, "_deliver_result", return_value=None):- mock_agent = MagicMock()- mock_agent.run_conversation.return_value = {"final_response": "ok"}- mock_agent_cls.return_value = mock_agent-- n = sched.tick(verbose=False) # sync=True by default: waits for the job- assert n == 1- assert timeouts == [0.2]-- # Without the fix this would still contain the job ID forever.- assert "guard-sessiondb-hang" not in sched.get_running_job_ids()-- # A second tick can dispatch the same job again — before the- # fix this would log "already running — skipping" and- # return 0.- n2 = sched.tick(verbose=False)- assert n2 == 1+ return scheduler.run_job(fired, **kwargs)finally:- sched._running_job_ids.discard(sched._inflight_key("guard-sessiondb-hang"))- sched._shutdown_parallel_pool()---# ===========================================================================-# Bug #72782: late SessionDB result leaks FDs after timeout abandonment-# ===========================================================================----class TestLateSessionDbClosedAfterTimeout:- """End-to-end: when SessionDB init times out but later completes inside the- abandoned worker, the orphaned result must be closed (#72782)."""-- def test_late_session_db_result_is_closed(self, tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.2")- never_set = threading.Event()- late_db_holder = [] # captures the SessionDB returned by the late init-- def _hanging_then_capture():- never_set.wait(timeout=30)- db = MagicMock()- late_db_holder.append(db)- return db-- job = {"id": "late-close-test", "name": "test", "prompt": "hello"}+ session_cron._execution.reset(token)+ with jobs.use_cron_store(owner.db.db_path.parent):+ saved = jobs.create_job(prompt="hello", schedule="every 5m", deliver="local")try:- with patch("cron.scheduler._hermes_home", tmp_path), \- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \- patch("hermes_cli.env_loader.load_hermes_dotenv"), \- patch("hermes_cli.env_loader.reset_secret_source_cache"), \- patch("hermes_state_registry.acquire", side_effect=_hanging_then_capture), \- patch(- "hermes_cli.runtime_provider.resolve_runtime_provider",- return_value={- "api_key": "test-key",- "base_url": "https://example.invalid/v1",- "provider": "openrouter",- "api_mode": "chat_completions",- },- ), \- patch("run_agent.AIAgent") as mock_agent_cls:- mock_agent = MagicMock()- mock_agent.run_conversation.return_value = {"final_response": "ok"}- mock_agent_cls.return_value = mock_agent-- success, _output, _final_response, _error = run_job(job)- # run_job returned promptly after the timeout; session_db is None- assert success is True-- # Release the hanging init so the abandoned worker completes.- never_set.set()- # Wait for the done-callback to fire and close the late result.- for _ in range(50):- if late_db_holder and late_db_holder[0].close.called:- break- time.sleep(0.1)+ with patch("hermes_state_registry.acquire", side_effect=acquire), \+ patch("cron.scheduler_authority.run_canonical_job", side_effect=admitted), \+ patch("cron.scheduler_authority.reconcile_pending"), \+ patch.object(scheduler, "get_due_jobs", return_value=[saved]):+ assert scheduler.tick() == 1+ assert saved["id"] not in scheduler.get_running_job_ids()+ agent_cls.assert_not_called()+ release.set()+ assert closed.wait(5)+ assert scheduler.tick() == 1+ assert len(calls) == 2+ assert agent_cls.call_count == 1+ final_job = jobs.get_job(saved["id"])+ assert final_job and final_job["last_status"] == "ok"finally:- never_set.set()-- assert len(late_db_holder) == 1, "SessionDB() should have completed once"- late_db_holder[0].close.assert_called_once(), (- "The SessionDB that completed after the timeout must be closed by "- "the done-callback — otherwise its SQLite FDs leak until process exit (#72782)"- )---# ===========================================================================-# #96290: gated runs must not open the session store at all-# ===========================================================================--class TestSessionDbInitAfterEarlyReturns:- """SessionDB init moved AFTER the wake-gate / prompt-validation early- returns (#96290): a run that never reaches the agent must never open- state.db, so there is no handle for a gated return path to abandon."""-- def test_wake_gate_false_never_opens_session_db(self, tmp_path, monkeypatch):- monkeypatch.delenv("HERMES_CRON_SESSION_DB_TIMEOUT", raising=False)- job = {- "id": "gated-no-db",- "name": "gated-no-db",- "prompt": "hello",- "script": "gate.py",- }-- with patch("cron.scheduler._hermes_home", tmp_path), \- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \- patch("hermes_cli.env_loader.load_hermes_dotenv"), \- patch("hermes_cli.env_loader.reset_secret_source_cache"), \- patch("hermes_state_registry.acquire") as mock_db_cls, \- patch(- "cron.scheduler._run_job_script_with_claim_heartbeat",- return_value=(True, '{"wakeAgent": false}'),- ), \- patch("run_agent.AIAgent") as mock_agent_cls:- success, _output, _final_response, _error = run_job(job)-- assert success is True- mock_db_cls.assert_not_called()- mock_agent_cls.assert_not_called()+ release.set()+ scheduler._shutdown_parallel_pool()+++def test_wake_gate_false_never_opens_session_db(owner_run):+ _, job, execution_id, agent_cls = owner_run+ job["script"] = "gate.py"+ with patch("hermes_state_registry.acquire") as acquire, \+ patch("cron.scheduler._run_job_script_with_claim_heartbeat", return_value=(True, '{"wakeAgent": false}')):+ success, _, _, error = scheduler.run_job(job, execution_id=execution_id)+ assert success and error is None+ acquire.assert_not_called()+ agent_cls.assert_not_called()diff --cc tests/hermes_cli/test_config_guard_surfaces.pyindex 11d9ef1a365,cddb84c4f96..cd308b8fc57--- a/tests/hermes_cli/test_config_guard_surfaces.py+++ b/tests/hermes_cli/test_config_guard_surfaces.py@@@ -58,36 -58,12 +58,36 @@@ class TestCronRunJobGuardjob.update(overrides)return job- def test_run_job_fails_closed_on_corrupt_config(self, tmp_path):- from cron.scheduler import run_job+ @pytest.mark.asyncio+ async def test_run_job_fails_closed_on_corrupt_config(self, tmp_path):+ import json+ from types import SimpleNamespace- _write_corrupt_config(tmp_path)+ from gateway.session_contract import SessionRef+ from gateway.session_cron import current_execution, execute+ from hermes_state_registry import acquire, release- success, _output_doc, final_response, error = run_job(self._job())+ _write_corrupt_config(tmp_path)+ # Agent-backed run_job is now a client. Exercise the scheduler's guard+ # through its owner entry, without launching a daemon or bypassing it.+ db = acquire(tmp_path / "state.db")+ ref = SessionRef("default", "cron-guard")+ db.create_session(ref.session_id, source="cron")+ owner = SimpleNamespace(db=db, pending_results={}, sessions={+ ref.session_id: SimpleNamespace(source=SimpleNamespace(user_id="cron-owner"))})+ admission = {"admission_id": "guard-fire", "request_id": "guard-fire",+ "principal_id": "cron-owner", "payload": {"text": ""}}+ policy = SimpleNamespace(request_json=json.dumps({+ "cron_job": self._job(), "extra_prompt": None, "request_id": "guard-fire"}))+ previous = current_execution()+ try:+ with pytest.raises(RuntimeError, match="Hermes stopped because your settings file"):+ await execute(owner, ref, admission, policy)- success, output_doc, final_response, error = owner.pending_results["guard-fire"]["result"]["cron_result"]++ success, _output_doc, final_response, error = owner.pending_results["guard-fire"]["result"]["cron_result"]+ assert current_execution() is previous+ assert not owner._cron_cancellations+ finally:+ release(db)assert success is Falseassert error is not Nonediff --cc tests/install/e2e-assets/verify-user-state.pyindex 5b420d92f06,ba7f64ae5df..55a36b906fd--- a/tests/install/e2e-assets/verify-user-state.py+++ b/tests/install/e2e-assets/verify-user-state.py@@@ -276,26 -276,14 +276,33 @@@ def _env_line_summary(path: str) -> dicreturn {"lines": len(lines), "comments": comments, "blanks": blanks, "key_order": order}+def _entry_record_unless_vanished(rel: str, abs_path: str) -> dict | None:+ """Volatile entries are recorded by kind only, never read.++ A SQLite sidecar can vanish between listdir and its digest (a live gateway closes the+ connection), and a lock file's bytes are unreadable while its owner holds it (Windows+ byte-range locks: Errno 13). Anything else vanishing still raises.+ """+ try:+ if _volatile_sidecar(rel) and not _is_link(abs_path):+ if not _lexists(abs_path):+ return None+ return {"kind": "dir" if os.path.isdir(abs_path) else "file"}+ return _entry_record(abs_path)+ except FileNotFoundError:+ if _volatile_sidecar(rel):+ return None+ raise++def _entry_record(abs_path: str) -> dict:+ try:+ return _read_entry_record(abs_path)+ except OSError as exc:+ raise ScanError(f"unreadable {abs_path}: {exc}") from exc+++ def _read_entry_record(abs_path: str) -> dict:if _is_link(abs_path):record: dict = {"kind": "symlink", "target": os.readlink(abs_path)}record["target_resolves"] = os.path.exists(os.path.realpath(abs_path))diff --cc tools/session_search_tool.pyindex 3b275bb58a9,fd64fcf6eca..ae1786a1700--- a/tools/session_search_tool.py+++ b/tools/session_search_tool.py@@@ -598,39 -616,17 +598,39 @@@ def _dispatch(query, role_filter, limitexclude_session_ids=_normalize_exclude_session_ids(exclude_session_ids))- def session_search(query: str = "", role_filter: str = None, limit: int = 3, db=None,- current_session_id: str = None, session_id: str = None, around_message_id: int = None,- window: int = 5, sort: str = None, profile: str = None, detail: str = "adaptive",- after: str = None, before: str = None, exclude_session_ids: Optional[list[str]] = None) -> str:+ def session_search(query: str = "", role_filter: str | None = None, limit: int = 3, db=None,+ current_session_id: str | None = None, session_id: str | None = None, around_message_id: int | None = None,+ window: int = 5, sort: str | None = None, profile: str | None = None, detail: str = "adaptive",+ after: str | None = None, before: str | None = None, exclude_session_ids: Optional[list[str]] = None) -> str:"""Run session search, closing DBs opened here. Positional order is frozen for old callers;new parameters are appended after ``detail``."""- from hermes_state import format_session_db_unavailable- from hermes_state_registry import acquire, release_or_close+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB, format_session_db_unavailable+ from hermes_state_registry import release_or_closeowned_dbs: list[Any] = []+ # A raw `@session:<profile>/<id>` link as session_id: ids never contain "/", so+ # split on it and adopt the embedded profile only when none was passed.+ if isinstance(session_id, str) and "/" in session_id:+ emb_profile, _, emb_id = session_id.partition("/")+ if emb_id:+ session_id = emb_id+ if emb_profile and (profile is None or not str(profile).strip()):+ profile = emb_profile+ # Cross-profile: swap in the named profile's DB (read-only) for every shape;+ # current-lineage guards key off ids that won't collide, so they stay inert.+ try:+ profile_db = _resolve_profile_db(profile)+ except Exception as e:+ logging.debug("session_search: cannot open profile %r", profile, exc_info=True)+ return tool_error(f"profile '{profile}': {e}", success=False)+ if profile_db is not None:+ db, current_session_id = profile_db, None+ owned_dbs.append(profile_db)if db is None:- db = _quiet(acquire, None, "SessionDB unavailable for session_search")+ db = _quiet(+ lambda: SessionDB(db_path=get_hermes_home() / "state.db", read_only=True),+ None, "SessionDB unavailable for session_search",+ )if db is None:return tool_error(format_session_db_unavailable(), success=False)owned_dbs.append(db)