The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: purge low-value tests, lane py05 (339 removed)
teknium1aedc6ccc3a85
diff --git a/tests/agent/transports/test_hermes_tools_mcp_server.py b/tests/agent/transports/test_hermes_tools_mcp_server.pyindex 09eeff2d9bd..e8049bc6b24 100644--- a/tests/agent/transports/test_hermes_tools_mcp_server.py+++ b/tests/agent/transports/test_hermes_tools_mcp_server.py@@ -9,7 +9,6 @@ build helper assembles a server when the SDK is present.from __future__ import annotationsimport inspect-from typing import get_argsfrom agent.transports.hermes_tools_mcp_server import (_signature_from_schema,@@ -36,7 +35,6 @@ class TestSignatureFromSchema:assert param.default is inspect.Parameter.empty-def test_skip_private_params(self):"""Params starting with '_' are excluded from the signature."""schema = {@@ -77,19 +75,7 @@ class TestSignatureFromSchema:assert annots["o"] == dict------class TestModuleSurface:- def test_module_imports_clean(self):- from agent.transports import hermes_tools_mcp_server as m- assert callable(m.main)- assert callable(m._build_server)- assert isinstance(m.EXPOSED_TOOLS, tuple)- assert len(m.EXPOSED_TOOLS) > 0def test_exposed_tools_are_safe_subset(self):"""We MUST NOT expose tools codex already has, because codex'@@ -108,10 +94,6 @@ class TestModuleSurface:)----class TestMain:def test_main_returns_2_when_mcp_unavailable(self, monkeypatch):"""When the mcp package isn't installed, main() should exitdiff --git a/tests/agent/transports/test_meta_codex_cache.py b/tests/agent/transports/test_meta_codex_cache.pyindex 6be2e7e8339..59e795f366e 100644--- a/tests/agent/transports/test_meta_codex_cache.py+++ b/tests/agent/transports/test_meta_codex_cache.py@@ -1,7 +1,5 @@"""Tests for Meta api.meta.ai prompt_cache_retention and transport plumbing."""-import json-from types import SimpleNamespaceimport pytest@@ -16,15 +14,6 @@ def transport():class TestMetaRetention:- def test_meta_retention_24h(self, transport):- kw = transport.build_kwargs(- model="muse-spark-1.2",- messages=[{"role": "user", "content": "Hi"}],- tools=[],- base_url="https://api.meta.ai/v1",- session_id="test-session",- )- assert kw.get("prompt_cache_retention") == "24h"def test_meta_retention_also_for_generic_model_name(self, transport):for model in ["muse-spark", "meta/muse-spark-1.2-2026-04-01", "gpt-5.4", ""]:@@ -63,8 +52,6 @@ class TestMetaRetention:)assert "prompt_cache_retention" not in kw- def test_non_meta_no_retention_helper(self):- assert _default_prompt_cache_retention_for_request("muse-spark-1.2", "https://generic.example.com/v1") is Nonedef test_meta_prompt_cache_key_is_content_addressed(self, transport):messages = [{"role": "user", "content": "Hi"}]@@ -97,18 +84,3 @@ class TestMetaRetention:reasoning_config={"effort": "high", "enabled": True},)assert kw.get("reasoning") == {"effort": "high", "summary": "auto"}-- def test_meta_request_hits_responses_plan(self, transport):- # Transport api_mode must be codex_responses so conversation_loop hits /v1/responses- assert transport.api_mode == "codex_responses"- kw = transport.build_kwargs(- model="muse-spark-1.2",- messages=[{"role": "user", "content": "Hi"}],- tools=[{"type": "function", "function": {"name": "terminal", "description": "x", "parameters": {"type": "object", "properties": {"command": {"type": "string"}}}}}],- base_url="https://api.meta.ai/v1",- session_id="sid",- )- # Ensure instructions/input/tools and retention present - i.e., responses shape- assert "instructions" in kw or "input" in kw- assert kw.get("prompt_cache_retention") == "24h"- assert "prompt_cache_key" in kwdiff --git a/tests/agent/transports/test_transport.py b/tests/agent/transports/test_transport.pyindex 792ac1520a7..cc5791ba8f3 100644--- a/tests/agent/transports/test_transport.py+++ b/tests/agent/transports/test_transport.py@@ -3,48 +3,12 @@import pytestfrom types import SimpleNamespace-from agent.transports.base import ProviderTransportfrom agent.transports.types import NormalizedResponse-from agent.transports import get_transport, register_transport, _REGISTRY+from agent.transports import get_transport# ── ABC contract tests ──────────────────────────────────────────────────-class TestProviderTransportABC:- """Verify the ABC contract is enforceable."""-- def test_cannot_instantiate_abc(self):- with pytest.raises(TypeError):- ProviderTransport()-- def test_concrete_must_implement_all_abstract(self):- class Incomplete(ProviderTransport):- @property- def api_mode(self):- return "test"- with pytest.raises(TypeError):- Incomplete()-- def test_minimal_concrete(self):- class Minimal(ProviderTransport):- @property- def api_mode(self):- return "test_minimal"- def convert_messages(self, messages, **kw):- return messages- def convert_tools(self, tools):- return tools- def build_kwargs(self, model, messages, tools=None, **params):- return {"model": model, "messages": messages}- def normalize_response(self, response, **kw):- return NormalizedResponse(content="ok", tool_calls=None, finish_reason="stop")-- t = Minimal()- assert t.api_mode == "test_minimal"- assert t.validate_response(None) is True # default- assert t.extract_cache_stats(None) is None # default- assert t.map_finish_reason("end_turn") == "end_turn" # default passthrough-# ── Registry tests ───────────────────────────────────────────────────────@@ -54,28 +18,6 @@ class TestTransportRegistry:assert get_transport("nonexistent_mode") is None-- def test_register_and_get(self):- class DummyTransport(ProviderTransport):- @property- def api_mode(self):- return "dummy_test"- def convert_messages(self, messages, **kw):- return messages- def convert_tools(self, tools):- return tools- def build_kwargs(self, model, messages, tools=None, **params):- return {}- def normalize_response(self, response, **kw):- return NormalizedResponse(content=None, tool_calls=None, finish_reason="stop")-- register_transport("dummy_test", DummyTransport)- t = get_transport("dummy_test")- assert t.api_mode == "dummy_test"- # Cleanup- _REGISTRY.pop("dummy_test", None)--# ── AnthropicTransport tests ────────────────────────────────────────────class TestAnthropicTransport:@@ -101,11 +43,6 @@ class TestAnthropicTransport:assert "input_schema" in result[0]-----def test_map_finish_reason(self, transport):assert transport.map_finish_reason("end_turn") == "stop"assert transport.map_finish_reason("tool_use") == "tool_calls"@@ -116,8 +53,6 @@ class TestAnthropicTransport:assert transport.map_finish_reason("unknown") == "stop"--def test_normalize_response_text(self, transport):"""Test normalization of a simple text response."""r = SimpleNamespace(@@ -216,17 +151,3 @@ class TestAnthropicTransport:assert tc.name == "terminal"assert tc.id == "toolu_123"assert '"command"' in tc.arguments---- def test_convert_messages_extracts_system(self, transport):- """Test convert_messages separates system from messages."""- messages = [- {"role": "system", "content": "You are helpful."},- {"role": "user", "content": "Hi"},- ]- system, msgs = transport.convert_messages(messages)- # System should be extracted- assert system is not None- # Messages should only have user- assert len(msgs) >= 1diff --git a/tests/agent/transports/test_types.py b/tests/agent/transports/test_types.pyindex 49d0042f012..47fbade31cd 100644--- a/tests/agent/transports/test_types.py+++ b/tests/agent/transports/test_types.py@@ -5,7 +5,6 @@ import jsonfrom agent.transports.types import (NormalizedResponse,ToolCall,- Usage,build_tool_call,map_finish_reason,)@@ -15,69 +14,16 @@ from agent.transports.types import (# ToolCall# ----------------------------------------------------------------------------class TestToolCall:- def test_basic_construction(self):- tc = ToolCall(id="call_abc", name="terminal", arguments='{"cmd": "ls"}')- assert tc.id == "call_abc"- assert tc.name == "terminal"- assert tc.arguments == '{"cmd": "ls"}'- assert tc.provider_data is None-- def test_none_id(self):- tc = ToolCall(id=None, name="read_file", arguments="{}")- assert tc.id is None-- def test_provider_data(self):- tc = ToolCall(- id="call_x",- name="t",- arguments="{}",- provider_data={"call_id": "call_x", "response_item_id": "fc_x"},- )- assert tc.provider_data["call_id"] == "call_x"- assert tc.provider_data["response_item_id"] == "fc_x"-# ---------------------------------------------------------------------------# Usage# ----------------------------------------------------------------------------class TestUsage:- def test_defaults(self):- u = Usage()- assert u.prompt_tokens == 0- assert u.completion_tokens == 0- assert u.total_tokens == 0- assert u.cached_tokens == 0-- def test_explicit(self):- u = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150, cached_tokens=80)- assert u.total_tokens == 150-# ---------------------------------------------------------------------------# NormalizedResponse# ----------------------------------------------------------------------------class TestNormalizedResponse:- def test_text_only(self):- r = NormalizedResponse(content="hello", tool_calls=None, finish_reason="stop")- assert r.content == "hello"- assert r.tool_calls is None- assert r.finish_reason == "stop"- assert r.reasoning is None- assert r.usage is None- assert r.provider_data is None-- def test_with_tool_calls(self):- tcs = [ToolCall(id="call_1", name="terminal", arguments='{"cmd":"pwd"}')]- r = NormalizedResponse(content=None, tool_calls=tcs, finish_reason="tool_calls")- assert r.finish_reason == "tool_calls"- assert len(r.tool_calls) == 1- assert r.tool_calls[0].name == "terminal"---# ---------------------------------------------------------------------------# build_tool_call@@ -90,12 +36,6 @@ class TestBuildToolCall:assert tc.provider_data is None-- def test_none_id(self):- tc = build_tool_call(id=None, name="t", arguments="{}")- assert tc.id is None--# ---------------------------------------------------------------------------# map_finish_reason# ---------------------------------------------------------------------------@@ -131,7 +71,6 @@ class TestToolCallBackwardCompat:the old SimpleNamespace(id, type, function=SimpleNamespace(name, arguments)) shape."""-def test_function_name_matches(self):tc = ToolCall(id="1", name="search", arguments='{"q":"test"}')assert tc.function.name == "search"@@ -143,9 +82,6 @@ class TestToolCallBackwardCompat:assert tc.function.arguments == tc.arguments---def test_getattr_pattern_matches_agent_loop(self):"""run_agent.py uses getattr(tool_call, 'call_id', None) — verify it works."""tc = ToolCall(id="1", name="fn", arguments="{}", provider_data={"call_id": "c1"})@@ -154,8 +90,6 @@ class TestToolCallBackwardCompat:assert getattr(tc_no_pd, "call_id", None) is None--def test_extra_content_getattr_pattern(self):"""_build_assistant_message uses getattr(tc, 'extra_content', None).@@ -193,8 +127,3 @@ class TestNormalizedResponseBackwardCompat:provider_data={"reasoning_details": details},)assert nr.reasoning_details == details-----diff --git a/tests/ci/test_assemble_review_comment.py b/tests/ci/test_assemble_review_comment.pyindex b7e60e0a076..b8ee423bc4a 100644--- a/tests/ci/test_assemble_review_comment.py+++ b/tests/ci/test_assemble_review_comment.py@@ -31,7 +31,6 @@ import jsonimport sysfrom pathlib import Path-import pytest_PATH = Path(__file__).resolve().parents[2] / "scripts" / "ci" / "assemble_review_comment.py"_spec = importlib.util.spec_from_file_location("assemble_review_comment", _PATH)@@ -65,8 +64,6 @@ def test_statuses_bad_json():assert sources == set()--def test_statuses_info():statuses = _status("review-label-gate", [{"kind": "info",@@ -79,20 +76,6 @@ def test_statuses_info():assert sources == {"review-label-gate"}--------------# ─── collect_failed_jobs ─────────────────────────────────────────────@@ -100,12 +83,6 @@ def test_failed_jobs_empty_needs():assert _mod.collect_failed_jobs("", "https://run") == []------def test_failed_jobs_excluded_by_source():"""Jobs whose name contains a declared source are excluded."""needs = json.dumps({@@ -117,70 +94,12 @@ def test_failed_jobs_excluded_by_source():assert items[0].title == "tests"------# ─── render_comment ───────────────────────────────────────────────────-------def test_render_group_header_for_errors():- """Errors appear under a '## ❌ Job failures' group header."""- items = [- ReviewItem(severity="error", title="tests", summary="Job **tests** failed.", link="https://run"),- ReviewItem(severity="error", title="lint", summary="Job **lint** failed.", link="https://run"),- ]- body = _mod.render_comment(items)- assert "## ❌ Job failures" in body- assert "### tests" in body- assert "### lint" in body- assert body.index("## ❌ Job failures") < body.index("### tests")------------------# ─── render_comment (pending jobs) ────────────────────────────────────-def test_render_pending_only_shows_header_with_clock():- """Pending jobs only — header has 'still waiting', footer lists jobs, no sections."""- body = _mod.render_comment([], pending_jobs=["ci-timings"])- assert body.startswith(MARKER)- assert "૮ >ﻌ< ა" in body- assert "Still running" in body- assert "`ci-timings`" in body- assert "##" not in body---def test_render_pending_notif():- items = [ReviewItem(severity="info", title="lockfile", summary="No changes.")]- body = _mod.render_comment(items, pending_jobs=["ci-timings"])- assert "૮ >ﻌ< ა" in body- assert "<sub>Still running 1 job: `ci-timings`</sub>" in body--# ─── render_comment (waiting for jobs to start) ───────────────────────@@ -204,55 +123,9 @@ def test_not_waiting_and_no_items_still_renders_all_good():assert "all good!" in body-def test_assemble_passes_waiting_through():- body = _mod.assemble(waiting=True)- assert "waiting for jobs to start" in body- assert "all good" not in body------# ─── assemble (integration) ──────────────────────────────────────────-------def test_assemble_review_status_detail_renders_sensitive_file_links():- statuses = _status("review-label-gate", [{- "kind": "action_required",- "title": "CI-sensitive file review",- "summary": "Changes detected.",- "detail": "**Sensitive files:**\n- [`ci.yml`](https://example.test/ci.yml)",- }])- body = _mod.assemble(review_statuses_json=statuses)- assert "**Sensitive files:**" in body- assert "[`ci.yml`](https://example.test/ci.yml)" in body---def test_assemble_info_keeps_screenshot_details_visible_below_its_summary():- statuses = _status("playwright e2e", [{- "kind": "info",- "title": "Desktop E2E screenshots",- "summary": "1 screenshot captured; 0 visual diffs.",- "detail": "<details>\n<summary>1 captured screenshot</summary>\n\n- [`proof.png`](https://example.test/artifact)\n\n</details>",- }])- body = _mod.assemble(review_statuses_json=statuses)- assert "## ℹ️ Info" in body- assert "1 screenshot captured; 0 visual diffs." in body- assert "<summary>1 captured screenshot</summary>" in body- assert "[`proof.png`](https://example.test/artifact)" in body------def test_assemble_with_timings_status():"""Timings status from the nested format renders as debug or warning."""statuses = _status("ci-timings", [{@@ -270,21 +143,6 @@ def test_assemble_with_timings_status():assert "## ⚠️" not in body-def test_assemble_with_lockfile_status():- """Lockfile no-changes status renders as visible info."""- statuses = _status("lockfile-diff", [{- "kind": "info",- "title": "package-lock.json",- "summary": "No lockfile changes — locked versions match the target branch.",- }])- body = _mod.assemble(review_statuses_json=statuses)- assert "## ℹ️ Info" in body- assert "### package-lock.json" in body- assert "No lockfile changes" in body----# ─── _attach_job_urls ────────────────────────────────────────────────@@ -307,51 +165,3 @@ def test_attach_job_urls_fills_missing_links():# Second item keeps its existing link, job_url is set separatelyassert items[1].link == "https://report"assert items[1].job_url == "https://fallback" # fell back to run_url---------def test_render_commit_info_below_header():- """Commit info is rendered below the header, above the content."""- body = _mod.render_comment(- [ReviewItem(severity="error", title="tests", summary="failed.")],- commit_info="<sub>running on [abc1234](https://commit-url) — fix: thing</sub>",- )- assert "# ૮ >ﻌ< ა ci review" in body- assert "running on [abc1234](https://commit-url)" in body- assert "fix: thing" in body- # Commit info appears before the content- assert body.index("abc1234") < body.index("## ❌")-----def test_assemble_passes_commit_info():- """assemble() passes commit_info through to render_comment."""- body = _mod.assemble(commit_info="<sub>running on abc1234</sub>")- assert "running on abc1234" in body- assert "all good!" in body---def test_render_both_emitted_link_and_job_url():- """An item with both an emitted link and a job_url shows both."""- item = ReviewItem(- severity="warning",- title="CI timings",- summary="Slower.",- link="https://artifact/report.html",- link_label="View report",- source="ci timings",- job_url="https://github.com/run/1/job/5",- )- body = _mod.render_comment([item])- assert "[View report](https://artifact/report.html)" in body- assert "[View job](https://github.com/run/1/job/5)" in body- # Both links on the same line, separated by ·- assert " · " in body--diff --git a/tests/ci/test_classify_changes.py b/tests/ci/test_classify_changes.pyindex 3a8d0f88b9d..d79244d2109 100644--- a/tests/ci/test_classify_changes.py+++ b/tests/ci/test_classify_changes.py@@ -10,7 +10,6 @@ from __future__ import annotationsimport importlib.utilimport ioimport json-import reimport subprocessimport sysfrom pathlib import Path@@ -141,16 +140,6 @@ CASES = {"flake.lock → nix only": (["flake.lock"], _lanes(nix=True)),# A flake-only file must not mask a Python change beside it."nix + python → both": (["nix/checks.nix", "agent/x.py"], _lanes(python=True, scan=True)),- # Nine checks run the built binary, so product Python is a nix input even- # when the diff touches no file under nix/.- "product python → nix": (["hermes_cli/config.py"], _lanes(python=True, scan=True)),- # tests/ is not packaged, so the built binary cannot change.- "tests-only → no nix": (- ["tests/agent/test_foo.py"],- _lanes(python=True, python_prod=False, scan=True),- ),- # Prose cannot change the closure or the binary.- "docs-only → no nix": (["README.md"], _lanes()),# install.ps1 is a shell script Python never imports, but it's also not# provably prose, so python stays on (fail-open) alongside the Windows lane."install.ps1 → installer": (["scripts/install.ps1"], _lanes(python=True, installer=True)),@@ -158,7 +147,6 @@ CASES = {["scripts/tests/test-install-ps1-longpath.ps1"],_lanes(python=True, installer=True),),- "python source alone → no installer lane": (["run_agent.py"], _lanes(python=True, scan=True)),# The Windows desktop-update hand-off is a PowerShell integration surface:# its tests spawn the real script and poll its loopback server. They run# when the script, the Electron side that launches it, or their own test@@ -181,7 +169,6 @@ CASES = {["apps/desktop/electron/updater-process.ts"],_lanes(frontend=True, desktop_updater=True),),- "python source alone → no desktop_updater lane": (["hermes_state.py"], _lanes(python=True, scan=True)),# `.rs` lives under apps/, so it matches `frontend` too. That lane builds# TypeScript and cannot notice a Rust error — before `rust` existed it was# the ONLY lane a Rust change ran, and the crate's tests never executed.@@ -248,22 +235,6 @@ CASES = {["eslint.config.shared.mjs"],_lanes(python=True, ci_review=True),),- "ui-tui eslint config → ci_review": (- ["ui-tui/eslint.config.mjs"],- _lanes(frontend=True, ci_review=True),- ),- "web eslint config → ci_review": (- ["web/eslint.config.js"],- _lanes(frontend=True, ci_review=True),- ),- "shared package eslint config → ci_review": (- ["apps/shared/eslint.config.mjs"],- _lanes(frontend=True, ci_review=True),- ),- "bootstrap-installer eslint config → ci_review": (- ["apps/bootstrap-installer/eslint.config.mjs"],- _lanes(frontend=True, ci_review=True),- ),"prettier config → ci_review": ([".prettierrc"],_lanes(python=True, ci_review=True),@@ -276,14 +247,6 @@ CASES = {[".github/actions/retry/action.yml"],DEFAULT,),- # Normal desktop source doesn't trigger ci_review.- "desktop src → no ci_review": (- ["apps/desktop/src/app.tsx"],- _lanes(frontend=True),- ),- # Fail open: CI-config / empty / blank diffs run everything.- ".github change → all": ([".github/workflows/tests.yml"], DEFAULT),- "action change → all": ([".github/actions/detect-changes/action.yml"], DEFAULT),"empty diff → all": ([], DEFAULT),"blank lines → all": (["", " "], DEFAULT),}@@ -294,55 +257,6 @@ def test_classify(files, expected):assert classify(files) == expected-_REPO = Path(__file__).resolve().parents[2]---def _yaml(rel: str) -> dict:- yaml = pytest.importorskip("yaml")- return yaml.safe_load((_REPO / rel).read_text(encoding="utf-8"))---def test_every_lane_reaches_the_composite_action():- """The action is the one surface every consumer reads, so it must carry all- of them — ci.yaml, nix.yml and docker.yml each re-export a different subset.- """- lanes = set(classify(["run_agent.py"]))- action_outputs = set(_yaml(".github/actions/detect-changes/action.yml")["outputs"])- assert lanes - action_outputs == set(), "lane(s) missing from the composite action's outputs"---def test_ci_jobs_only_gate_on_detect_outputs_that_detect_actually_declares():- """An ``if`` that reads an undeclared output resolves to the empty string.-- The lane then reports "skipping" on every PR, forever, and nothing goes red- — there is no error for referencing an output a job never declared. That is- exactly how the ``rust`` lane shipped dead: the classifier emitted it and- the composite action re-exported it, but ci.yaml's ``detect`` job did not,- so ``needs.detect.outputs.rust`` was never anything but "".- """- ci = _yaml(".github/workflows/ci.yaml")- declared = set(ci["jobs"]["detect"]["outputs"])-- referenced: set[str] = set()- for job in ci["jobs"].values():- for expr in _iter_if_expressions(job):- referenced.update(re.findall(r"needs\.detect\.outputs\.(\w+)", expr))-- assert referenced, "found no detect-gated jobs — the walk is broken, not the wiring"- assert referenced - declared == set(), "job(s) gate on an output detect never declares"---def _iter_if_expressions(job: object):- """Yield every ``if:`` string in a job, including inside its steps."""- if not isinstance(job, dict):- return- if isinstance(cond := job.get("if"), str):- yield cond- for step in job.get("steps", []) or []:- if isinstance(step, dict) and isinstance(cond := step.get("if"), str):- yield cond--def test_ci_review_files_returns_only_sensitive_paths_sorted_and_unique():assert ci_review_files(["apps/desktop/src/app.tsx",diff --git a/tests/ci/test_emit_review_status.py b/tests/ci/test_emit_review_status.pyindex b1587a5d13c..9ac1edfe0ce 100644--- a/tests/ci/test_emit_review_status.py+++ b/tests/ci/test_emit_review_status.py@@ -46,15 +46,5 @@ def test_approved_ci_review_is_visible_info():head_sha="abc123",)- assert results == [{- "kind": "info",- "title": "CI-sensitive file review",- "summary": (- "PR touches sensitive files, but the `ci-reviewed` label has been "- "added, approving them."- ),- "detail": (- "**Sensitive files changed:**\n"- "- [`.github/workflows/ci.yml`](https://github.com/nousresearch/hermes-agent/compare/base456...abc123#diff-b803fcb7f17ed9235f1e5cb1fcd2f5d3b2838429d4368ae4c57ce4436577f03f)"- ),- }]+ assert len(results) == 1+ assert results[0]["kind"] == "info"diff --git a/tests/ci/test_live_comment.py b/tests/ci/test_live_comment.pyindex b4c1329eb05..5bc7875ff38 100644--- a/tests/ci/test_live_comment.py+++ b/tests/ci/test_live_comment.py@@ -12,7 +12,6 @@ import importlib.utilimport sysfrom pathlib import Path-import pytest_PATH = Path(__file__).resolve().parents[2] / "scripts" / "ci" / "live_comment.py"_spec = importlib.util.spec_from_file_location("live_comment", _PATH)@@ -88,55 +87,6 @@ def test_parse_watch_workflows_keeps_commas_inside_a_name():assert _mod.parse_watch_workflows("") == []-def test_workflow_watch_list_names_a_workflow_that_exists():- """The names the workflow passes must match real workflow ``name:`` values.-- A name that matches nothing makes the poller silently drop that run- from the comment, which no unit test on its own would notice.- """- yaml = pytest.importorskip("yaml")- root = Path(__file__).resolve().parents[2]- caller = yaml.safe_load(- (root / ".github/workflows/ci-review-comment.yml").read_text(encoding="utf-8")- )- step = next(- s for s in caller["jobs"]["comment"]["steps"]- if "WATCH_WORKFLOWS" in (s.get("env") or {})- )- watched = _mod.parse_watch_workflows(step["env"]["WATCH_WORKFLOWS"])- assert watched, "the poller is watching nothing"-- known = set()- for path in (root / ".github/workflows").glob("*.yml"):- doc = yaml.safe_load(path.read_text(encoding="utf-8"))- if isinstance(doc, dict) and isinstance(doc.get("name"), str):- known.add(doc["name"])-- assert set(watched) <= known, f"unknown workflow names: {set(watched) - known}"---def test_poller_never_watches_its_own_workflow():- """The poller's own run must never gate completion.-- ``runs_all_completed`` waits until every relevant run is completed.- The poller's run is in progress for as long as it polls, so watching- itself would make the loop wait for itself and only ever exit on- timeout.- """- yaml = pytest.importorskip("yaml")- root = Path(__file__).resolve().parents[2]- doc = yaml.safe_load(- (root / ".github/workflows/ci-review-comment.yml").read_text(encoding="utf-8")- )- own_name = doc["name"]- step = next(- s for s in doc["jobs"]["comment"]["steps"]- if "WATCH_WORKFLOWS" in (s.get("env") or {})- )- watched = _mod.parse_watch_workflows(step["env"]["WATCH_WORKFLOWS"])- assert own_name not in watched--# ─── runs_all_completed ───────────────────────────────────────────────diff --git a/tests/ci/test_lockfile_diff.py b/tests/ci/test_lockfile_diff.pyindex 37f1e0af81f..4f8d6546e85 100644--- a/tests/ci/test_lockfile_diff.py+++ b/tests/ci/test_lockfile_diff.py@@ -39,10 +39,6 @@ BASE = _lock()----def test_add_remove_update_all_detected():head = _lock({@@ -72,19 +68,6 @@ def test_nested_dedup_is_distinct_entry():assert d["updated"] == [("node_modules/foo/node_modules/react", "17.0.2", "17.0.3")]-def test_render_markdown_contains_versions_and_nested_display():- d = _mod.diff_locks(- _mod.parse_lockfile(BASE),- _mod.parse_lockfile(_lock({"node_modules/react": {"version": "19.0.0"}})),- )- md = _mod.render_markdown({"apps/desktop/package-lock.json": d})- # Fragment starts directly with the per-lockfile subsection header.- assert md.startswith("#### `apps/desktop/package-lock.json`")- assert "`18.2.0`" in md and "`19.0.0`" in md- # nested display name keeps the parent chain visible- assert "nested under foo" in md--def test_render_markdown_omits_unchanged_lockfiles():changed = _mod.diff_locks({}, {"node_modules/x": "1.0.0"})unchanged = _mod.diff_locks({}, {})diff --git a/tests/ci/test_timings_report.py b/tests/ci/test_timings_report.pyindex f7c313d6a6d..723565aaf8e 100644--- a/tests/ci/test_timings_report.py+++ b/tests/ci/test_timings_report.py@@ -86,8 +86,6 @@ def test_large_regression_is_warning():assert "+33" in result["summary"]--def test_detail_shows_top_deltas():cur = _timings([_job("slow-job", 120.0), _job("fast-job", 30.0, start_s=120.0)])bl = _timings([_job("slow-job", 60.0), _job("fast-job", 60.0, start_s=60.0)])@@ -96,30 +94,3 @@ def test_detail_shows_top_deltas():assert "fast-job" in result["detail"]# Sorted by abs delta — slow-job (+60) before fast-job (-30)assert result["detail"].index("slow-job") < result["detail"].index("fast-job")-----def test_report_url_passed_through():- t = _timings([_job("tests", 60.0)])- result = _result(_mod.generate_review_status(t, None, report_url="https://artifact/123"))- assert result["link"] == "https://artifact/123"- assert result["link_label"] == "View report"-----def test_nested_format_structure():- """The return value is a list with one {source, results: [...]} entry."""- t = _timings([_job("tests", 60.0)])- statuses = _mod.generate_review_status(t, None)- assert isinstance(statuses, list)- assert len(statuses) == 1- assert statuses[0]["source"] == "ci timing"- assert isinstance(statuses[0]["results"], list)- assert len(statuses[0]["results"]) == 1- r = statuses[0]["results"][0]- assert r["kind"] == "debug"- assert r["title"] == "CI timings"- assert "summary" in r- assert "detail" in rdiff --git a/tests/computer_use/test_cua_atexit_teardown.py b/tests/computer_use/test_cua_atexit_teardown.pyindex 596e6216495..25e5e0c43ef 100644--- a/tests/computer_use/test_cua_atexit_teardown.py+++ b/tests/computer_use/test_cua_atexit_teardown.py@@ -23,14 +23,6 @@ from tools.computer_use import tool as cu_toolclass TestAtexitTeardown:- def test_shutdown_stops_a_live_backend(self):- """A cached backend is stopped when the interpreter exits."""- fake = MagicMock()- with patch.object(cu_tool, "_backend", fake):- cu_tool._shutdown_backend_atexit()- fake.stop.assert_called_once()--def test_shutdown_stops_every_session_backend(self):diff --git a/tests/computer_use/test_cua_cli_fallback_env.py b/tests/computer_use/test_cua_cli_fallback_env.pydeleted file mode 100644index b068b151a52..00000000000--- a/tests/computer_use/test_cua_cli_fallback_env.py+++ /dev/null@@ -1,60 +0,0 @@-"""Regression test: the cua-driver CLI-fallback transport must sanitize the-subprocess environment like every other cua-driver spawn site.--``_CuaDriverSession._call_tool_via_cli()`` (the EAGAIN/silent-empty MCP-fallback) invoked ``subprocess.run`` with no ``env=`` at all, so the-third-party ``cua-driver`` binary inherited the full, unsanitized parent-environment — including provider API keys and other Hermes-managed-secrets that ``_lifecycle_coro``'s primary MCP spawn already strips via-``_sanitize_subprocess_env(cua_driver_child_env())``.-"""--import json-from unittest.mock import MagicMock--from tools.computer_use.cua_backend_session import _CuaDriverSession---def _make_session() -> _CuaDriverSession:- # _call_tool_via_cli() doesn't touch any instance state (bridge/session/- # capabilities); bypass __init__ so the test doesn't need a real- # _AsyncBridge.- return object.__new__(_CuaDriverSession)---def _fake_completed_process(stdout: str) -> MagicMock:- proc = MagicMock()- proc.stdout = stdout- proc.stderr = ""- proc.returncode = 0- return proc---def test_cli_fallback_strips_provider_secret_from_subprocess_env(monkeypatch):- monkeypatch.setenv("ANTHROPIC_API_KEY", "«redacted:sk-…»")- monkeypatch.setenv("PATH", "/usr/bin:/bin")- monkeypatch.setattr(- "tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd",- lambda: "/resolved/cua-driver",- )-- captured = {}-- def fake_run(cmd, **kwargs):- captured["env"] = kwargs.get("env")- return _fake_completed_process(json.dumps({"tree_markdown": "root"}))-- monkeypatch.setattr("subprocess.run", fake_run)-- session = _make_session()- result = session._call_tool_via_cli("list_windows", {}, timeout=5.0)-- assert result["isError"] is False- assert captured["env"] is not None, "subprocess.run must receive an explicit env="- assert "ANTHROPIC_API_KEY" not in captured["env"]- # Sanitization filters secrets, not everything — an ordinary var survives.- # Original PATH entries are preserved; the hermes console-script dir may- # be prepended (see _sanitize_subprocess_env, issue #92998).- assert captured["env"].get("PATH", "").endswith("/usr/bin:/bin")--diff --git a/tests/computer_use/test_cua_perf_knobs.py b/tests/computer_use/test_cua_perf_knobs.pyindex ad8f3d3eab4..dfc8cb29f4b 100644--- a/tests/computer_use/test_cua_perf_knobs.py+++ b/tests/computer_use/test_cua_perf_knobs.py@@ -1,27 +1,9 @@"""Behavior contracts for computer_use latency knobs."""-from unittest.mock import patch-from tools.computer_use import cua_backendfrom tools.computer_use import tool as cu_tool-def test_max_image_dimension_default():- with patch("hermes_cli.config.load_config", return_value={}):- assert cua_backend._computer_use_max_image_dimension() == 1456-----def test_capture_after_mode_default_som():- with patch("hermes_cli.config.load_config", return_value={}):- assert cu_tool._capture_after_mode() == "som"------def test_aux_vision_route_caches_per_provider_model(monkeypatch):cu_tool._AUX_VISION_ROUTE_CACHE.clear()calls = {"n": 0}diff --git a/tests/computer_use/test_cua_wayland_env.py b/tests/computer_use/test_cua_wayland_env.pyindex df06e132d6c..05f18ef9acd 100644--- a/tests/computer_use/test_cua_wayland_env.py+++ b/tests/computer_use/test_cua_wayland_env.py@@ -1,15 +1,17 @@from unittest.mock import patch+import pytest+from tools.computer_use import cua_backend+pytestmark = pytest.mark.linux_only_VAR = "CUA_DRIVER_RS_ENABLE_WAYLAND"def _child_env(base_env, native_wayland):config = {"computer_use": {"native_wayland": native_wayland}}- with patch("hermes_cli.config.load_config", return_value=config), \- patch.object(cua_backend.sys, "platform", "linux"):+ with patch("hermes_cli.config.load_config", return_value=config):return cua_backend.cua_driver_child_env(base_env)diff --git a/tests/computer_use/test_doctor.py b/tests/computer_use/test_doctor.pyindex ae95a94f39c..ba0967e1da7 100644--- a/tests/computer_use/test_doctor.py+++ b/tests/computer_use/test_doctor.py@@ -79,8 +79,6 @@ def _degraded_report() -> dict:}--@pytest.fixture(autouse=True)def _default_cli_version_matches_report(monkeypatch):"""Existing tests mock only the MCP Popen handshake. ``subprocess.run``@@ -183,21 +181,6 @@ class TestDoctorExitCodes:class TestResponseShapeParsing:- def test_prefers_structuredContent(self):- from tools.computer_use import doctor-- proc = _fake_proc_with_responses(- {"jsonrpc": "2.0", "id": 1, "result": {}},- {"jsonrpc": "2.0", "id": 2, "result": {"structuredContent": _ok_report()}},- )- with patch("shutil.which", return_value="/fake/cua-driver"), \- patch("subprocess.Popen", return_value=proc), \- patch("sys.stdout", new_callable=StringIO) as out:- doctor.run_doctor()- # Header line includes driver version + platform + overall.- text = out.getvalue()- assert "darwin" in text- assert "ok" in textdef test_jsonrpc_error_response_exits_2(self, capsys):@@ -237,22 +220,6 @@ class TestArgPassthrough:"binary_version", "tcc_accessibility",]- def test_skip_passed_through(self):- from tools.computer_use import doctor-- proc = _fake_proc_with_responses(- {"jsonrpc": "2.0", "id": 1, "result": {}},- {"jsonrpc": "2.0", "id": 2, "result": {"structuredContent": _ok_report()}},- )- with patch("shutil.which", return_value="/fake/cua-driver"), \- patch("subprocess.Popen", return_value=proc), \- patch("sys.stdout", new_callable=StringIO):- doctor.run_doctor(skip=["bundle_identity"])- writes = [call.args[0] for call in proc.stdin.write.call_args_list]- call_payload = next(json.loads(w) for w in writes if "tools/call" in w)- assert call_payload["params"]["arguments"]["skip"] == ["bundle_identity"]--# ── json output ────────────────────────────────────────────────────────────@@ -332,7 +299,7 @@ class TestDriverCmdResolution:patch("sys.stdout", new_callable=StringIO):assert doctor.run_doctor() == 0- health.assert_called_once_with(str(driver), include=(), skip=(), timeout=12.0)+ assert health.call_args.args[0] == str(driver)# ── cua-driver 0.10 unclassified health_report fallback ────────────────────@@ -386,9 +353,6 @@ class TestHealthReportFallback:"""---def test_extract_raises_health_report_unavailable_on_isError(self):from tools.computer_use import doctor@@ -397,7 +361,6 @@ class TestHealthReportFallback:assert "Permission denied" in str(ei.value) or "unclassified" in str(ei.value).lower() or "risk" in str(ei.value).lower()-# ── binary identity (CLI --version vs health_report) ───────────────────────@@ -441,7 +404,6 @@ class TestDoctorVersionIdentity:assert payload["hermes_identity"]["version_mismatch"] is False-def test_failed_tcc_row_from_health_report_names_the_stale_row_reset_for_that_service():"""A failed ``tcc_*`` row from the driver's own health_report (0.22+, not only the 0.10 fallback probes) mustcarry the stale-grant recovery for its own TCC service, because System Settings can show the toggle ON whilediff --git a/tests/conformance/persistence/test_cells_wave2_stubs.py b/tests/conformance/persistence/test_cells_wave2_stubs.pydeleted file mode 100644index 670f04121fc..00000000000--- a/tests/conformance/persistence/test_cells_wave2_stubs.py+++ /dev/null@@ -1,47 +0,0 @@-"""Wave-2 cell stubs — contract clauses named, implementations interlocked.--These are deliberate ``pytest.skip`` placeholders, not TODOs: each names the-exact contract clause it will pin and the reason it is not implemented in the-skeleton PR. See the tracking issue (#80921) for the full ~39-cell matrix.-"""--from __future__ import annotations--import pytest---def test_cell4_fork_determinism_on_rewind_stub():- """Cell 4 — fork determinism on the edit/rewind paths.-- Contract clause: after an edit/rewind fork, recovery yields exactly the- chosen prefix (no resurrection of superseded turns, no archived-copy- duplication), deterministically across independent recovery passes.-- Deliberately deferred: the rewind/archive semantics this cell would pin- are being actively redesigned in #82956–#82959 (durable row-id- addressing, archive-mode dedup, /retry archive_drop plumbing). Writing- the cell against today's behavior would test a moving target; it lands- as that cluster's conformance check once the contract settles.- """- pytest.skip(- "wave 2: interlocked with the rewind/archive redesign "- "(#82956-#82959) — cell lands as that cluster's conformance check"- )---def test_cell5_delivery_outbox_exactly_once_stub():- """Cell 5 — effect exactly-once across the delivery outbox boundary.-- Contract clause: a crash between provider send and durable record must- not double-deliver on catch-up (cron ticker restart, gateway reboot) —- the cell the paper (arXiv:2608.03836) probes as 'effect exactly-once',- distinct from cell 2's consume-once (claim vs side-effect).-- Deliberately deferred: requires a deterministic fake-transport seam for- the delivery path (the send must be observable without a live adapter);- the cron delivery-scope interplay is also in flight (#83197/#83557).- """- pytest.skip(- "wave 2: needs a deterministic fake-transport seam; cron delivery "- "scope fixes in flight (#83197/#83557)"- )diff --git a/tests/cron/test_agent_scheduling_gate.py b/tests/cron/test_agent_scheduling_gate.pyindex b8dc88de2a6..b0a54c63a12 100644--- a/tests/cron/test_agent_scheduling_gate.py+++ b/tests/cron/test_agent_scheduling_gate.py@@ -32,21 +32,8 @@ class TestGateOffDefault:"cronjob", "messaging", "clarify",]- def test_none_config_denies_cronjob(self):- assert _resolve_cron_disabled_toolsets(None) == [- "cronjob", "messaging", "clarify",- ]- def test_cron_section_present_but_gate_absent(self):- cfg = {"cron": {"preflight": True}}- assert _resolve_cron_disabled_toolsets(cfg) == [- "cronjob", "messaging", "clarify",- ]- def test_explicit_false_matches_default(self):- cfg = {"cron": {"allow_agent_scheduling": False}}- assert _resolve_cron_disabled_toolsets(cfg) == \- _resolve_cron_disabled_toolsets({})@pytest.mark.parametrize("falsy", [False, None, "", 0])def test_falsy_values_keep_gate_off(self, falsy):@@ -101,11 +88,6 @@ class TestUserLayerUnchanged:# No duplicate when the user names an already-denied toolset.assert disabled.count("cronjob") == 1- def test_user_can_still_deny_memory_for_cron(self):- # Memory is no longer policy-denied, but a user-level denylist- # entry still applies to cron runs.- cfg = {"agent": {"disabled_toolsets": ["memory"]}}- assert "memory" in _resolve_cron_disabled_toolsets(cfg)def test_blank_and_whitespace_entries_ignored(self):cfg = {diff --git a/tests/cron/test_blueprint_catalog.py b/tests/cron/test_blueprint_catalog.pyindex 4296c1d0ffb..49aae2d7664 100644--- a/tests/cron/test_blueprint_catalog.py+++ b/tests/cron/test_blueprint_catalog.py@@ -9,7 +9,6 @@ cron job store.import importlibimport jsonfrom pathlib import Path-from unittest.mock import patchimport pytest@@ -19,23 +18,12 @@ from cron.blueprint_catalog import (BlueprintSlot,fill_blueprint,get_blueprint,- blueprint_catalog_entry,blueprint_deeplink,- blueprint_form_schema,- blueprint_slash_command,)class TestCatalog:- def test_catalog_nonempty_and_keyed(self):- assert len(CATALOG) >= 1- for r in CATALOG:- assert get_blueprint(r.key) is r- def test_every_slot_has_known_type(self):- for r in CATALOG:- for s in r.slots:- assert s.type in {"time", "enum", "text", "weekdays"}def test_bad_slot_type_rejected(self):with pytest.raises(ValueError):@@ -68,9 +56,6 @@ class TestScheduleResolution:)assert spec["schedule"] == "0 14 * * 1-5"- def test_defaults_fill_when_omitted(self):- spec = fill_blueprint(get_blueprint("morning-brief"), {})- assert spec["schedule"] == "0 8 * * *"class TestValidation:@@ -121,16 +106,7 @@ class TestValidation:class TestRenderers:- def test_form_schema_fields(self):- schema = blueprint_form_schema(get_blueprint("morning-brief"))- names = [f["name"] for f in schema["fields"]]- assert names == ["time", "deliver"]- assert schema["key"] == "morning-brief"- def test_slash_command_defaults(self):- cmd = blueprint_slash_command(get_blueprint("morning-brief"))- assert cmd.startswith("/blueprint morning-brief")- assert "time=08:00" in cmddef test_deeplink_shape(self):@@ -152,24 +128,7 @@ def isolated_home(tmp_path, monkeypatch):class TestCommandHandler:- def test_bare_lists_catalog(self, isolated_home):- from hermes_cli.blueprint_cmd import handle_blueprint_command-- res = handle_blueprint_command("")- assert "morning-brief" in res.text and "Automation Blueprints" in res.text- assert res.agent_seed is None-- def test_name_seeds_agent(self, isolated_home):- from hermes_cli.blueprint_cmd import handle_blueprint_command- # `/blueprint <name>` (no inline slots) now seeds the agent to ask- # the user for each value conversationally instead of dumping fields.- res = handle_blueprint_command("morning-brief")- assert res.agent_seed is not None- assert "morning-brief" in res.agent_seed- assert "cronjob tool" in res.agent_seed- # the schedule template is handed to the agent to build the cron expr- assert "* * *" in res.agent_seeddef test_fill_creates_job(self, isolated_home):diff --git a/tests/cron/test_bot_chat_delivery_child_env.py b/tests/cron/test_bot_chat_delivery_child_env.pyindex e8915631779..41a4b142a02 100644--- a/tests/cron/test_bot_chat_delivery_child_env.py+++ b/tests/cron/test_bot_chat_delivery_child_env.py@@ -9,9 +9,7 @@ credentials into another profile's turn."""from __future__ import annotations-import osimport subprocess-from pathlib import Pathimport pytest@@ -91,20 +89,6 @@ def test_a_delivery_into_the_gateway_s_own_bot_chat_keeps_its_environment(fleet,assert env["DISCORD_ALLOWED_USERS"] == "root-operator"-def test_the_delivery_child_still_runs_this_install_and_targets_the_named_chat(fleet, monkeypatch):- """Guard rails the env change must not disturb: the running install, and `-p default`- only for a root home."""- root, beta = fleet- captured = _capture_child_env(monkeypatch)- delivery._deliver_to_bot_chat({"id": "j", "name": "nightly"}, "the brief", "beta")- argv = captured["argv"]- assert argv[:3] == [os.sys.executable, "-m", "hermes_cli.main"]- assert "-p" not in argv # a profile home is addressed by HERMES_HOME, not a flag- assert argv[3:10] == ["chat", "--in", "~", "-c", "Bot Chat", "--create-if-missing", "-Q"]-- captured.clear()- delivery._deliver_to_bot_chat({"id": "j", "name": "nightly"}, "the brief", "")- assert captured["argv"][3:5] == ["-p", "default"] # a root home keeps its explicit profile flagdef test_a_missing_target_home_is_refused_before_any_child_is_built(fleet, monkeypatch):diff --git a/tests/cron/test_bot_chat_warning_replay.py b/tests/cron/test_bot_chat_warning_replay.pyindex 8c126009d42..90c20152935 100644--- a/tests/cron/test_bot_chat_warning_replay.py+++ b/tests/cron/test_bot_chat_warning_replay.py@@ -47,9 +47,9 @@ def receipt_key(job):return job["_bot_chat_delivery_receipts"]["bot-chat:(own)"]["delivery_id"][email protected]("live", [False, True])[email protected]("first_failure", [False, True])[email protected]("suppress_retry", [False, True])[email protected]("live,first_failure,suppress_retry", [+ (False, True, True), (True, False, True), (True, True, False),+])def test_admitted_identity_rejects_category_changing_retry(owner, live, first_failure, suppress_retry):home, acquire, run = owneracquire(live)@@ -66,8 +66,9 @@ def test_admitted_identity_rejects_category_changing_retry(owner, live, first_farun.assert_not_called()[email protected]("status", ["queued", "claimed", "settled", "ambiguous"])[email protected]("live", [False, True])[email protected]("live,status", [+ (False, "queued"), (False, "settled"), (True, "claimed"), (True, "ambiguous"),+])def test_admitted_outcome_survives_suppressed_retry(owner, live, status):home, acquire, run = owneracquire(live)diff --git a/tests/cron/test_codex_execution_paths.py b/tests/cron/test_codex_execution_paths.pyindex 574e8f5446a..3172958c2d1 100644--- a/tests/cron/test_codex_execution_paths.py+++ b/tests/cron/test_codex_execution_paths.py@@ -1,4 +1,3 @@-import asyncioimport sysimport typesfrom types import SimpleNamespace@@ -9,10 +8,7 @@ sys.modules.setdefault("firecrawl", types.SimpleNamespace(Firecrawl=object))sys.modules.setdefault("fal_client", types.SimpleNamespace())import cron.scheduler as cron_scheduler-import gateway.run as gateway_runimport run_agent-from gateway.config import Platform-from gateway.session import SessionSourcedef _patch_agent_bootstrap(monkeypatch):@@ -122,70 +118,3 @@ def test_cron_run_job_codex_path_handles_internal_401_refresh(monkeypatch):assert _Codex401ThenSuccessAgent.last_init["api_mode"] == "codex_responses"-def test_gateway_run_agent_codex_path_handles_internal_401_refresh(monkeypatch):- _patch_agent_bootstrap(monkeypatch)- monkeypatch.setattr("agent.process_bootstrap.OpenAI", _FakeOpenAI)- monkeypatch.setattr(run_agent, "AIAgent", _Codex401ThenSuccessAgent)- monkeypatch.setattr(- gateway_run,- "_resolve_runtime_agent_kwargs",- lambda: {- "provider": "openai-codex",- "api_mode": "codex_responses",- "base_url": "https://chatgpt.com/backend-api/codex",- "api_key": "codex-token",- },- )- monkeypatch.setenv("HERMES_TOOL_PROGRESS", "false")- monkeypatch.setenv("HERMES_MODEL", "gpt-5.3-codex")-- _Codex401ThenSuccessAgent.refresh_attempts = 0- _Codex401ThenSuccessAgent.last_init = {}-- runner = gateway_run.GatewayRunner.__new__(gateway_run.GatewayRunner)- runner.adapters = {}- runner._ephemeral_system_prompt = ""- runner._prefill_messages = []- runner._reasoning_config = None- runner._provider_routing = {}- runner._fallback_model = None- runner._running_agents = {}- from unittest.mock import MagicMock, AsyncMock- runner.hooks = MagicMock()- runner.hooks.emit = AsyncMock()- runner.hooks.loaded_hooks = []- runner._session_db = None- # Ensure model resolution returns the codex model even if xdist- # leaked env vars cleared HERMES_MODEL.- monkeypatch.setattr(- gateway_run.GatewayRunner,- "_resolve_turn_agent_config",- lambda self, msg, model, runtime: {- "model": model or "gpt-5.3-codex",- "runtime": runtime,- },- )-- source = SessionSource(- platform=Platform.LOCAL,- chat_id="cli",- chat_name="CLI",- chat_type="dm",- user_id="user-1",- )-- result = asyncio.run(- runner._run_agent(- message="ping",- context_prompt="",- history=[],- source=source,- session_id="session-1",- session_key="agent:main:local:dm",- )- )-- assert result["final_response"] == "Recovered via refresh"- assert _Codex401ThenSuccessAgent.refresh_attempts == 1- assert _Codex401ThenSuccessAgent.last_init["provider"] == "openai-codex"- assert _Codex401ThenSuccessAgent.last_init["api_mode"] == "codex_responses"diff --git a/tests/cron/test_cron_bot_chat_delivery.py b/tests/cron/test_cron_bot_chat_delivery.pyindex 41f55c43bca..afc33e0d80a 100644--- a/tests/cron/test_cron_bot_chat_delivery.py+++ b/tests/cron/test_cron_bot_chat_delivery.py@@ -16,7 +16,6 @@ from unittest import mockimport pytest-from cron import scheduler as schedfrom cron import scheduler_delivery as sched_deliveryfrom cron.scheduler import _resolve_delivery_targetsfrom cron.scheduler_delivery import (@@ -26,7 +25,7 @@ from cron.scheduler_delivery import (parse_bot_chat_deliver_token,)from cron.scheduler_preflight import _preflight_check_delivery-from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV, write_turn_report+from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV# ── token parsing ────────────────────────────────────────────────────────────@@ -52,17 +51,8 @@ def test_non_bot_chat_tokens_pass_through():# ── target resolution ────────────────────────────────────────────────────────-def test_own_profile_resolves_without_name():- target = _resolve_bot_chat_target({"id": "j1"}, "")- assert target == {"platform": BOT_CHAT_PLATFORM, "chat_id": "", "thread_id": None}-def test_named_profile_resolves_when_exists():- with mock.patch("hermes_cli.profiles.profile_exists", return_value=True):- target = _resolve_bot_chat_target({"id": "j1"}, "research")- assert target is not None- assert target["platform"] == BOT_CHAT_PLATFORM- assert target["chat_id"] == "research"def test_unknown_profile_resolves_to_none():@@ -105,7 +95,6 @@ def test_create_validation_rejects_unknown_profile():with mock.patch("hermes_cli.profiles.profile_exists", return_value=False):err = _validate_bot_chat_deliver("bot-chat:ghost")assert err is not None- assert "machine-local" in errdef test_create_validation_accepts_bare_and_existing():@@ -153,13 +142,6 @@ def test_deliver_runs_canonical_bot_chat_lane():assert calls["env"][TURN_REPORT_FILE_ENV] == calls["report_path"]-def test_deliver_failure_returns_error_string():- with mock.patch.object(- sched_delivery, "_run_bot_chat_turn", return_value=_completed(returncode=1, stderr="boom")- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- assert "boom" in errdef test_deliver_failure_reports_both_streams_labeled():@@ -175,22 +157,6 @@ def test_deliver_failure_reports_both_streams_labeled():assert "stdout: banner out" in err-def test_deliver_failure_banner_only_stdout_names_exit_code_not_banner():- """The reported shape: empty stderr, stdout holding only the resume- banner — the recorded error must say what happened (exit code, banner-only- stdout) instead of echoing the banner as if it were a reason (#104056)."""- banner = ('↻ Resumed session 20260905_121420_8084c7 "Bot Chat" (1 user message, 1 total messages)'- '\n\nsession_id: 20260905_121420_8084c7')- with mock.patch.object(- sched_delivery, "_run_bot_chat_turn",- return_value=_completed(returncode=1, stdout=banner, stderr=""),- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- assert "exit code 1" in err- assert "stdout was only the resume banner" in err- assert "Resumed session" not in err- assert "stderr:" not in errdef test_deliver_failure_persisted_stdout_tail_is_short_and_redacted():@@ -309,38 +275,6 @@ def test_turn_that_never_ends_is_still_killed_at_the_cap(tmp_path):assert time.monotonic() - started < 8[email protected]_only-def test_bot_chat_turn_keeps_failure_tail_under_non_utf8_parent(tmp_path):- """The gateway parent's locale codec, not the child's UTF-8, decides the decode: a parent- outside UTF-8 mode with a C locale (the Linux twin of the cp1252 gateway parent on Windows)- used to lose the failing child's accented stderr entirely — the drain thread died on the- first undecodable byte and ``_format_failure_streams`` recorded nothing but the exit code- (#115894). Lossy decoding keeps the tail: on POSIX the accented characters degrade to- U+FFFD (the locale default stays, #66566) but the diagnostic text and exit code survive.-- ``PYTHONUTF8=0`` alone is not enough on 3.11 — PEP 538 coerces the C locale to UTF-8, so- the nested parent also sets ``PYTHONCOERCECLOCALE=0`` and asserts it is really ASCII."""- nested = textwrap.dedent("""- import json, locale, os, sys- from cron.scheduler_delivery import _run_bot_chat_turn- child = "import sys; sys.stderr.buffer.write({!r}); sys.exit(3)".format(- bytes.fromhex(sys.argv[1]))- result = _run_bot_chat_turn(- [sys.executable, "-c", child], dict(os.environ), sys.argv[2], timeout=30)- print(json.dumps({"preferred": locale.getpreferredencoding(False),- "returncode": result.returncode, "stderr": result.stderr}))- """)- env = {**_child_env(), "LC_ALL": "C", "LANG": "C", "PYTHONUTF8": "0", "PYTHONCOERCECLOCALE": "0"}- env.pop("PYTHONIOENCODING", None)- tail = "relatório nº 3: falhou\n"- res = subprocess.run(- [sys.executable, "-X", "utf8=0", "-c", nested, tail.encode("utf-8").hex(), str(tmp_path / "turn.json")],- env=env, timeout=60, check=True, capture_output=True, encoding="utf-8")-- result = json.loads(res.stdout)- assert result["preferred"].lower() in ("ansi_x3.4-1968", "ascii", "us-ascii"), result- assert result["returncode"] == 3- assert result["stderr"] == "relat\ufffd\ufffdrio n\ufffd\ufffd 3: falhou\n"@pytest.mark.linux_onlydiff --git a/tests/cron/test_cron_context_from.py b/tests/cron/test_cron_context_from.pyindex 6c8dfb45d45..bcad17f6b70 100644--- a/tests/cron/test_cron_context_from.py+++ b/tests/cron/test_cron_context_from.py@@ -1,6 +1,5 @@"""Tests for cron job context_from feature (issue #5439 Option C)."""-import loggingimport sysfrom pathlib import Path@@ -45,11 +44,6 @@ class TestJobContextFromField:assert loaded["context_from"] == [job_a["id"]]- def test_context_from_empty_string_normalized_to_none(self, cron_env):- from cron.jobs import create_job-- job = create_job(prompt="Hello", schedule="every 1h", context_from="")- assert job.get("context_from") is Noneclass TestBuildJobPromptContextFrom:@@ -289,34 +283,7 @@ class TestSelfContext:assert "prev output" in promptassert "previous run" in prompt.lower()- def test_tool_create_accepts_self(self, cron_env):- from tools.cronjob_tools import cronjob- from cron.jobs import get_job- import json- result = json.loads(cronjob(- action="create",- prompt="Scan for news",- schedule="every 1h",- context_from="self",- ))- assert result["success"] is True- job_id = result["job_id"]- assert get_job(job_id)["context_from"] == ["self"]-- def test_tool_update_accepts_self(self, cron_env):- from cron.jobs import create_job, get_job- from tools.cronjob_tools import cronjob- import json-- job = create_job(prompt="Scan", schedule="every 1h")- result = json.loads(cronjob(- action="update",- job_id=job["id"],- context_from="self",- ))- assert result["success"] is True- assert get_job(job["id"])["context_from"] == ["self"]class TestContinuityFlag:@@ -325,19 +292,6 @@ class TestContinuityFlag:It translates to the reserved 'self' entry in context_from internally."""- def test_create_with_continuity_true(self, cron_env):- from tools.cronjob_tools import cronjob- from cron.jobs import get_job- import json-- result = json.loads(cronjob(- action="create",- prompt="Scan for news",- schedule="every 1h",- continuity=True,- ))- assert result["success"] is True- assert get_job(result["job_id"])["context_from"] == ["self"]def test_create_continuity_false_is_noop(self, cron_env):from tools.cronjob_tools import cronjobdiff --git a/tests/cron/test_cron_created_delivery.py b/tests/cron/test_cron_created_delivery.pyindex 8a71abae799..d96b234343d 100644--- a/tests/cron/test_cron_created_delivery.py+++ b/tests/cron/test_cron_created_delivery.py@@ -124,25 +124,7 @@ class TestCronContextDeliveryResolution:_exit_cron_context(tokens, extra)assert result["deliver"] == "discord:#engineering"- def test_local_passes_through(self, temp_cron_home):- tokens, extra = _enter_cron_context("telegram", "-100999")- try:- result = _create(deliver="local")- finally:- _exit_cron_context(tokens, extra)- assert result["deliver"] == "local"- def test_stored_deliver_never_literal_origin_in_cron_context(self, temp_cron_home):- from cron.jobs import get_job-- tokens, extra = _enter_cron_context("telegram", "-100123456")- try:- result = _create(deliver="origin")- finally:- _exit_cron_context(tokens, extra)- job = get_job(result["job_id"])- stored = str(job.get("deliver", ""))- assert "origin" not in [p.strip() for p in stored.split(",")]class TestCronContextUpdatePath:@@ -186,11 +168,3 @@ class TestNonCronContextUnchanged:result = _create(deliver="origin")assert result["deliver"] == "origin"- def test_chat_session_omitted_deliver_unchanged(self, temp_cron_home):- # Outside cron context the resolution helper must be a no-op so the- # ordinary chat/CLI create path is byte-identical to before.- from tools.cronjob_tools import _resolve_cron_context_deliver-- assert _resolve_cron_context_deliver(None) is None- assert _resolve_cron_context_deliver("origin") == "origin"- assert _resolve_cron_context_deliver("origin,all") == "origin,all"diff --git a/tests/cron/test_cron_direct_api_call.py b/tests/cron/test_cron_direct_api_call.pyindex 222027e61e0..40d5d20699c 100644--- a/tests/cron/test_cron_direct_api_call.py+++ b/tests/cron/test_cron_direct_api_call.py@@ -45,30 +45,6 @@ def test_should_use_direct_api_call_only_for_cron_openai_wire():assert should_use_direct_api_call(moa) is False-def test_direct_api_call_runs_two_sequential_requests_on_same_thread():- """Mirror the 2nd+ call failure mode: two back-to-back completions.create."""- agent = _make_agent()- calls = {"n": 0}- fake_client = MagicMock()-- def _create(**_kwargs):- calls["n"] += 1- return fake_client-- fake_client.chat.completions.create.side_effect = [- SimpleNamespace(id="first"),- SimpleNamespace(id="second"),- ]- agent._create_request_openai_client.side_effect = _create-- first = direct_api_call(agent, {"model": "m", "messages": []})- second = direct_api_call(agent, {"model": "m", "messages": []})-- assert first.id == "first"- assert second.id == "second"- assert calls["n"] == 2- assert fake_client.chat.completions.create.call_count == 2- assert agent._close_request_openai_client.call_count == 2def test_direct_api_call_keeps_activity_alive_during_slow_wait(monkeypatch):@@ -124,10 +100,6 @@ def test_direct_api_call_keeps_activity_alive_during_slow_wait(monkeypatch):assert touches_while_blocked >= 3, (f"expected mid-wait activity heartbeats, got {touches_while_blocked}")- assert all(- call.args[0] == "waiting for non-streaming API response"- for call in agent._touch_activity.call_args_list- )def test_direct_api_call_heartbeat_stops_on_exception(monkeypatch):diff --git a/tests/cron/test_cron_direct_api_call_watchdog.py b/tests/cron/test_cron_direct_api_call_watchdog.pyindex ab8a716c40b..e8dd3e244b8 100644--- a/tests/cron/test_cron_direct_api_call_watchdog.py+++ b/tests/cron/test_cron_direct_api_call_watchdog.py@@ -88,14 +88,6 @@ def test_stalled_inline_call_is_aborted_and_raises_retryable_timeout():assert elapsed < 4.0, "watchdog did not bound the call"-def test_watchdog_abort_never_surfaces_as_interrupted_error():- """InterruptedError means "the user wants to stop" — the outer loop does- not retry it. A watchdog abort must stay retryable."""- agent = _make_agent(stale_timeout=0.2)- _stalling_client(agent, aborted=[])-- with pytest.raises(TimeoutError):- direct_api_call(agent, {"model": "m", "messages": []})def test_watchdog_kill_feeds_the_cross_turn_stale_circuit_breaker():@@ -175,23 +167,6 @@ def test_local_endpoint_infinite_budget_leaves_the_watchdog_disarmed():agent._abort_request_openai_client.assert_not_called()-def test_watchdog_uses_the_same_budget_as_the_interrupt_worker_path():- """The budget comes from ``_compute_non_stream_stale_timeout`` — the same- resolver the worker path's stale detector uses — with the live request- payload, so provider config and context scaling both apply."""- seen: list[dict] = []- agent = _make_agent(stale_timeout=30.0)- agent._compute_non_stream_stale_timeout = lambda payload: (- seen.append(payload) or 30.0- )- fake_client = MagicMock()- fake_client.chat.completions.create.return_value = SimpleNamespace(id="ok")- agent._create_request_openai_client.return_value = fake_client-- payload = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}- direct_api_call(agent, payload)-- assert seen == [payload]# ---------------------------------------------------------------------------@@ -392,25 +367,8 @@ def test_resolver_exception_propagates_instead_of_disarming_the_watchdog():# ----------------------------------------------------------------------------def test_inline_hard_timeout_matches_stale_budget():- """Keepalive httpx uses read=None. The injected timeout's read budget- must equal the stale watchdog so a no-op abort cannot hang for hours."""- from agent.chat_completion_helpers import _inline_nonstream_hard_timeout-- timeout = _inline_nonstream_hard_timeout(600.0)- assert timeout is not None- assert timeout.read == 600.0- assert timeout.connect == 60.0- assert timeout.write == 60.0- assert timeout.pool == 60.0--def test_inline_hard_timeout_disarmed_when_watchdog_is_disarmed():- from agent.chat_completion_helpers import _inline_nonstream_hard_timeout- assert _inline_nonstream_hard_timeout(float("inf")) is None- assert _inline_nonstream_hard_timeout(0) is None- assert _inline_nonstream_hard_timeout(-1) is Nonedef test_inline_call_passes_hard_read_timeout_to_the_sdk():diff --git a/tests/cron/test_cron_emfile_stall.py b/tests/cron/test_cron_emfile_stall.pyindex 2b895b386cf..a77355f7103 100644--- a/tests/cron/test_cron_emfile_stall.py+++ b/tests/cron/test_cron_emfile_stall.py@@ -84,9 +84,6 @@ class TestTickLockEmfileNotSwallowed:with patch.object(fcntl, "flock", side_effect=OSError(errno.EWOULDBLOCK, "Resource temporarily unavailable")):assert scheduler_mod.tick(verbose=False) == 0- def test_lock_contention_eagain_still_skips(self):- with patch.object(fcntl, "flock", side_effect=OSError(errno.EAGAIN, "Resource temporarily unavailable")):- assert scheduler_mod.tick(verbose=False) == 0# ── Fix 2: ticker loop survives EMFILE, reclaims fds, backs off, self-heals ──@@ -209,13 +206,4 @@ class TestEmfileHelpers:RuntimeError("Failed to read cron database: [Errno 24] Too many open files"))- def test_reclaim_fds_best_effort_never_raises(self):- # gc.collect + apply_nofile_soft_limit are both best-effort; the helper- # must tolerate missing/refusing platforms without raising.- assert scheduler_mod._reclaim_fds_best_effort() is None- def test_lock_contention_errno_classification(self):- assert scheduler_mod._is_lock_contention_errno(OSError(errno.EWOULDBLOCK, "x"))- assert scheduler_mod._is_lock_contention_errno(OSError(errno.EAGAIN, "x"))- assert not scheduler_mod._is_lock_contention_errno(OSError(errno.EMFILE, "x"))- assert not scheduler_mod._is_lock_contention_errno(OSError(errno.ENFILE, "x"))diff --git a/tests/cron/test_cron_empty_payload.py b/tests/cron/test_cron_empty_payload.pyindex 4e1792309da..cb62bf2f14f 100644--- a/tests/cron/test_cron_empty_payload.py+++ b/tests/cron/test_cron_empty_payload.py@@ -121,23 +121,8 @@ def test_update_job_rejects_clearing_the_only_payload(hermes_env):assert get_job(job["id"])["prompt"] == "check the news"-def test_update_job_rejects_dropping_last_skill_from_promptless_job(hermes_env):- from cron.jobs import create_job, update_job-- job = create_job(prompt=None, schedule="every 5m", skills=["daily-report"], deliver="local")-- with pytest.raises(ValueError, match="nothing to run"):- update_job(job["id"], {"skills": []})-def test_update_job_rejects_clearing_script_from_promptless_job(hermes_env):- from cron.jobs import create_job, update_job-- (hermes_env / "scripts" / "w.sh").write_text("echo hi\n")- job = create_job(prompt=None, schedule="every 5m", script="w.sh", deliver="local")-- with pytest.raises(ValueError, match="nothing to run"):- update_job(job["id"], {"script": ""})def test_update_job_rejects_toggling_no_agent_on_without_a_script(hermes_env):@@ -288,20 +273,6 @@ def test_run_job_fails_closed_and_never_builds_an_agent(hermes_env):assert "auto-paused" in final-def test_run_job_pauses_the_job_on_disk(hermes_env):- """Fail-closed isn't enough — the job must stop being scheduled."""- import cron.scheduler as scheduler- from cron.jobs import get_job-- job = _legacy_empty_job(hermes_env)-- scheduler.run_job(job)-- stored = get_job(job["id"])- assert stored["enabled"] is False- assert stored["state"] == "paused"- assert "nothing to run" in (stored["paused_reason"] or "")- assert stored["paused_at"]def test_run_one_job_does_not_resurrect_the_paused_job(hermes_env):@@ -525,34 +496,3 @@ def test_tool_update_still_renames_when_a_real_name_is_given(hermes_env):assert get_job(job["id"])["name"] == "new"-def test_tool_update_blank_scalars_still_clear_workdir_and_context_from(hermes_env):- """KNOWN HOLE, pinned deliberately — not an endorsement.-- ``workdir:""`` / ``context_from:[]`` / ``enabled_toolsets:[]`` are- documented clears, so a bulk-empty update that survives the payload guard- (because it keeps a script) still silently drops all three. Closing this- means changing documented semantics; recorded as a finding in- RECOVERY_REPORT.md instead. This test exists so the behaviour cannot change- unnoticed.- """- from cron.jobs import create_job, get_job-- (hermes_env / "scripts" / "w.sh").write_text("echo hi\n")- (hermes_env / "wd").mkdir()- job = create_job(- prompt=None, schedule="0 2 * * *", script="w.sh", name="keeper",- enabled_toolsets=["file"], workdir=str(hermes_env / "wd"),- deliver="local",- )- assert get_job(job["id"])["workdir"] == str(hermes_env / "wd")-- result = _cronjob(job_id=job["id"], action="update", script="w.sh",- workdir="", enabled_toolsets=[], context_from=[])-- assert result["success"] is True- stored = get_job(job["id"])- assert stored["name"] == "keeper" # protected by the fix above- assert stored["script"] == "w.sh" # payload survives- assert stored["workdir"] is None # still clobbered- assert stored["enabled_toolsets"] is None # still clobbered- assert stored["context_from"] is None # still clobbereddiff --git a/tests/cron/test_cron_failure_alert_remediation_hint.py b/tests/cron/test_cron_failure_alert_remediation_hint.pydeleted file mode 100644index 545fa4343ac..00000000000--- a/tests/cron/test_cron_failure_alert_remediation_hint.py+++ /dev/null@@ -1,47 +0,0 @@-"""The empty-chain failure alert must tell the operator how to fix it.--Field report: a user whose cron died with "No fallback-chain configured." still cannot self-serve — the alert names the problem but-not the remedy. The empty-chain branch of _fallback_chain_phrase() must name-the exact commands: `hermes fallback add` for the chain, and the-cron.model / cron.model_provider fleet-default keys as the operator-level-alternative. The exhausted branch stays terse — the chain is intact and the-problem is provider-side, so no config command applies.-"""--import cron.scheduler as scheduler-from cron.scheduler import _summarize_cron_failure_for_delivery---def test_empty_chain_alert_names_the_remediation_commands(monkeypatch):- monkeypatch.setattr(scheduler, "load_config", lambda: {"fallback_providers": []})- monkeypatch.setattr(scheduler, "get_fallback_chain", lambda cfg: [])- job = {"name": "semi-analyst-radar", "id": "aaa111"}- msg = _summarize_cron_failure_for_delivery(job, "Request timed out.")- assert "No backup provider is configured" in msg- assert "hermes fallback add" in msg- assert "cron.model_provider" in msg---def test_exhausted_chain_alert_does_not_carry_the_config_hint(monkeypatch):- monkeypatch.setattr(- scheduler, "load_config",- lambda: {"fallback_providers": [{"provider": "openrouter", "model": "x"}]},- )- monkeypatch.setattr(- scheduler, "get_fallback_chain",- lambda cfg: [{"provider": "openrouter", "model": "x"}],- )- job = {"name": "semi-analyst-radar", "id": "aaa111"}- msg = _summarize_cron_failure_for_delivery(job, "Request timed out.")- assert "No backup provider succeeded either." in msg- assert "hermes fallback add" not in msg---def test_rate_limit_empty_chain_also_carries_the_hint(monkeypatch):- monkeypatch.setattr(scheduler, "load_config", lambda: {"fallback_providers": []})- monkeypatch.setattr(scheduler, "get_fallback_chain", lambda cfg: [])- job = {"name": "kz-coverage", "id": "bbb222"}- msg = _summarize_cron_failure_for_delivery(job, "HTTP 429: rate limit exceeded")- assert "No backup provider is configured" in msg- assert "hermes fallback add" in msgdiff --git a/tests/cron/test_cron_failure_notice_copy.py b/tests/cron/test_cron_failure_notice_copy.pyindex 22b57fe0108..19089095163 100644--- a/tests/cron/test_cron_failure_notice_copy.py+++ b/tests/cron/test_cron_failure_notice_copy.py@@ -9,7 +9,6 @@ import reimport cron.scheduler as schedulerfrom cron.scheduler import _compose_run_delivery, _summarize_cron_failure_for_delivery-from hermes_constants import display_hermes_homeJOB = {"name": "Morning brief", "id": "ab12cd34"}_HTTP_LEAD = re.compile(r"failed: (HTTP|Error code:|provider )")@@ -20,23 +19,8 @@ def _no_chain(monkeypatch):monkeypatch.setattr(scheduler, "get_fallback_chain", lambda cfg: [])-def test_generic_failure_names_runs_and_pause_commands_and_the_real_output_dir():- msg = _summarize_cron_failure_for_delivery(JOB, "[Errno 2] No such file or directory: '/x.py'")- assert "/x.py" in msg # the raw detail survives as the cause- for cmd in ("hermes cron runs ab12cd34", "hermes cron run ab12cd34", "hermes cron pause ab12cd34"):- assert f"`{cmd}`" in msg- assert f"{display_hermes_home()}/cron/output/ab12cd34/" in msg- assert "cron output" not in msg # the unnamed internal location is gone-def test_auth_failure_points_at_login_and_a_retry_command(monkeypatch):- _no_chain(monkeypatch)- msg = _summarize_cron_failure_for_delivery(JOB, "Error code: 401 - Unauthorized")- assert "/login" in msg and "`hermes auth add <provider>`" in msg- assert "hermes login" not in msg # that command was removed- assert "`hermes cron run ab12cd34`" in msg- assert not _HTTP_LEAD.search(msg)- assert "401" not in msgdef test_auth_failure_names_the_pinned_provider_and_the_failing_profile(monkeypatch, tmp_path):@@ -82,24 +66,8 @@ def test_cron_cause_gloss_is_the_shared_table():assert provider_failure_notice("Morning brief", "ab12cd34", "unknown", backup_provider_phrase="x.") is None-def test_waf_block_names_the_header_fix_not_a_bare_rerun(monkeypatch):- """A firewall refusing the SDK's User-Agent is healed by a header or another provider,- never by `hermes cron run` alone — the action must say so (#53099, #70566)."""- _no_chain(monkeypatch)- msg = _summarize_cron_failure_for_delivery(JOB, "Error code: 403 - Sorry, you have been blocked")- assert "extra_headers" in msg and "`hermes cron edit ab12cd34 --provider <name>`" in msg, msg- assert "Run it again with" not in msg, msg- assert "rejected" not in msg.lower(), msg # not read as a key rejection-def test_transient_provider_failures_never_lead_with_jargon(monkeypatch):- _no_chain(monkeypatch)- for err in ("Request timed out.", "HTTP 429: Too Many Requests"):- msg = _summarize_cron_failure_for_delivery(JOB, err)- assert not _HTTP_LEAD.search(msg), msg- assert "fallback chain" not in msg.lower()- assert "`hermes cron run ab12cd34`" in msg- assert "`hermes cron runs ab12cd34`" in msgdef test_blocked_config_notice_says_it_did_not_run_and_will_self_heal():@@ -107,12 +75,4 @@ def test_blocked_config_notice_says_it_did_not_run_and_will_self_heal():JOB, success=False, error="[blocked_config] provider credential missing: no key",final_response="", output_file=None)assert blocked is True- assert "did not run" in textassert "provider credential missing: no key" in text- assert "Nothing was charged" in text- # Some blocks (MCP server temporarily down) clear on their own, so the retry- # line must not condition the retry on the user fixing something.- assert "once this is fixed" not in text- assert "`hermes cron doctor`" in text- for jargon in ("configuration validation", "LLM call", "pre-dispatch"):- assert jargon not in textdiff --git a/tests/cron/test_cron_import_error_skew_hint.py b/tests/cron/test_cron_import_error_skew_hint.pyindex cf7b4c4d80a..12a258f4da8 100644--- a/tests/cron/test_cron_import_error_skew_hint.py+++ b/tests/cron/test_cron_import_error_skew_hint.py@@ -45,17 +45,6 @@ def test_import_error_without_skew_stays_a_plain_import_message(monkeypatch):assert "hermes gateway restart" not in msg-def test_modulenotfound_matches_the_import_class(monkeypatch):- monkeypatch.setattr(- scheduler,- "_detect_gateway_code_skew",- lambda: ("aaaa111111", "bbbb222222"),- )- job = {"name": "nightly-digest", "id": "ccc333"}- msg = _summarize_cron_failure_for_delivery(- job, "ModuleNotFoundError: No module named 'agent.turn_context'"- )- assert "hermes gateway restart" in msgdef test_no_agent_script_import_error_never_blames_gateway_skew(monkeypatch):@@ -91,17 +80,3 @@ def test_skew_probe_failure_degrades_to_the_plain_message(monkeypatch):assert "cannot import name" in msg-def test_wrapper_seam_swallows_detector_import_failure(monkeypatch):- """_detect_gateway_code_skew itself never raises when the gateway module- is unimportable (e.g. stripped install)."""- import builtins-- real_import = builtins.__import__-- def failing_import(name, *args, **kwargs):- if name.startswith("gateway"):- raise ImportError("gateway package missing")- return real_import(name, *args, **kwargs)-- monkeypatch.setattr(builtins, "__import__", failing_import)- assert scheduler._detect_gateway_code_skew() is Nonediff --git a/tests/cron/test_cron_inactivity_timeout.py b/tests/cron/test_cron_inactivity_timeout.pyindex cf45ec41aa6..47edcdc74b2 100644--- a/tests/cron/test_cron_inactivity_timeout.py+++ b/tests/cron/test_cron_inactivity_timeout.py@@ -1,240 +1,7 @@-"""Tests for cron job inactivity-based timeout.+"""Tests for the cron inactivity watchdog loop (runs on its own daemon thread)."""-Tests cover:-- Active agent runs indefinitely (no inactivity timeout)-- Idle agent triggers inactivity timeout with diagnostic info-- Unlimited timeout (HERMES_CRON_TIMEOUT=0)-- Backward compat: HERMES_CRON_TIMEOUT env var still works-- Error message includes activity summary-"""--import concurrent.futures-import os-import sysimport threadingimport time-from pathlib import Path---# Ensure project root is importable-sys.path.insert(0, str(Path(__file__).parent.parent.parent))---class FakeAgent:- """Mock agent with controllable activity summary for timeout tests."""-- def __init__(self, idle_seconds=0.0, activity_desc="tool_call",- current_tool=None, api_call_count=5, max_iterations=90):- self._idle_seconds = idle_seconds- self._activity_desc = activity_desc- self._current_tool = current_tool- self._api_call_count = api_call_count- self._max_iterations = max_iterations- self._interrupted = False- self._interrupt_msg = None-- def get_activity_summary(self):- return {- "last_activity_ts": time.time() - self._idle_seconds,- "last_activity_desc": self._activity_desc,- "seconds_since_activity": self._idle_seconds,- "current_tool": self._current_tool,- "api_call_count": self._api_call_count,- "max_iterations": self._max_iterations,- }-- def interrupt(self, msg):- self._interrupted = True- self._interrupt_msg = msg-- def run_conversation(self, prompt):- """Simulate a quick agent run that finishes immediately."""- return {"final_response": "Done", "messages": []}---class SlowFakeAgent(FakeAgent):- """Agent that runs for a while, simulating active work then going idle."""-- def __init__(self, run_duration=0.5, idle_after=None, **kwargs):- super().__init__(**kwargs)- self._run_duration = run_duration- self._idle_after = idle_after # seconds before becoming idle- self._start_time = None-- def get_activity_summary(self):- summary = super().get_activity_summary()- if self._idle_after is not None and self._start_time:- elapsed = time.time() - self._start_time- if elapsed > self._idle_after:- # Agent has gone idle- idle_time = elapsed - self._idle_after- summary["seconds_since_activity"] = idle_time- summary["last_activity_desc"] = "api_call_streaming"- else:- summary["seconds_since_activity"] = 0.0- return summary-- def run_conversation(self, prompt):- self._start_time = time.time()- time.sleep(self._run_duration)- return {"final_response": "Completed after work", "messages": []}---class TestInactivityTimeout:- """Test the inactivity-based timeout polling loop in cron scheduler."""-- def test_active_agent_completes_normally(self):- """An agent that finishes quickly should return its result."""- agent = FakeAgent(idle_seconds=0.0)- _cron_inactivity_limit = 10.0- _POLL_INTERVAL = 0.1-- pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)- future = pool.submit(agent.run_conversation, "test prompt")- _inactivity_timeout = False-- result = None- while True:- done, _ = concurrent.futures.wait({future}, timeout=_POLL_INTERVAL)- if done:- result = future.result()- break- _idle_secs = 0.0- if hasattr(agent, "get_activity_summary"):- _act = agent.get_activity_summary()- _idle_secs = _act.get("seconds_since_activity", 0.0)- if _idle_secs >= _cron_inactivity_limit:- _inactivity_timeout = True- break-- pool.shutdown(wait=False)- assert result is not None- assert result["final_response"] == "Done"- assert not _inactivity_timeout- assert not agent._interrupted-- def test_idle_agent_triggers_timeout(self):- """An agent that goes idle should be detected and interrupted."""- # Agent will run for 0.3s, then become idle after 0.1s of that- agent = SlowFakeAgent(- run_duration=5.0, # would run forever without timeout- idle_after=0.1, # goes idle almost immediately- activity_desc="api_call_streaming",- current_tool="web_search",- api_call_count=3,- max_iterations=50,- )-- _cron_inactivity_limit = 0.5 # 0.5s inactivity triggers timeout- _POLL_INTERVAL = 0.1-- pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)- future = pool.submit(agent.run_conversation, "test prompt")- _inactivity_timeout = False-- result = None- while True:- done, _ = concurrent.futures.wait({future}, timeout=_POLL_INTERVAL)- if done:- result = future.result()- break- _idle_secs = 0.0- if hasattr(agent, "get_activity_summary"):- try:- _act = agent.get_activity_summary()- _idle_secs = _act.get("seconds_since_activity", 0.0)- except Exception:- pass- if _idle_secs >= _cron_inactivity_limit:- _inactivity_timeout = True- break-- pool.shutdown(wait=False, cancel_futures=True)- assert _inactivity_timeout is True- assert result is None # Never got a result — interrupted-- def test_unlimited_timeout(self):- """HERMES_CRON_TIMEOUT=0 means no timeout at all."""- agent = FakeAgent(idle_seconds=0.0)- _cron_inactivity_limit = None # unlimited-- pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)- future = pool.submit(agent.run_conversation, "test prompt")-- # With unlimited, we just await the result directly.- result = future.result()- pool.shutdown(wait=False)-- assert result["final_response"] == "Done"-- def _parse_cron_timeout(self, raw_value):- """Mirror the defensive parsing logic from cron/scheduler.py run_job()."""- if raw_value:- try:- return float(raw_value)- except (ValueError, TypeError):- return 600.0- return 600.0-- def test_timeout_env_var_parsing(self, monkeypatch):- """HERMES_CRON_TIMEOUT env var is respected."""- monkeypatch.setenv("HERMES_CRON_TIMEOUT", "1200")- raw = os.getenv("HERMES_CRON_TIMEOUT", "").strip()- _cron_timeout = self._parse_cron_timeout(raw)- assert _cron_timeout == 1200.0-- _cron_inactivity_limit = _cron_timeout if _cron_timeout > 0 else None- assert _cron_inactivity_limit == 1200.0--- def test_agent_without_activity_summary_uses_wallclock_fallback(self):- """If agent lacks get_activity_summary, idle_secs stays 0 (never times out).-- This ensures backward compat if somehow an old agent is used.- The polling loop will eventually complete when the task finishes.- """- class BareAgent:- def run_conversation(self, prompt):- return {"final_response": "no activity tracker", "messages": []}-- agent = BareAgent()- _cron_inactivity_limit = 0.1 # tiny limit- _POLL_INTERVAL = 0.1-- pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)- future = pool.submit(agent.run_conversation, "test")- _inactivity_timeout = False-- while True:- done, _ = concurrent.futures.wait({future}, timeout=_POLL_INTERVAL)- if done:- result = future.result()- break- _idle_secs = 0.0- if hasattr(agent, "get_activity_summary"):- try:- _act = agent.get_activity_summary()- _idle_secs = _act.get("seconds_since_activity", 0.0)- except Exception:- pass- if _idle_secs >= _cron_inactivity_limit:- _inactivity_timeout = True- break-- pool.shutdown(wait=False)- # Should NOT have timed out — bare agent has no get_activity_summary- assert not _inactivity_timeout- assert result["final_response"] == "no activity tracker"---class TestSysPathOrdering:- """Test that sys.path is set before repo-level imports."""-- def test_hermes_time_importable(self):- """hermes_time should be importable when cron.scheduler loads."""- # This import would fail if sys.path.insert comes after the import- from cron.scheduler import _hermes_now- assert callable(_hermes_now)class TestInactivityWatchdogLoop:diff --git a/tests/cron/test_cron_kanban_env_isolation.py b/tests/cron/test_cron_kanban_env_isolation.pyindex a177de98057..155e34bad7b 100644--- a/tests/cron/test_cron_kanban_env_isolation.py+++ b/tests/cron/test_cron_kanban_env_isolation.py@@ -59,10 +59,6 @@ def worker_env(monkeypatch):# ---------------------------------------------------------------------------class TestDispatcherOwnedPredicate:- def test_default_is_dispatcher_owned(self):- from agent.delegation_context import is_dispatcher_owned_worker_context-- assert is_dispatcher_owned_worker_context() is Truedef test_false_inside_non_dispatcher_context(self):from agent.delegation_context import (@@ -172,15 +168,6 @@ class TestKanbanGatesRespectContext:with non_dispatcher_owned_context():assert kanban_tools._default_task_id("t_explicit") == "t_explicit"- def test_skill_environment_gate(self, worker_env):- from agent.delegation_context import non_dispatcher_owned_context- import agent.skill_utils as su-- su._ENV_DETECT_CACHE.pop("kanban", None)- assert su._detect_environment("kanban") is True- with non_dispatcher_owned_context():- su._ENV_DETECT_CACHE.pop("kanban", None)- assert su._detect_environment("kanban") is Falsedef test_kanban_env_verdict_is_not_memoized(self, worker_env):"""`kanban` must bypass _ENV_DETECT_CACHE: caching it process-wide would@@ -274,7 +261,6 @@ class TestRunJobKanbanIsolation:def test_agent_runs_as_non_dispatcher(self, monkeypatch, worker_env):import cron.scheduler as sched- from cron import scheduler_delivery as sched_deliveryobserved: dict = {}self._install_stubs(monkeypatch, observed)@@ -288,7 +274,6 @@ class TestRunJobKanbanIsolation:"""The whole point of the ContextVar: os.environ must not be mutated, sothe worker's claim heartbeat and the gateway watchers keep working."""import cron.scheduler as sched- from cron import scheduler_delivery as sched_deliverybefore = {k: v for k, v in os.environ.items() if k.startswith("HERMES_KANBAN_")@@ -309,20 +294,9 @@ class TestRunJobKanbanIsolation:}assert after == before- def test_context_reset_after_job(self, monkeypatch, worker_env):- import cron.scheduler as sched- from cron import scheduler_delivery as sched_delivery- from agent.delegation_context import is_dispatcher_owned_worker_context-- observed: dict = {}- self._install_stubs(monkeypatch, observed)-- sched.run_job(self._job("kanban-iso-reset"))- assert is_dispatcher_owned_worker_context() is Truedef test_context_reset_even_when_job_raises(self, monkeypatch, worker_env):import cron.scheduler as sched- from cron import scheduler_delivery as sched_deliveryfrom agent.delegation_context import is_dispatcher_owned_worker_contextclass ExplodingAgent:@@ -352,7 +326,6 @@ class TestRunJobKanbanIsolation:restore this permanently destroyed the worker's identity; a ContextVar isper-thread and cannot."""import cron.scheduler as sched- from cron import scheduler_delivery as sched_deliverybefore = {k: v for k, v in os.environ.items() if k.startswith("HERMES_KANBAN_")diff --git a/tests/cron/test_cron_live_delivery_confirmation.py b/tests/cron/test_cron_live_delivery_confirmation.pyindex 080c247a8b4..fe436d16b04 100644--- a/tests/cron/test_cron_live_delivery_confirmation.py+++ b/tests/cron/test_cron_live_delivery_confirmation.py@@ -24,7 +24,6 @@ from unittest.mock import MagicMock, patchimport pytest-from cron import scheduler as schedfrom cron import scheduler_delivery as sched_deliveryfrom cron.scheduler import _deliver_resultfrom cron.scheduler_delivery import _confirm_adapter_delivery@@ -63,9 +62,6 @@ class TestConfirmAdapterDelivery:filtered = {"success": True, "filtered": "silence_narration", "delivered": False}assert _confirm_adapter_delivery(filtered, "j1") is False- def test_delivered_false_on_an_object_is_not_delivered(self):- result = _SendResult(success=True, message_id=42, delivered=False)- assert _confirm_adapter_delivery(result, "j1") is Falsedef test_positive_evidence_is_delivered_without_warning(self, caplog):with caplog.at_level(logging.WARNING, logger="cron.scheduler"):@@ -85,10 +81,6 @@ class TestConfirmAdapterDelivery:assert "UNVERIFIED" in caplog.textassert "92e639af907f" in caplog.text- def test_evidence_free_success_dict_is_accepted_but_warned(self, caplog):- with caplog.at_level(logging.WARNING, logger="cron.scheduler"):- assert _confirm_adapter_delivery({"success": True}, "j1") is True- assert "UNVERIFIED" in caplog.text# ---------------------------------------------------------------------------@@ -212,13 +204,6 @@ class TestFilteredResultIsNotDelivered:class TestEmptyPayloadFailsClosed:- def test_empty_payload_never_reaches_the_adapter(self, caplog):- with caplog.at_level(logging.INFO, logger="cron.scheduler"):- _, router_calls, _ = _run(_job(), " ", _SendResult(message_id=1))-- assert router_calls == [] # nothing was sent- assert "via live adapter" not in caplog.text # and nothing was claimed- assert "empty text and no media" in caplog.textdef test_empty_payload_never_reaches_the_standalone_sender(self, caplog):"""The native fallback must not re-open the hole the live lane closed.@@ -246,24 +231,6 @@ class TestEmptyPayloadFailsClosed:assert "live adapter send skipped (empty text and no media)" in error-class TestDeliveredLogNamesTheLane:- def test_log_includes_thread_and_message_id(self, caplog):- with caplog.at_level(logging.INFO, logger="cron.scheduler"):- error, _, _ = _run(- _job(thread_id="99"), "Nightly report.", _SendResult(message_id=1234),- )-- assert error is None- assert "via live adapter thread=99 message_id=1234" in caplog.text-- def test_log_uses_a_dash_when_the_lane_is_unknown(self, caplog):- """No thread and an evidence-free result must still be attributable."""- with caplog.at_level(logging.INFO, logger="cron.scheduler"):- error, _, _ = _run(_job(), "Nightly report.", _SendResult())-- assert error is None- assert "via live adapter thread=- message_id=-" in caplog.text- assert "UNVERIFIED" in caplog.textclass TestLiveDeliveryIsAFinalNotification:@@ -322,9 +289,6 @@ class TestNotifyIsConfigurable:text route and the media route so the two never disagree."""- def test_default_is_notify(self):- _, router_calls, _ = _run(_job(), "Nightly report.", _SendResult(message_id=1))- assert router_calls[0]["metadata"]["notify"] is Truedef test_explicit_false_disables_notify_on_text_route(self):_, router_calls, _ = _run(@@ -362,10 +326,6 @@ class TestNotifyIsConfigurable:_, router_calls, _ = _run(_job(), "Nightly report.", _SendResult(message_id=1), cron_cfg=cron_cfg)assert router_calls[0]["metadata"]["notify"] is True- def test_default_config_ships_notify_true(self):- from hermes_cli.config_defaults import DEFAULT_CONFIG-- assert DEFAULT_CONFIG["cron"]["delivery"]["notify"] is Trueclass TestUnverifiedDeliveryIsRecordedOnTheJob:@@ -383,28 +343,14 @@ class TestUnverifiedDeliveryIsRecordedOnTheJob:assert error is Noneassert RECORDED_VERIFICATION == [("92e639af907f", [])]- def test_recorder_skips_the_write_when_nothing_changed(self):- with patch("cron.jobs.update_job") as update_job:- sched_delivery._record_delivery_verification({"id": "j1", "last_delivery_unverified": None}, [])- update_job.assert_not_called()- sched_delivery._record_delivery_verification({"id": "j1", "last_delivery_unverified": None}, ["slack:C1"])- update_job.assert_called_once_with("j1", {"last_delivery_unverified": ["slack:C1"]})def test_recorder_clears_a_stale_marker(self):with patch("cron.jobs.update_job") as update_job:sched_delivery._record_delivery_verification({"id": "j1", "last_delivery_unverified": ["slack:C1"]}, [])update_job.assert_called_once_with("j1", {"last_delivery_unverified": None})- def test_tool_listing_exposes_the_field(self):- from tools.cronjob_tools import _format_job-- assert _format_job({"id": "j1", "name": "n", "prompt": "p",- "last_delivery_unverified": ["slack:C1"]})["last_delivery_unverified"] == ["slack:C1"]-def test_scheduler_module_exposes_the_confirmation_helper():- """Guard the import surface the delivery block depends on."""- assert callable(sched_delivery._confirm_adapter_delivery)class TestStandaloneSendIsBounded:diff --git a/tests/cron/test_cron_mcp_toolset_empty_block.py b/tests/cron/test_cron_mcp_toolset_empty_block.pyindex 3352868b387..f0f2cb2f6d1 100644--- a/tests/cron/test_cron_mcp_toolset_empty_block.py+++ b/tests/cron/test_cron_mcp_toolset_empty_block.py@@ -75,9 +75,6 @@ def test_requested_mcp_server_owned_by_other_profile_blocks_run(tmp_path):assert agent_built is Falseassert success is Falseassert error is not None and "[blocked_config]" in error and "notion" in error- # The reason is operator-facing copy: it must say the block re-evaluates itself so a- # transient outage is not mistaken for a config error to repair by hand (#112871).- assert "clears by itself" in errordef test_requested_mcp_server_with_tools_runs(tmp_path):@@ -152,32 +149,3 @@ def test_requested_mcp_server_parked_on_permanent_error_blocks(tmp_path):assert error is not None and "[blocked_config]" in error and "notion" in error-def test_reconnecting_warning_is_once_per_job_and_server_per_outage(tmp_path, caplog):- """The reconnecting exemption warns once per job+server while the outage lasts (not every- tick) and warns again once the server recovered and dropped out a second time."""- import logging-- import cron.scheduler_preflight as preflight-- preflight._RECONNECTING_WARNED.clear()- job = _job(enabled_toolsets=["terminal", "notion"])- undo = _park_notion(ever_connected=True)- try:- with caplog.at_level(logging.WARNING, logger="cron.scheduler_preflight"):- _run(job, tmp_path)- _run(job, tmp_path)- warned = [r for r in caplog.records if "are reconnecting" in r.getMessage()]- assert len(warned) == 1- # Server back: the dedupe entry drops, so the next outage warns again.- _register = _register_notion_in_scope(None)- try:- _run(job, tmp_path)- finally:- _register()- assert ("mcpjob", "notion") not in preflight._RECONNECTING_WARNED- _run(job, tmp_path)- warned = [r for r in caplog.records if "are reconnecting" in r.getMessage()]- assert len(warned) == 2- finally:- undo()- preflight._RECONNECTING_WARNED.clear()diff --git a/tests/cron/test_cron_memory_contract.py b/tests/cron/test_cron_memory_contract.pyindex 1e67e107388..5cee126ba3e 100644--- a/tests/cron/test_cron_memory_contract.py+++ b/tests/cron/test_cron_memory_contract.py@@ -85,17 +85,6 @@ def _run_job_patches(tmp_path):yield fake_db, entered[-1]-class TestCronMemoryContractOn:- """Direction (a): default cron agents GET persistent memory (#91447)."""-- def test_resolver_denylist_has_no_memory_entry(self):- """_resolve_cron_disabled_toolsets({}) itself never emits 'memory'."""- from cron.scheduler import _resolve_cron_disabled_toolsets-- assert "memory" not in _resolve_cron_disabled_toolsets({})- assert "memory" not in _resolve_cron_disabled_toolsets(- {"cron": {"allow_agent_scheduling": True}}- )class TestCronMemoryContractOff:@@ -126,20 +115,3 @@ class TestCronMemoryContractOff:"the cron agent's denylist — the OFF direction of the contract")- def test_skip_memory_is_not_a_per_job_knob(self, tmp_path):- """No per-job field flips skip_memory: the scheduler always passes False.-- Guards against a partial re-flip where some job shape quietly gets- #91384 behavior back. A field named skip_memory on the job dict is- ignored by the construction site.- """- job = {- "id": "mem-contract-noknob",- "name": "t",- "prompt": "hi",- "skip_memory": True, # not a supported job field; must be ignored- }- with _run_job_patches(tmp_path) as (_db, agent_cls):- run_job(job)- kwargs = agent_cls.call_args.kwargs- assert kwargs["skip_memory"] is Falsediff --git a/tests/cron/test_cron_no_agent.py b/tests/cron/test_cron_no_agent.pyindex a72f401af7b..8046d8c429d 100644--- a/tests/cron/test_cron_no_agent.py+++ b/tests/cron/test_cron_no_agent.py@@ -11,10 +11,6 @@ Covers:from __future__ import annotations-import json-import pathlib-import subprocess-from unittest.mock import patchimport pytest@@ -74,14 +70,6 @@ def test_update_job_roundtrips_no_agent_flag(hermes_env):# ----------------------------------------------------------------------------def test_cronjob_tool_create_no_agent_without_script_errors(hermes_env):- from tools.cronjob_tools import cronjob-- result = json.loads(- cronjob(action="create", schedule="every 5m", no_agent=True, deliver="local")- )- assert result.get("success") is False- assert "no_agent=True requires a script" in result.get("error", "")# ---------------------------------------------------------------------------@@ -193,107 +181,8 @@ def test_no_agent_script_of_launch_profile_keeps_its_own_env_credential(hermes_eassert output.splitlines() == ["JOB_SVC_TOKEN=MISSING", "LAUNCH_ONLY_TOKEN=set"]-def test_timed_out_no_agent_script_delivery_is_not_mislabeled_as_provider_failure(- hermes_env, monkeypatch,-):- """A watchdog timeout happens before any LLM/provider call.-- The delivery summary must preserve that process-level failure taxonomy and- must not claim a provider fallback was attempted or exhausted.- """- from cron.jobs import create_job- import cron.scheduler as scheduler- from cron import scheduler_script as sched_script-- (hermes_env / "scripts" / "slow.py").write_text("import time; time.sleep(999)\n")- job = create_job(- prompt=None,- schedule="every 5m",- script="slow.py",- no_agent=True,- deliver="telegram",- name="slow watchdog",- )- delivered = []-- # The script runner uses Popen + a polling loop (cancel/timeout aware),- # so simulate a process that never finishes: communicate() always times- # out and the script deadline is shrunk to keep the test fast.- class _NeverFinishes:- returncode = None- pid = 0- stdout = None- stderr = None-- def __init__(self, *_args, **_kwargs):- pass-- def poll(self):- return None-- def communicate(self, timeout=None):- raise subprocess.TimeoutExpired(cmd="slow.py", timeout=timeout)-- def wait(self, timeout=None):- raise subprocess.TimeoutExpired(cmd="slow.py", timeout=timeout)-- def kill(self):- self.returncode = -9-- monkeypatch.setattr(scheduler.subprocess, "Popen", _NeverFinishes)- monkeypatch.setattr(sched_script, "_get_script_timeout", lambda: 1)- monkeypatch.setattr(sched_script, "_terminate_cron_script_process",- lambda proc: setattr(proc, "returncode", -15),- )- monkeypatch.setattr(- scheduler,- "_deliver_result",- lambda _job, content, **_kwargs: delivered.append(content),- )-- assert scheduler.run_one_job(job) is True- assert len(delivered) == 1- assert "script timed out" in delivered[0].lower()- assert "provider" not in delivered[0].lower()- assert "fallback" not in delivered[0].lower()--def test_agent_provider_timeout_delivery_keeps_fallback_guidance(hermes_env, monkeypatch):- """Provider timeout classification remains available to agent-backed jobs."""- from cron.jobs import create_job- import cron.scheduler as scheduler- from cron import scheduler_script as sched_script-- job = create_job(- prompt="Summarize the overnight logs.",- schedule="every 5m",- deliver="telegram",- name="provider-backed report",- )- delivered = []-- monkeypatch.setattr(- scheduler,- "run_job",- lambda *_args, **_kwargs: (- False,- "# Cron Job: provider-backed report\n\nprovider request timed out\n",- "",- "ReadTimeout: provider request timed out after fallback attempts",- ),- )- monkeypatch.setattr(- scheduler,- "_deliver_result",- lambda _job, content, **_kwargs: delivered.append(content),- )- assert scheduler.run_one_job(job) is True- assert len(delivered) == 1- assert "did not respond in time" in delivered[0].lower()- # Chain wording is honest (#85508): "no backup provider succeeded" when configured,- # "no backup provider is configured" guidance otherwise.- assert "backup provider" in delivered[0].lower()# ---------------------------------------------------------------------------@@ -301,14 +190,6 @@ def test_agent_provider_timeout_delivery_keeps_fallback_guidance(hermes_env, mon# ----------------------------------------------------------------------------def test_run_job_script_path_traversal_still_blocked(hermes_env):- """Security regression: shell-script support must NOT loosen containment."""- from cron.scheduler_script import _run_job_script-- # Absolute path outside the scripts dir should be rejected.- ok, output = _run_job_script("/etc/passwd")- assert ok is False- assert "Blocked" in output or "outside" in outputdef test_run_job_script_nul_path_fails_cleanly(hermes_env):@@ -331,43 +212,8 @@ def test_run_job_script_nul_path_fails_cleanly(hermes_env):assert "NUL byte" in output-def test_run_job_script_nul_rejected_before_any_path_call(hermes_env, monkeypatch):- """The eager NUL check must run before ``Path(...)`` is ever constructed.-- On Windows ``expanduser()`` never expands ``~user`` and never raises,- so without the pre-check the NUL surfaces later from ``resolve()`` /- ``exists()`` — outside the guard's try — and the uncaught ValueError- crashes the scheduler (#86829). Stubbing ``Path`` with a hard failure- proves the rejection happens before any pathlib call on every- platform, not just the ones where expanduser happens to raise."""- import cron.scheduler as scheduler_module- from cron import scheduler_script as sched_script- def boom(*_args, **_kwargs):- raise AssertionError("Path must not be touched for a NUL-bearing script path")- monkeypatch.setattr(scheduler_module, "Path", boom)- ok, output = sched_script._run_job_script("nul\x00byte.sh")- assert ok is False- assert "NUL byte" in output---def test_run_job_script_accepts_pathlike_script_path(hermes_env):- """The eager NUL guard must not crash on a non-str script_path.-- ``"\x00" in script_path`` raises TypeError for a pathlib.Path (not- iterable), so a Path passed by a future caller would crash the- scheduler at the guard itself. The guard coerces with str() first;- a valid Path must still run the script end-to-end (regression for- the #86832 review point)."""- from cron.scheduler_script import _run_job_script-- script = hermes_env / "scripts" / "probe.py"- script.write_text('print("pathlike ok")\n', encoding="utf-8")-- ok, output = _run_job_script(pathlib.Path(script))- assert ok is True- assert "pathlike ok" in output# ---------------------------------------------------------------------------diff --git a/tests/cron/test_cron_non_push_origin.py b/tests/cron/test_cron_non_push_origin.pyindex edd0954630d..7d481e21e85 100644--- a/tests/cron/test_cron_non_push_origin.py+++ b/tests/cron/test_cron_non_push_origin.py@@ -21,7 +21,7 @@ def test_non_push_session_stamps_no_origin_and_gets_creation_notice():finally:clear_session_vars(tokens)assert origin is None- assert notice and "NOT be delivered" in notice+ assert notice# Control: a push-capable platform keeps its origin.tokens = set_session_vars(platform="telegram", chat_id="777", session_key="tg", async_delivery=True)@@ -56,7 +56,7 @@ def test_non_push_session_creation_notice_names_home_channel_fallback(monkeypatcnotice = _local_delivery_notice({"id": "j", "deliver": "origin", "origin": _origin_from_env()}, None)finally:clear_session_vars(tokens)- assert notice and "telegram:12345" in notice and "instead of back here" in notice+ assert notice and "telegram:12345" in noticetokens = set_session_vars(platform="telegram", chat_id="777", session_key="tg", async_delivery=True)try:diff --git a/tests/cron/test_cron_provider_pin.py b/tests/cron/test_cron_provider_pin.pyindex dcab5bfb46f..63b1544ce25 100644--- a/tests/cron/test_cron_provider_pin.py+++ b/tests/cron/test_cron_provider_pin.py@@ -119,8 +119,7 @@ class TestUnpinnedJobsFollowTheMainModel:assert success is Falseassert agent_kwargs is None- assert "hermes cron edit pin-test --model <name>" in error- assert "cronjob action=update" not in error+ assert errorclass TestPinnedLocksTheMainModel:diff --git a/tests/cron/test_cron_reasoning_effort.py b/tests/cron/test_cron_reasoning_effort.pyindex bf0431f30d6..d979b3aa8d2 100644--- a/tests/cron/test_cron_reasoning_effort.py+++ b/tests/cron/test_cron_reasoning_effort.py@@ -39,19 +39,10 @@ def _create(**kw):class TestJobStoreReasoningEffort:- def test_absent_field_stores_none_and_shape_unchanged(self, tmp_cron_dir):- """No reasoning_effort arg => None in the record; the rest of the job- dict keeps exactly the keys pre-feature jobs had (plus the new field),- so existing consumers see no shape drift."""- job = _create()- assert job.get("reasoning_effort") is None- # The new field must not perturb sibling inference axes.- assert job["model"] is None- assert job["provider"] is None@pytest.mark.parametrize("level",- ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"],+ ["none", "xhigh"],)def test_valid_levels_stored_normalized(self, tmp_cron_dir, level):job = _create(reasoning_effort=level)@@ -64,14 +55,11 @@ class TestJobStoreReasoningEffort:job = _create(reasoning_effort=raw)assert job["reasoning_effort"] == expected- @pytest.mark.parametrize("garbage", ["turbo", "11", "hgih", "medium-plus"])+ @pytest.mark.parametrize("garbage", ["turbo", "medium-plus"])def test_garbage_rejected_nothing_persisted(self, tmp_cron_dir, garbage):with pytest.raises(ValueError) as exc:_create(reasoning_effort=garbage)- # Actionable message: names the bad value and the valid grammar.- msg = str(exc.value)- assert garbage in msg- assert "minimal" in msg and "ultra" in msg+ assert garbage in str(exc.value)assert load_jobs() == []@pytest.mark.parametrize("empty", [None, ""])@@ -188,22 +176,6 @@ class TestCronjobToolReasoningEffort:return mod.registry._tools["cronjob_manage"].handler- def test_schema_does_not_expose_reasoning_effort(self):- """Policy pin: the model-facing surface must NOT offer the- reasoning_effort knob. Models never choose model config; the CLI is- the only mutation surface for this field. The cronjob() function- keeps the parameter for the CLI lane (hermes_cli/cron.py), but the- tool schema and the registry dispatch drop it — same pattern as- model/provider/base_url."""- import inspect-- import tools.cronjob_tools as mod-- assert "reasoning_effort" not in mod.CRONJOB_SCHEMA["parameters"]["properties"]- # The registry handler lambda must not forward the agent's args to- # the parameter (mirrors the intentional model/provider omission).- source = inspect.getsource(self._tool_handler())- assert 'args.get("reasoning_effort")' not in sourcedef test_tool_dispatch_drops_reasoning_effort_arg(self, tmp_cron_dir):"""Even if a model hallucinates the argument, dispatch ignores it:diff --git a/tests/cron/test_cron_relay_run_forward.py b/tests/cron/test_cron_relay_run_forward.pyindex 6925b42d5d8..5c09a1fe586 100644--- a/tests/cron/test_cron_relay_run_forward.py+++ b/tests/cron/test_cron_relay_run_forward.py@@ -19,9 +19,6 @@ class _Resp:class TestRelayFrontedDeliveryPlatforms:- def test_empty_when_nothing_fronted(self):- with patch("gateway.relay.relay_fronted_platforms", return_value=set()):- assert cronjob_tools._relay_fronted_delivery_platforms({"id": "j1"}) == set()def test_detects_fronted_delivery_platform(self):job = {"id": "j1", "deliver": "discord"}@@ -135,18 +132,6 @@ class TestForwardRelayFrontedRun:)assert sent["json"] == {"prompt": "focus on EU numbers"}- def test_empty_body_without_prompt(self):- sent = {}-- def fake_post(url, headers=None, json=None, timeout=None):- sent["json"] = json- return _Resp(200)-- with patch.object(- cronjob_tools, "_relay_fronted_delivery_platforms", return_value={"discord"}- ), patch("httpx.post", side_effect=fake_post):- cronjob_tools._forward_relay_fronted_run({"id": "j1"})- assert sent["json"] == {}class TestManualRunPromptConsumption:diff --git a/tests/cron/test_cron_request_overrides.py b/tests/cron/test_cron_request_overrides.pydeleted file mode 100644index 6cf8d34d5c1..00000000000--- a/tests/cron/test_cron_request_overrides.py+++ /dev/null@@ -1,60 +0,0 @@-"""Standalone regression test for cron runtime request_overrides forwarding.--Split out of tests/cron/test_scheduler.py as an independent, upgrade-safe file-(registered in the local-patch ledger's allowed_untracked list) so the local-request_overrides forwarding hotfix no longer collides with upstream inserting-new tests around its anchor in the large test_scheduler.py module.--The functional change under test lives in cron/scheduler.py (run_job forwards-runtime['request_overrides'] into the ephemeral AIAgent); that hunk stays in the-source patch. Only this test moved here.-"""--from unittest.mock import patch, MagicMock--from cron.scheduler import run_job---class TestRunJobRequestOverrides:- def test_run_job_forwards_runtime_request_overrides_to_agent(self, tmp_path):- # runtime_provider may resolve provider-specific request_overrides;- # cron must pass them into the ephemeral AIAgent or scheduled jobs- # regress to SDK-default request settings.- job = {- "id": "request-overrides-job",- "name": "request-overrides",- "prompt": "hello",- }- fake_db = MagicMock()- overrides = {- "extra_headers": {- "User-Agent": "codex_cli_rs/0.138.0 (Windows 10.0.26100; x86_64)"- }- }-- with patch("cron.scheduler._hermes_home", tmp_path), \- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \- patch("dotenv.load_dotenv"), \- patch("hermes_state_registry.acquire", return_value=fake_db), \- patch(- "hermes_cli.runtime_provider.resolve_runtime_provider",- return_value={- "api_key": "test-key",- "base_url": "https://example.invalid/v1",- "provider": "custom",- "api_mode": "codex_responses",- "request_overrides": overrides,- },- ), \- 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)-- assert success is True- assert error is None- assert final_response == "ok"- kwargs = mock_agent_cls.call_args.kwargs- assert kwargs["request_overrides"] == overridesdiff --git a/tests/cron/test_cron_run_stale_claim_reap.py b/tests/cron/test_cron_run_stale_claim_reap.pyindex 1e29c9c74bf..b9bdac0afa7 100644--- a/tests/cron/test_cron_run_stale_claim_reap.py+++ b/tests/cron/test_cron_run_stale_claim_reap.py@@ -9,138 +9,13 @@ no equivalent moment of its own, so the self-heal never ran for it.from __future__ import annotations-import json-import os-import subprocessimport sys-from pathlib import Path-def test_stale_claim_from_a_dead_one_shot_process_blocks_new_execution_creation(- tmp_path,-):- """Sanity/negative-control: reproduces the exact reported symptom in- isolation -- a genuinely dead-owner 'claimed' row for a job, with no- recovery step run, simply sits there. (create_execution() doesn't- itself gate on prior rows for the same job_id; the blocking happens- at a higher layer that checks for an existing claimed/running row --- this test establishes the stale row exists and stays 'claimed'- without recovery, matching the bug report's own SQL evidence.)"""- home = tmp_path / "home"- repo = Path(__file__).resolve().parents[2]- env = os.environ.copy()- env["HERMES_HOME"] = str(home)- env["PYTHONPATH"] = str(repo)- # Simulate the dispatched runner's owner process dying mid-flight,- # exactly as issue #86721 describes: a one-shot process creates the- # execution row (status='claimed') and exits before finishing it.- create = subprocess.run(- [- sys.executable, "-c",- "from cron.executions import create_execution; "- "r=create_execution('cron-run-job', source='direct'); "- "print(r['id'])",- ],- cwd=repo, env=env, text=True, capture_output=True, check=True,- )- execution_id = create.stdout.strip()- # Without recovery, the row is exactly where the bug report found it.- check = subprocess.run(- [- sys.executable, "-c",- "import json; from cron.executions import list_executions; "- "print(json.dumps(list_executions(job_id='cron-run-job')))",- ],- cwd=repo, env=env, text=True, capture_output=True, check=True,- )- records = json.loads(check.stdout.strip())- assert len(records) == 1- assert records[0]["id"] == execution_id- assert records[0]["status"] == "claimed" # stranded, matching the report-def test_recover_interrupted_executions_reaps_the_stale_claim_from_a_dead_process(- tmp_path,-):- """The self-heal this issue's fix now triggers per one-shot- invocation: recover_interrupted_executions() correctly identifies and- clears a stale claim left by a process that has genuinely exited- (real dead PID, not a mock), unblocking the job for a new run."""- home = tmp_path / "home"- repo = Path(__file__).resolve().parents[2]- env = os.environ.copy()- env["HERMES_HOME"] = str(home)- env["PYTHONPATH"] = str(repo)-- create = subprocess.run(- [- sys.executable, "-c",- "from cron.executions import create_execution; "- "r=create_execution('cron-run-job-2', source='direct'); "- "print(r['id'])",- ],- cwd=repo, env=env, text=True, capture_output=True, check=True,- )- execution_id = create.stdout.strip()-- # This is what #86721's fix now calls, from a FRESH process, mirroring- # exactly what a subsequent `hermes cron run` invocation would trigger- # before attempting its own claim.- recover = subprocess.run(- [- sys.executable, "-c",- "import json; "- "from cron.executions import recover_interrupted_executions, list_executions; "- "print(recover_interrupted_executions()); "- "print(json.dumps(list_executions(job_id='cron-run-job-2')))",- ],- cwd=repo, env=env, text=True, capture_output=True, check=True,- )- lines = recover.stdout.strip().splitlines()- assert lines[0] == "1", "exactly one stale execution must be reaped"- records = json.loads(lines[1])- assert records[0]["id"] == execution_id- assert records[0]["status"] == "unknown", (- "the stale claim from the dead owner must be reclassified, "- "no longer blocking a fresh claim attempt for this job"- )---def test_try_dispatch_background_run_calls_recovery_before_claiming(monkeypatch):- """Direct unit check on the fix's exact insertion point: the one-shot- dispatch path must call recover_interrupted_executions() before- proceeding to claim/create an execution for THIS run, so a stale row- left by a prior dead one-shot invocation is cleared first."""- import tools.cronjob_tools as cronjob_tools-- calls = []- monkeypatch.setattr(- "cron.executions.recover_interrupted_executions",- lambda: calls.append("recovered") or 0,- )- # Force the function past its own early-return guards so execution- # reaches the point where recovery is called, without needing a real- # gateway/session runtime.- monkeypatch.setattr(- "gateway.session_context.async_delivery_supported", lambda: True- )- monkeypatch.setattr(- "tools.approval_context.get_current_session_key", lambda default="": ""- )-- job = {"id": "unit-test-job", "name": "unit test job", "deliver": "local"}- # session_id is intentionally empty/None too, matching the direct-- # caller ("hermes cron run", tests) early return documented just- # below the recovery call -- this test only needs to confirm recovery- # ran before that point, not exercise the full dispatch.- cronjob_tools._try_dispatch_background_run(job, session_id=None)-- assert calls == ["recovered"], (- "recover_interrupted_executions() must be called before any claim "- "attempt in the one-shot dispatch path"- )def test_one_shot_cli_path_reaps_dead_owner_row_before_returning_sync(tmp_path, monkeypatch):diff --git a/tests/cron/test_cron_script.py b/tests/cron/test_cron_script.pyindex 7ca29fa83b3..df09189ae5a 100644--- a/tests/cron/test_cron_script.py+++ b/tests/cron/test_cron_script.py@@ -15,8 +15,6 @@ import sysimport textwrapfrom datetime import datetime, timedelta, timezonefrom pathlib import Path-from types import SimpleNamespace-from typing import castimport pytest@@ -135,8 +133,7 @@ class TestRunJobScript:success, output = _run_job_script("copied-from-other-profile.py")assert success is Falseassert "Script not found" in output- assert str(cron_env / "scripts") in output and "profile" in output- assert "hermes cron edit" in output+ assert str(cron_env / "scripts") in outputdef test_script_subprocess_env_sanitized(self, cron_env, monkeypatch):@@ -240,7 +237,6 @@ class TestRunJobScript:"""The bootstrap must process .pth files — the whole reason theoverlay mode exists is that PYTHONPATH alone cannot (editableinstalls would raise ModuleNotFoundError in cron scripts)."""- import subprocessfrom cron.scheduler_script import _windows_cron_bootstrap_argv@@ -271,7 +267,6 @@ class TestRunJobScript:"""`python script.py` puts the script's directory on sys.path, so ascript may import a sibling module. The bootstrap must preserve that(runpy.run_path alone does not add it)."""- import subprocessfrom cron.scheduler_script import _windows_cron_bootstrap_argv@@ -309,91 +304,7 @@ class TestRunJobScript:assert argv == [sys.executable, str(script)]- @pytest.mark.skipif(- sys.platform == "win32",- reason="Windows always takes the overlay/creationflags branch",- )- def test_non_windows_script_keeps_locale_encoding_with_lossy_errors(self, cron_env, monkeypatch):- """POSIX keeps the platform-default (locale) encoding — gating ``encoding=`` to win32- was deliberate (#66566: unconditional UTF-8 leaked into POSIX) — but decoding must be- lossy: ``errors='replace'`` so a stray non-UTF-8 byte in script output cannot raise- UnicodeDecodeError in communicate() and fail the whole run (#105582). Supersedes- ``test_non_windows_script_preserves_default_text_decoding``, which pinned strict- decoding as a side effect of the win32 encoding gate."""- # No platform patching: the Linux CI host already takes this branch.- from cron import scheduler as sched_mod- from cron import scheduler_script as sched_script- from cron.scheduler_script import _run_job_script-- script = cron_env / "scripts" / "probe.py"- script.write_text('print("ok")\n')-- captured = {}-- class FakeProc:- def __init__(self, argv, **kwargs):- captured["argv"] = argv- captured["kwargs"] = kwargs- self.returncode = 0-- def poll(self):- return self.returncode-- def communicate(self, timeout=None):- return ("ok\n", "")-- def wait(self, timeout=None):- return self.returncode-- fake_run = FakeProc-- monkeypatch.setattr(sched_mod.sys, "platform", "linux")- monkeypatch.setattr(sched_mod.subprocess, "Popen", fake_run)-- success, output = _run_job_script("probe.py")-- assert success is True- assert output == "ok"- assert captured["argv"] == [sys.executable, str(script.resolve())]- assert captured["kwargs"]["text"] is True- assert "creationflags" not in captured["kwargs"]- assert "encoding" not in captured["kwargs"]- assert captured["kwargs"]["errors"] == "replace"-- def test_non_overlay_branch_keeps_plain_argv(self, cron_env, monkeypatch):- """When the Windows uv-venv overlay is NOT active, the invocation must- stay a plain `python script.py` — the bootstrap is overlay-only.- Cross-platform: forces the non-overlay branch explicitly."""- from cron import scheduler as sched_mod- from cron import scheduler_script as sched_script- from cron.scheduler_script import _run_job_script-- script = cron_env / "scripts" / "probe.py"- script.write_text('print("ok")\n', encoding="utf-8")-- captured = {}-- class FakeProc:- def __init__(self, argv, **kwargs):- captured["argv"] = argv- self.returncode = 0-- def poll(self):- return self.returncode- def communicate(self, timeout=None):- return ("ok\n", "")-- monkeypatch.setattr(sched_script, "_windows_cron_python_invocation",- lambda python_exe: (python_exe, {}),- )- monkeypatch.setattr(sched_mod.subprocess, "Popen", FakeProc)-- success, output = _run_job_script("probe.py")-- assert success is True- assert output == "ok"- assert captured["argv"] == [sys.executable, str(script.resolve())]def test_emoji_stdout_round_trips_through_script_capture(self, cron_env):"""Emoji in script stdout must reach the caller intact (#42384).@@ -417,28 +328,6 @@ class TestRunJobScript:assert success is Trueassert "backup done 🎉 日次" == output- def test_invalid_utf8_stdout_does_not_raise(self, cron_env):- """Truncated/invalid UTF-8 in script stdout must never escape as an- exception (#47393) — a raised UnicodeDecodeError higher up would- silently drop the whole delivery (#42384). The run may fail, but it- must fail as a (False, message) result the scheduler can deliver.- """- from cron.scheduler_script import _run_job_script-- script = cron_env / "scripts" / "bad_bytes.py"- # b'\xe6\x97' is the first two bytes of a three-byte CJK sequence —- # a truncated write, exactly the shape reported in #47393.- script.write_text(- "import sys\n"- "sys.stdout.buffer.write(b'partial \\xe6\\x97')\n",- encoding="utf-8",- )-- success, output = _run_job_script("bad_bytes.py") # must not raise-- assert isinstance(success, bool)- assert isinstance(output, str)- assert output # a message is always produced, never a silent dropclass TestBuildJobPromptWithScript:@@ -676,76 +565,12 @@ class TestRunJobEnvVarCleanup:class TestScriptTimeoutTreeKill:"""Phase 4a (#85125): a script timeout must leave zero living descendants."""- def test_unified_tree_kill_failure_falls_back(self, monkeypatch, caplog):- from agent import deadline- from cron import scheduler as sched- from cron import scheduler_script as sched_script-- proc = SimpleNamespace(pid=12345, poll=lambda: None)- fallback_calls = []- monkeypatch.setattr(deadline, "kill_process_tree", lambda _pid: False)- monkeypatch.setattr(sched_script, "_terminate_cron_script_process",- lambda candidate: fallback_calls.append(candidate),- )-- with caplog.at_level("WARNING", logger=sched.__name__):- sched_script._terminate_cron_script_tree(cast("subprocess.Popen", proc))-- assert fallback_calls == [proc]- assert "falling back to process-group termination" in caplog.text-- def test_invalid_pid_never_reaches_unified_tree_kill(self, monkeypatch, caplog):- from agent import deadline- from cron import scheduler as sched- from cron import scheduler_script as sched_script-- proc = SimpleNamespace(pid=0, poll=lambda: None)- tree_kill_calls = []- fallback_calls = []- monkeypatch.setattr(- deadline,- "kill_process_tree",- lambda pid: tree_kill_calls.append(pid),- )- monkeypatch.setattr(sched_script, "_terminate_cron_script_process",- lambda candidate: fallback_calls.append(candidate),- )-- with caplog.at_level("WARNING", logger=sched.__name__):- sched_script._terminate_cron_script_tree(cast("subprocess.Popen", proc))- assert tree_kill_calls == []- assert fallback_calls == [proc]- assert "invalid pid 0" in caplog.text- def test_already_exited_proc_is_left_alone(self, monkeypatch):- """A script that finished right at the deadline needs no signalling —- and must not produce a spurious "no signal" warning."""- from agent import deadline- from cron import scheduler as sched- from cron import scheduler_script as sched_script-- proc = SimpleNamespace(pid=12345, poll=lambda: 0)- tree_kill_calls = []- fallback_calls = []- monkeypatch.setattr(- deadline,- "kill_process_tree",- lambda pid: tree_kill_calls.append(pid) or True,- )- monkeypatch.setattr(sched_script, "_terminate_cron_script_process",- lambda candidate: fallback_calls.append(candidate),- )-- sched_script._terminate_cron_script_tree(cast("subprocess.Popen", proc))-- assert tree_kill_calls == []- assert fallback_calls == []def test_cancel_path_also_tree_kills(self, monkeypatch, cron_env):"""The ownership-lost/cancel kill site is the timeout site's sibling:it must go through the same tree-kill (#71148 class)."""- from cron import scheduler as schedfrom cron import scheduler_script as sched_scripttree_calls = []diff --git a/tests/cron/test_cron_tick_stale_yield.py b/tests/cron/test_cron_tick_stale_yield.pyindex ff523b51b1a..edfcc0038b9 100644--- a/tests/cron/test_cron_tick_stale_yield.py+++ b/tests/cron/test_cron_tick_stale_yield.py@@ -19,7 +19,6 @@ ticks must surface as failed ticks (``record_ticker_error`` + heartbeatfrom __future__ import annotations-import loggingimport threadingimport timefrom unittest.mock import patch@@ -149,25 +148,6 @@ class TestTickYieldGate:monkeypatch.setattr(gateway_status, "is_gateway_runtime_lock_active", _boom)assert scheduler_mod.tick(verbose=False) == 0- def test_yield_logs_once_per_episode(self, monkeypatch, caplog):- """The yield log is throttled: repeated yields with the same skew- signature log once, not once per tick interval."""- _gate_mocks(monkeypatch, owns=False, active=True)- with caplog.at_level(logging.ERROR, logger="cron.scheduler"):- scheduler_mod._log_tick_yield_once("boot=a disk=b")- scheduler_mod._log_tick_yield_once("boot=a disk=b")- scheduler_mod._log_tick_yield_once("boot=a disk=b")- yield_logs = [- r for r in caplog.records if "Cron tick yielded" in r.getMessage()- ]- assert len(yield_logs) == 1- # A NEW skew signature (the checkout moved again) is a new episode.- with caplog.at_level(logging.ERROR, logger="cron.scheduler"):- scheduler_mod._log_tick_yield_once("boot=a disk=c")- yield_logs = [- r for r in caplog.records if "Cron tick yielded" in r.getMessage()- ]- assert len(yield_logs) == 2class TestYieldedTickIsAFailedTick:diff --git a/tests/cron/test_cron_workdir.py b/tests/cron/test_cron_workdir.pyindex dd8505966d4..d17c16e3d4d 100644--- a/tests/cron/test_cron_workdir.py+++ b/tests/cron/test_cron_workdir.py@@ -12,7 +12,6 @@ Covers:from __future__ import annotations-import jsonimport pytest@@ -31,9 +30,6 @@ def tmp_cron_dir(tmp_path, monkeypatch):# ---------------------------------------------------------------------------class TestNormalizeWorkdir:- def test_none_returns_none(self):- from cron.jobs import _normalize_workdir- assert _normalize_workdir(None) is Nonedef test_empty_string_returns_none(self):from cron.jobs import _normalize_workdir@@ -123,14 +119,6 @@ class TestUpdateJobWorkdir:# tools.cronjob_tools: end-to-end JSON round-trip# ----------------------------------------------------------------------------class TestCronjobToolWorkdir:--- def test_schema_advertises_workdir(self):- from tools.cronjob_tools import CRONJOB_SCHEMA- assert "workdir" in CRONJOB_SCHEMA["parameters"]["properties"]- desc = CRONJOB_SCHEMA["parameters"]["properties"]["workdir"]["description"]- assert "absolute" in desc.lower()# ---------------------------------------------------------------------------@@ -142,7 +130,6 @@ class TestTickWorkdirPartition:def test_workdir_jobs_overlap_on_parallel_pool(self, tmp_path, monkeypatch):import cron.scheduler as sched- from cron import scheduler_delivery as sched_deliveryimport threadingworkdir_a = tmp_path / "a"@@ -258,7 +245,6 @@ class TestRunJobTerminalCwd:"""import osimport cron.scheduler as sched- from cron import scheduler_delivery as sched_delivery# Pin TERMINAL_CWD to a sentinel via monkeypatch so we control both# the before-value and the after-value regardless of cross-test state.@@ -293,7 +279,6 @@ class TestRunJobTerminalCwd:):import osimport cron.scheduler as sched- from cron import scheduler_delivery as sched_deliveryfrom tools.terminal_tool import get_session_cwdbaseline = str(tmp_path / "baseline")diff --git a/tests/cron/test_cronjob_gateway_liveness.py b/tests/cron/test_cronjob_gateway_liveness.pyindex 3156c3ae822..da4fa98bf43 100644--- a/tests/cron/test_cronjob_gateway_liveness.py+++ b/tests/cron/test_cronjob_gateway_liveness.py@@ -76,12 +76,7 @@ class TestCreateSurfacesGatewayLiveness:"the job itself is still created successfully")assert result["gateway_running"] is False- warning = result.get("warning", "")- assert "not running" in warning.lower()- assert "will NOT fire" in warning, (- "the model must be told the job won't fire (#87033)"- )- assert "gateway" in warning.lower()+ assert result.get("warning"), "the model must be told the job won't fire (#87033)"def test_non_builtin_provider_is_exempt(self, hermes_env):"""External schedulers (e.g. Chronos) fire without the gateway —@@ -130,11 +125,7 @@ class TestListSurfacesGatewayLiveness:assert result["success"] is Trueassert result["gateway_running"] is False- warning = result.get("warning", "")- assert "will NOT fire" in warning, (- "the model must be told the listed jobs won't fire (#87033)"- )- assert "these jobs" in warning+ assert result.get("warning"), "the model must be told the listed jobs won't fire (#87033)"def test_list_empty_without_gateway_stays_quiet(self, hermes_env):"""Nothing scheduled + no gateway → no alarm; there is nothing inert."""@@ -325,48 +316,3 @@ class TestRuntimeLockFirstLiveness:assert cron_cli._builtin_gateway_liveness() is False-class TestCronStatusLockFirst:- """`hermes cron status` shares the lock-first false-alarm fix (#95947).-- Sibling site of `_builtin_gateway_liveness`: it previously declared- "No gateway is running on this host — cron jobs will NOT fire" from a bare- `find_gateway_pids()` miss even while the runtime lock proved the- gateway (and its ticker) alive.- """-- def _run_status(self, *, pids, lock_active, lock_pid=None):- from unittest.mock import patch- import io- from contextlib import redirect_stdout-- import hermes_cli.cron as cron_cli-- out = io.StringIO()- with (- patch("hermes_cli.cron._active_cron_provider_name", return_value="builtin"),- patch("hermes_cli.gateway.find_gateway_pids", return_value=list(pids)),- patch(- "gateway.status.is_gateway_runtime_lock_active",- return_value=lock_active,- ),- patch("gateway.status.get_running_pid", return_value=lock_pid),- redirect_stdout(out),- ):- cron_cli.cron_status()- return out.getvalue()-- def test_lock_active_suppresses_not_running_false_alarm(self, hermes_env):- text = self._run_status(pids=[], lock_active=True, lock_pid=4242)- # The lock-first contract (#87033): an active runtime lock means the- # gateway process is alive, so the RED "No gateway is running" alarm- # must never fire. Since #98790 a never-written heartbeat is no longer- # silently green — the YELLOW first-heartbeat notice (which also says- # "NOT fire") is expected here, so assert on the red alarm itself- # rather than the "NOT fire" substring both messages share.- assert "No gateway is running on this host" not in text- assert "has not reported a heartbeat" in text- assert "Gateway is running" in text or "running" in text-- def test_no_lock_no_pids_still_warns(self, hermes_env):- text = self._run_status(pids=[], lock_active=False)- assert "NOT fire" in textdiff --git a/tests/cron/test_cronjob_schema.py b/tests/cron/test_cronjob_schema.pydeleted file mode 100644index e61db74b76c..00000000000--- a/tests/cron/test_cronjob_schema.py+++ /dev/null@@ -1,21 +0,0 @@-"""Tests for the cronjob tool schema shape.--Guards the description text that flags ``schedule`` (and ``prompt``) as-REQUIRED for ``action=create`` — the load-bearing fix for description-driven-models (e.g. Grok) that omit schedule when the schema only lists ``action``-in ``required[]``. See issue #32427 / PR #32448.-"""--from __future__ import annotations---def test_cronjob_schema_action_description_flags_create_requirements():- """`action` description must state schedule + prompt are required for create."""- from tools.cronjob_tools import CRONJOB_SCHEMA-- action_desc = CRONJOB_SCHEMA["parameters"]["properties"]["action"]["description"]- assert "action=create" in action_desc- assert "schedule" in action_desc- assert "REQUIRED" in action_desc--diff --git a/tests/cron/test_estop.py b/tests/cron/test_estop.pyindex 392e6fc869c..c489a1254c4 100644--- a/tests/cron/test_estop.py+++ b/tests/cron/test_estop.py@@ -14,7 +14,6 @@ from __future__ import annotationsimport argparseimport json-import loggingimport pytest@@ -59,8 +58,6 @@ def test_reason_and_timestamp_stored(hermes_home):assert raw["reason"] == "runaway cron fan-out"-def test_get_state_none_when_disengaged(hermes_home):- assert estop.get_state() is Nonedef test_corrupt_sentinel_still_engages(hermes_home):@@ -75,8 +72,6 @@ def test_corrupt_sentinel_still_engages(hermes_home):# ── paused notice for new gateway turns ─────────────────────────────────────-def test_paused_reply_none_when_disengaged(hermes_home):- assert estop.paused_reply() is Nonedef test_paused_reply_surfaces_reason_and_resume_hint(hermes_home):@@ -85,40 +80,13 @@ def test_paused_reply_surfaces_reason_and_resume_hint(hermes_home):assert notice is not Noneassert "paused" in notice.lower()assert "deploy window" in notice- assert "hermes resume" in notice-def test_paused_reply_without_reason(hermes_home):- estop.engage()- notice = estop.paused_reply()- assert notice is not None- assert "paused" in notice.lower()- assert "hermes resume" in notice# ── check_paused: cheap gate + log-once ─────────────────────────────────────-def test_check_paused_logs_once_per_engagement(hermes_home, caplog):- logger = logging.getLogger("test.estop.component")- estop.engage()- with caplog.at_level(logging.INFO, logger=logger.name):- assert estop.check_paused("cron", logger) is True- assert estop.check_paused("cron", logger) is True- assert estop.check_paused("cron", logger) is True- paused_logs = [r for r in caplog.records if "paused" in r.getMessage().lower()]- assert len(paused_logs) == 1-- # Resume then re-engage → logs once more (transition-based, not forever).- caplog.clear()- estop.disengage()- with caplog.at_level(logging.INFO, logger=logger.name):- assert estop.check_paused("cron", logger) is False- estop.engage()- assert estop.check_paused("cron", logger) is True- assert estop.check_paused("cron", logger) is True- paused_logs = [r for r in caplog.records if "paused" in r.getMessage().lower()]- assert len(paused_logs) == 1# ── cron scheduler integration ──────────────────────────────────────────────@@ -256,19 +224,8 @@ def test_cli_resume_disengages(hermes_home, capsys):assert "resumed" in capsys.readouterr().out.lower()-def test_cli_resume_when_not_paused(hermes_home, capsys):- from hermes_cli.subcommands.pause import cmd_resume-- rc = cmd_resume(argparse.Namespace())- assert rc == 0- assert "not paused" in capsys.readouterr().out.lower()--def test_builtin_subcommands_include_pause_resume():- from hermes_cli.main import _BUILTIN_SUBCOMMANDS- assert "pause" in _BUILTIN_SUBCOMMANDS- assert "resume" in _BUILTIN_SUBCOMMANDS# ── hermes status surfacing ─────────────────────────────────────────────────diff --git a/tests/cron/test_execution_ledger.py b/tests/cron/test_execution_ledger.pyindex d68259ae4b4..b55857b2e68 100644--- a/tests/cron/test_execution_ledger.py+++ b/tests/cron/test_execution_ledger.py@@ -455,9 +455,8 @@ def test_ledger_operations_close_every_connection(monkeypatch, tmp_path):executions.latest_executions(["leak-check"])executions.recover_interrupted_executions()- assert len(opened) == 6- assert len(closed) == 6- assert set(opened) == set(closed)+ assert opened+ assert sorted(opened) == sorted(closed)def test_early_return_still_closes_connection(monkeypatch, tmp_path):@@ -472,49 +471,8 @@ def test_early_return_still_closes_connection(monkeypatch, tmp_path):assert len(closed) == 1-def test_exception_during_operation_still_closes_connection(monkeypatch, tmp_path):- """A failing statement inside the transaction must roll back and close,- not leak the connection."""- executions = _point_ledger(monkeypatch, tmp_path)- opened, closed = _count_open_connections(executions, monkeypatch)-- with __import__("pytest").raises(sqlite3.IntegrityError):- with executions._transaction() as conn:- conn.execute(- "INSERT INTO executions (id, job_id, source, process_id, pid, "- "status, claimed_at) VALUES ('x', 'x', 'x', 'x', 1, 'bogus-status', 'now')"- )-- assert len(opened) == 1- assert len(closed) == 1---def test_schema_init_failure_still_closes_connection(monkeypatch, tmp_path):- """If PRAGMA/DDL setup in _connect() fails after sqlite3.connect()- succeeds, the partially-initialized connection must still be closed."""- executions = _point_ledger(monkeypatch, tmp_path)- opened_ids = []- closed_ids = []- real_connect = sqlite3.connect-- class _FailingSchemaConnection(_TrackingConnection):- def execute(self, sql, *args, **kwargs):- if "CREATE TABLE" in sql:- raise sqlite3.OperationalError("simulated schema init failure")- return self._real.execute(sql, *args, **kwargs)-- def tracking_connect(*args, **kwargs):- conn = real_connect(*args, **kwargs)- opened_ids.append(id(conn))- return _FailingSchemaConnection(conn, closed_ids)-- monkeypatch.setattr(executions.sqlite3, "connect", tracking_connect)- with __import__("pytest").raises(sqlite3.OperationalError):- executions.create_execution("init-fail", source="builtin")- assert len(opened_ids) == 1- assert len(closed_ids) == 1def test_job_listing_exposes_latest_execution(monkeypatch, tmp_path):diff --git a/tests/cron/test_fire_forward_failure_stamp.py b/tests/cron/test_fire_forward_failure_stamp.pyindex 7743959b81f..73c44d368fd 100644--- a/tests/cron/test_fire_forward_failure_stamp.py+++ b/tests/cron/test_fire_forward_failure_stamp.py@@ -51,11 +51,6 @@ class TestNoteFireForwardFailure:err = get_job(job["id"])["last_fire_error"]assert err["detail"] == "second miss"- def test_detail_truncated_to_500(self, tmp_cron_dir):- job = create_job(prompt="Daily invoice triage", schedule="every 1h")- note_fire_forward_failure(job["id"], "x" * 2000)- err = get_job(job["id"])["last_fire_error"]- assert len(err["detail"]) == 500def test_successful_run_clears_stamp(self, tmp_cron_dir):"""The stamp describes CURRENT auto-fire health — a run that made itdiff --git a/tests/cron/test_idle_tick_config_skip.py b/tests/cron/test_idle_tick_config_skip.pyindex 292de0020f2..34f0f98cc13 100644--- a/tests/cron/test_idle_tick_config_skip.py+++ b/tests/cron/test_idle_tick_config_skip.py@@ -38,18 +38,7 @@ def _run_idle_tick(**kwargs):class TestIdleTickSkipsConfigLoad:- def test_idle_nonverbose_tick_skips_load_config(self):- """Gateway-style tick(verbose=False) with no due jobs: no config load."""- rc, calls = _run_idle_tick(verbose=False)- assert rc == 0- assert calls["load_config"] == 0, (- "idle tick must not load config (was loading every 60s in the gateway ticker)"- )- def test_idle_verbose_tick_skips_load_config(self):- rc, calls = _run_idle_tick(verbose=True)- assert rc == 0- assert calls["load_config"] == 0def test_idle_tick_still_sweeps_mcp_orphans(self):"""The idle-tick orphan sweep is intentional on main — must survive."""diff --git a/tests/cron/test_inflight_stale_guard.py b/tests/cron/test_inflight_stale_guard.pyindex 3085fb388d8..c83c275e81e 100644--- a/tests/cron/test_inflight_stale_guard.py+++ b/tests/cron/test_inflight_stale_guard.py@@ -315,17 +315,6 @@ class TestStaleInflightSweep:with patch.object(sched, "mark_job_run"):assert sched.sweep_stale_inflight([job]) == [job["id"]]- def test_forced_release_logs_a_warning(self, tmp_path, caplog):- job = _job()- sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))- sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 5 * 60 * 60-- with caplog.at_level("WARNING"), \- patch.object(sched, "mark_job_run"), \- patch.object(sched, "_get_hermes_home", return_value=tmp_path):- sched.sweep_stale_inflight([job])-- assert any("cron.inflight.forced_release" in r.message for r in caplog.records)class TestWedgedJobRefiresWithoutRestart:diff --git a/tests/cron/test_jobs.py b/tests/cron/test_jobs.pyindex ee4303e1c67..34818dae700 100644--- a/tests/cron/test_jobs.py+++ b/tests/cron/test_jobs.py@@ -1141,10 +1141,6 @@ class TestGetDueJobs:}-class TestEnabledToolsets:- def test_enabled_toolsets_stored(self, tmp_cron_dir):- job = create_job(prompt="monitor", schedule="every 1h", enabled_toolsets=["web", "terminal"])- assert job["enabled_toolsets"] == ["web", "terminal"]class TestMarkJobRunConcurrency:@@ -1520,48 +1516,6 @@ class TestLateEnvRepointScopesStore:# UTF-8 BOM on jobs.json (Windows Notepad / PowerShell 5.1)# =========================================================================-class TestJobsJsonShapes:- def test_load_jobs_normalizes_id_keyed_jobs_mapping(self, tmp_cron_dir):- import json- from cron.jobs import JOBS_FILE-- job_a = {- "id": "cron1234abcd",- "name": "daily briefing",- "enabled": True,- "prompt": "Summarize overnight incidents",- "schedule": {"kind": "interval", "minutes": 1440, "display": "every 24h"},- }- job_b = {- "id": "cron5678efgh",- "name": "disabled cleanup",- "enabled": False,- "prompt": "Clean stale scratch files",- "schedule": {"kind": "once", "run_at": "2030-01-15T14:00:00+00:00"},- }- payload = {- "jobs": {- job_a["id"]: job_a,- job_b["id"]: job_b,- },- "updated_at": "2026-08-23T00:00:00+00:00",- }- JOBS_FILE.parent.mkdir(parents=True, exist_ok=True)- JOBS_FILE.write_text(json.dumps(payload), encoding="utf-8")-- loaded = load_jobs()- assert isinstance(loaded, list)- assert {job["id"] for job in loaded} == {job_a["id"], job_b["id"]}-- listed = {job["id"]: job for job in list_jobs(include_disabled=True)}- assert set(listed) == {job_a["id"], job_b["id"]}- for expected in (job_a, job_b):- actual = listed[expected["id"]]- assert actual["id"] == expected["id"]- assert actual["name"] == expected["name"]- assert actual["prompt"] == expected["prompt"]- assert actual["schedule"] == expected["schedule"]- assert actual["enabled"] is expected["enabled"]class TestJobsJsonUtf8Bom:@@ -1574,7 +1528,6 @@ class TestJobsJsonUtf8Bom:def test_load_jobs_accepts_utf8_bom(self, tmp_cron_dir):"""BOM'd jobs.json loads — the pre-fix crash repro."""import json- from pathlib import Pathfrom cron.jobs import JOBS_FILE, load_jobspayload = {@@ -1597,27 +1550,6 @@ class TestJobsJsonUtf8Bom:assert [j["id"] for j in loaded] == ["bomjob01"]assert loaded[0]["name"] == "bom-test"- def test_load_jobs_bomless_regression(self, tmp_cron_dir):- """BOM-less UTF-8 jobs.json must keep loading after utf-8-sig."""- import json- from cron.jobs import JOBS_FILE, load_jobs-- payload = {- "jobs": [- {- "id": "plainjob01",- "name": "plain",- "enabled": True,- "prompt": "hi",- "schedule": {"kind": "interval", "minutes": 30, "display": "every 30m"},- }- ]- }- JOBS_FILE.parent.mkdir(parents=True, exist_ok=True)- JOBS_FILE.write_text(json.dumps(payload), encoding="utf-8")-- loaded = load_jobs()- assert [j["id"] for j in loaded] == ["plainjob01"]@@ -1786,17 +1718,6 @@ class TestJobsJsonIdKeyedMap:assert isinstance(on_disk["jobs"], list)assert [j["id"] for j in on_disk["jobs"]] == ["goodjob1"]- def test_all_junk_map_values_yield_empty_list(self, tmp_cron_dir):- """A map of only junk values flattens to [] without crashing."""- import json- from cron.jobs import JOBS_FILE, load_jobs-- JOBS_FILE.parent.mkdir(parents=True, exist_ok=True)- JOBS_FILE.write_text(- json.dumps({"jobs": {"a": "junk", "b": 1}}), encoding="utf-8"- )-- assert load_jobs() == []@@ -1836,39 +1757,8 @@ class TestAdvanceNextRuns:# one-shots keep their (past) next_run_at for restart retryassert datetime.fromisoformat(get_job(jid)["next_run_at"]) < datetime.now()- def test_batch_single_load_and_save(self, tmp_cron_dir, monkeypatch):- """I/O pin: the whole due set costs one load + one save, not N+N.- Fails pre-fix (function absent) and would fail on any regression- back to per-job I/O."""- from cron.jobs import advance_next_runs- rec_ids, _ = self._make_due(tmp_cron_dir, n_recurring=10, n_oneshot=0)- import cron.jobs as cj- counts = {"load": 0, "save": 0}- real_load, real_save = cj.load_jobs, cj.save_jobs- monkeypatch.setattr(cj, "load_jobs", lambda *a, **k: (- counts.__setitem__("load", counts["load"] + 1), real_load(*a, **k))[1])- monkeypatch.setattr(cj, "save_jobs", lambda *a, **k: (- counts.__setitem__("save", counts["save"] + 1), real_save(*a, **k))[1])- advance_next_runs(rec_ids)- assert counts == {"load": 1, "save": 1}-- def test_batch_no_save_when_nothing_advances(self, tmp_cron_dir, monkeypatch):- from cron.jobs import advance_next_runs- rec_ids, one_ids = self._make_due(tmp_cron_dir, n_recurring=0, n_oneshot=2)- import cron.jobs as cj- saves = [0]- real_save = cj.save_jobs- monkeypatch.setattr(cj, "save_jobs", lambda *a, **k: (- saves.__setitem__(0, saves[0] + 1), real_save(*a, **k))[1])- assert advance_next_runs(one_ids + ["missing-id"]) == 0- assert saves[0] == 0-- def test_wrapper_semantics_unchanged(self, tmp_cron_dir):- """advance_next_run keeps its per-job contract over the batch."""- rec_ids, one_ids = self._make_due(tmp_cron_dir)- assert advance_next_run(rec_ids[0]) is True- assert advance_next_run(one_ids[0]) is False- assert advance_next_run("missing-id") is False++# =========================================================================diff --git a/tests/cron/test_jobs_changed_notify.py b/tests/cron/test_jobs_changed_notify.pyindex 55d299f2597..1b7ebb10fab 100644--- a/tests/cron/test_jobs_changed_notify.py+++ b/tests/cron/test_jobs_changed_notify.py@@ -43,12 +43,6 @@ def test_notify_helper_calls_provider_on_jobs_changed(monkeypatch):assert calls == [1]-def test_builtin_notify_is_harmless(monkeypatch):- """With the built-in provider (default), notify is a no-op and never- raises."""- import cron.scheduler as sched- # default resolution → built-in; just assert it doesn't blow up.- sched._notify_provider_jobs_changed()def test_create_registers_first_trigger_with_active_provider(@@ -92,7 +86,6 @@ def test_create_failure_preserves_job_and_hides_provider_details(error = exc_info.valueassert jobs.get_job(error.job["id"]) == error.jobassert "private callback URL and token" not in str(error)- assert "Do not create a duplicate" in str(error)# Human-facing variant hides the exception class name and names the job.assert "RuntimeError" not in error.user_message()assert "'w'" in error.user_message()diff --git a/tests/cron/test_jobs_file_ownership.py b/tests/cron/test_jobs_file_ownership.pyindex e1dce9bee42..17ca99c25d3 100644--- a/tests/cron/test_jobs_file_ownership.py+++ b/tests/cron/test_jobs_file_ownership.py@@ -233,8 +233,5 @@ class TestCronStatusSurfacesError:cron_cli.cron_status()out = capsys.readouterr().out- assert "Last tick error:" in outassert "Permission denied" in out- # The permission-specific hint must point at the ownership fix.- assert "docker exec -u" in outdiff --git a/tests/cron/test_jobs_shrink_merge.py b/tests/cron/test_jobs_shrink_merge.pyindex 423c3fe93d3..890ef17db89 100644--- a/tests/cron/test_jobs_shrink_merge.py+++ b/tests/cron/test_jobs_shrink_merge.py@@ -9,7 +9,6 @@ unexpected on-disk ids back unless the caller passes ``removed_ids``.from __future__ import annotationsimport json-from pathlib import Pathimport pytest@@ -59,7 +58,7 @@ def test_stale_empty_save_preserves_concurrent_no_agent_create(hermes_env):def test_remove_other_job_preserves_concurrent_create(hermes_env):"""``cron remove`` of job A must not drop job B created mid-flight."""- from cron.jobs import create_job, load_jobs, remove_job, save_jobs+ from cron.jobs import create_job, load_jobs, save_jobsagent = create_job(prompt="hello",@@ -120,26 +119,11 @@ def test_replace_flag_allows_wholesale_rewrite(hermes_env):assert load_jobs() == []-def test_jobs_json_on_disk_matches_merge(hermes_env):- from cron.jobs import create_job, save_jobs-- job = create_job(- prompt=None,- schedule="every 2m",- script="watch.sh",- no_agent=True,- deliver="local",- name="watchdog",- repeat=0,- )- save_jobs([])- payload = json.loads((Path(hermes_env) / "cron" / "jobs.json").read_text())- assert [j["id"] for j in payload["jobs"]] == [job["id"]]-def test_stamp_fast_path_skips_merge_when_file_unchanged(hermes_env, monkeypatch):- """Inside a critical section whose load stamp still matches, the save- must not re-read jobs.json at all (#80703's single-stat fast path)."""+def test_sibling_write_inside_section_is_merged(hermes_env):+ """A write that lands on disk after the section's load changes the stamp,+ so the save must re-merge instead of trusting its stale snapshot."""import cron.jobs as jobsfrom cron.jobs import create_job@@ -153,23 +137,6 @@ def test_stamp_fast_path_skips_merge_when_file_unchanged(hermes_env, monkeypatchrepeat=0,)- peeks = {"count": 0}- real_peek = jobs._peek_jobs_unlocked-- def _counting_peek():- peeks["count"] += 1- return real_peek()-- monkeypatch.setattr(jobs, "_peek_jobs_unlocked", _counting_peek)-- # load -> save inside ONE critical section, no sibling write in between:- # the stamp matches, so the merge (and its peek) must be skipped.- with jobs._jobs_lock():- current = jobs.load_jobs()- jobs._save_jobs_unlocked(current)- assert peeks["count"] == 0, "healthy same-section save should not re-parse"-- # A sibling write invalidates the stamp -> the merge runs again.with jobs._jobs_lock():current = jobs.load_jobs()(jobs._current_cron_store().jobs_file).write_text(@@ -177,7 +144,6 @@ def test_stamp_fast_path_skips_merge_when_file_unchanged(hermes_env, monkeypatchencoding="utf-8",)jobs._save_jobs_unlocked(current)- assert peeks["count"] > 0, "changed stamp must re-trigger the merge"ids = {j["id"] for j in jobs.load_jobs()}assert ids == {job["id"], "bbbbbbbbbbbb"}diff --git a/tests/cron/test_lifecycle_guard_budget.py b/tests/cron/test_lifecycle_guard_budget.pyindex 181461744f8..9fd6c851094 100644--- a/tests/cron/test_lifecycle_guard_budget.py+++ b/tests/cron/test_lifecycle_guard_budget.py@@ -57,13 +57,6 @@ def test_root_budget_counts_utf8_bytes(monkeypatch):assert guard("ééé") is True-def test_exhaustion_is_logged_at_warning(monkeypatch, caplog):- monkeypatch.setattr(lifecycle_guard, "_MAX_LIFECYCLE_SCAN_BYTES", 4)- monkeypatch.setattr(lifecycle_guard, "_MAX_LIFECYCLE_SCAN_LINE_BYTES", 4)-- with caplog.at_level("WARNING", logger=lifecycle_guard.logger.name):- assert guard("echo hello") is True- assert "budget exhausted" in caplog.textdef test_lifecycle_scan_root_within_budget_is_not_a_verdict(monkeypatch):@@ -130,24 +123,6 @@ def test_cumulative_text_budget_bounds_recursive_scan(monkeypatch, tmp_path):assert guard("bash a.sh;bash b.sh", cwd=cwd) is True-def test_referenced_read_is_capped_at_remaining_budget(monkeypatch, tmp_path):- """A file bigger than what the walk can still afford is never read whole:- the read helper receives the remaining budget as its cap."""- monkeypatch.setattr(lifecycle_guard, "_MAX_LIFECYCLE_SCAN_BYTES", 64)- (tmp_path / "big.sh").write_text("echo " + "x" * 200 + "\n", encoding="utf-8")-- caps: list = []- original = lifecycle_guard._read_referenced_script-- def spy(path, *, max_bytes=None):- caps.append(max_bytes)- return original(path, max_bytes=max_bytes)-- monkeypatch.setattr(lifecycle_guard, "_read_referenced_script", spy)-- root = "bash big.sh"- assert guard(root, cwd=str(tmp_path)) is True- assert caps == [64 - len(root)]def test_remote_script_sanitizer_honours_remaining_budget():diff --git a/tests/cron/test_media_delivery_parity.py b/tests/cron/test_media_delivery_parity.pyindex f863df3edee..b7b9abe16d5 100644--- a/tests/cron/test_media_delivery_parity.py+++ b/tests/cron/test_media_delivery_parity.py@@ -148,18 +148,6 @@ class TestStandaloneWarningsSurfaced:)assert err is None- def test_media_actually_reaches_sender(- self, monkeypatch, slack_platform_config, slack_job, media_file- ):- calls = _install_fake_slack_sender(- monkeypatch,- lambda call: {"success": True, "chat_id": call["chat_id"], "message_id": "1.2"},- )- _deliver_result(- slack_job, f"Report ready.\n\nMEDIA:{media_file}", adapters=None, loop=None- )- sent_media = [m for c in calls for m in c["media_files"]]- assert any(media_file in m[0] for m in sent_media)class TestLiveAdapterMediaFailuresSurfaced:@@ -224,32 +212,6 @@ class TestLiveAdapterMediaFailuresSurfaced:class TestMediaPolicyEnvBridge:"""Defect 3: media-policy config must apply outside the gateway process."""- def test_bridge_helper_exists_and_applies_config(self, monkeypatch, tmp_path):- home = tmp_path / "hermes-home"- home.mkdir()- allow_dir = tmp_path / "reports"- allow_dir.mkdir()- (home / "config.yaml").write_text(- "gateway:\n"- " strict: true\n"- f" media_delivery_allow_dirs: [{str(allow_dir)!r}]\n"- " trust_recent_files: false\n"- )- monkeypatch.setenv("HERMES_HOME", str(home))- for var in (- "HERMES_MEDIA_DELIVERY_STRICT",- "HERMES_MEDIA_ALLOW_DIRS",- "HERMES_MEDIA_TRUST_RECENT_FILES",- ):- monkeypatch.delenv(var, raising=False)-- from gateway.media_policy import apply_media_policy_env-- apply_media_policy_env()-- assert os.environ.get("HERMES_MEDIA_DELIVERY_STRICT") == "1"- assert str(allow_dir) in os.environ.get("HERMES_MEDIA_ALLOW_DIRS", "")- assert os.environ.get("HERMES_MEDIA_TRUST_RECENT_FILES") == "0"def test_standalone_filter_honors_bridged_allowlist(self, monkeypatch, tmp_path):"""End-to-end: strict-mode file inside allow_dirs passes validationdiff --git a/tests/cron/test_media_send_timeout.py b/tests/cron/test_media_send_timeout.pyindex 41db2544840..24706c594fe 100644--- a/tests/cron/test_media_send_timeout.py+++ b/tests/cron/test_media_send_timeout.py@@ -22,7 +22,7 @@ class TestMediaSendTimeoutResolution:def test_default(self, monkeypatch):monkeypatch.delenv("HERMES_CRON_MEDIA_SEND_TIMEOUT", raising=False)monkeypatch.setattr("cron.scheduler.load_config", lambda: {})- assert _get_media_send_timeout() == _DEFAULT_MEDIA_SEND_TIMEOUT == 300+ assert _get_media_send_timeout() == _DEFAULT_MEDIA_SEND_TIMEOUTdef test_env_wins(self, monkeypatch):monkeypatch.setenv("HERMES_CRON_MEDIA_SEND_TIMEOUT", "45")diff --git a/tests/cron/test_mirror_origin_fallback.py b/tests/cron/test_mirror_origin_fallback.pyindex 9e3f3dd0af9..dbeca914885 100644--- a/tests/cron/test_mirror_origin_fallback.py+++ b/tests/cron/test_mirror_origin_fallback.py@@ -181,7 +181,6 @@ class TestFallbackMirrorEndToEnd:mirror_calls = []- import cron.scheduler as scheddef fake_mirror(platform, chat_id, text, source_label="cli",thread_id=None, user_id=None, role="assistant"):@@ -235,9 +234,8 @@ class TestFallbackMirrorEndToEnd:reply_session = store.get_or_create_session(source)assert reply_session.session_id == session.session_idmessages = store.load_transcript(reply_session.session_id)- assert [(m["role"], m["content"]) for m in messages] == [- ("user", "[Cron delivery: managed]\nmorning brief")- ]+ assert [m["role"] for m in messages] == ["user"]+ assert "morning brief" in messages[0]["content"]def test_explicit_target_with_attach_mirrors(self, slack_env):job = {diff --git a/tests/cron/test_misfire_catchup.py b/tests/cron/test_misfire_catchup.pyindex 3ad5aef3ea5..a786b6075ca 100644--- a/tests/cron/test_misfire_catchup.py+++ b/tests/cron/test_misfire_catchup.py@@ -8,7 +8,6 @@ gateway housekeeping, claims and fires those jobs after a grace window."""import threading-import timefrom datetime import timedeltaimport pytest@@ -148,17 +147,22 @@ class TestFireOverdueJobs:"""fire_claimed runs off-thread — a slow job must not stall thesweep (housekeeping loop) for the length of an agent run."""- class SlowProvider(RecordingProvider):+ release = threading.Event()++ class BlockedProvider(RecordingProvider):def fire_claimed(self, claimed_job, **kw):- time.sleep(3.0)+ assert release.wait(10)return super().fire_claimed(claimed_job, **kw)job = create_job(prompt="p", schedule="every 1h")_park_in_past(job["id"], minutes=30)- provider = SlowProvider()- start = time.monotonic()- assert fire_overdue_jobs(provider) == 1- assert time.monotonic() - start < 1.0 # returned before the run+ provider = BlockedProvider()+ try:+ # Returns while fire_claimed is still blocked -> dispatched off-thread.+ assert fire_overdue_jobs(provider) == 1+ assert provider.fired == []+ finally:+ release.set()assert provider.wait_fired(timeout=10)assert provider.fired == [job["id"]]diff --git a/tests/cron/test_monitor_kind.py b/tests/cron/test_monitor_kind.pyindex 07f43f70125..fe75091257d 100644--- a/tests/cron/test_monitor_kind.py+++ b/tests/cron/test_monitor_kind.py@@ -112,20 +112,6 @@ def _install_agent_stubs(monkeypatch, observed: dict):# ----------------------------------------------------------------------------def test_create_job_stores_monitor_script(hermes_env):- from cron.jobs import create_job, get_job-- _write_script(hermes_env, "mon.sh", "echo stable\n")- job = create_job(- prompt="React to the change",- schedule="every 5m",- monitor_script="mon.sh",- deliver="local",- )- reloaded = get_job(job["id"])- assert reloaded["monitor_script"] == "mon.sh"- assert reloaded.get("monitor_url") is None- assert reloaded.get("monitor_state") is Nonedef test_create_job_monitor_script_and_url_mutually_exclusive(hermes_env):@@ -222,20 +208,6 @@ def test_update_job_allows_clearing_monitor_then_no_agent(hermes_env):assert reloaded["no_agent"] is True-def test_update_job_unrelated_fields_skip_mode_validation(hermes_env):- """A legacy/odd record must keep accepting updates that don't touch the- mode fields — the invariant re-check is scoped to changed fields."""- from cron.jobs import create_job, update_job-- _write_script(hermes_env, "mon.sh", "echo stable\n")- job = create_job(- prompt="React",- schedule="every 5m",- monitor_script="mon.sh",- deliver="local",- )- updated = update_job(job["id"], {"name": "renamed"})- assert updated["name"] == "renamed"# ---------------------------------------------------------------------------@@ -348,7 +320,6 @@ def test_changed_output_injects_diff(hermes_env, monkeypatch):assert success is Trueassert observed["agent_runs"] == 2prompt = observed["prompts"][1]- assert "MONITOR CHANGE DETECTED" in promptassert "-state A" in promptassert "+state B" in promptassert "state B" in prompt # new output included verbatimdiff --git a/tests/cron/test_notepad.py b/tests/cron/test_notepad.pyindex e91c1ac1392..553cd911951 100644--- a/tests/cron/test_notepad.py+++ b/tests/cron/test_notepad.py@@ -81,13 +81,6 @@ class TestNotepadCrud:assert notepad.get_note("job-2", "k") == "two"assert len(notepad.list_notes("job-1")) == 1- def test_survives_new_connection(self, notepad):- """Durability: values persist across independent calls (fresh connections)."""- notepad.set_note("job-1", "state", "persisted")- # Every public call opens its own connection, so a second read- # after the writer's connection closed proves on-disk durability.- assert notepad.get_note("job-1", "state") == "persisted"- assert notepad.list_notes("job-1")[0]["value"] == "persisted"def test_clear_notepad_removes_all_keys_for_job_only(self, notepad):notepad.set_note("job-1", "a", "1")@@ -209,12 +202,9 @@ class TestPromptInjection:notepad.set_note(job["id"], "watchlist", "alpha, beta")prompt = _build_job_prompt(job)- assert "Job notepad (persistent across runs)" in promptassert "last_seen_id" in promptassert "8842" in promptassert "watchlist" in prompt- # The injected section documents the CLI write path for this job.- assert f"hermes cron notepad {job['id']} set" in promptdef test_empty_notepad_prompt_byte_stable(self, cron_env, notepad):from cron.jobs import create_job@@ -284,7 +274,7 @@ class TestNotepadCli:big = "x" * (notepad.MAX_VALUE_BYTES + 1)assert cron_notepad(self._ns(job_id="job-1", notepad_action="set", key="k", value=big)) == 1- assert "too large" in capsys.readouterr().out.lower()+ assert notepad.get_note("job-1", "k") is Nonedef test_cron_command_dispatches_notepad(self, notepad):from hermes_cli.cron import cron_commanddiff --git a/tests/cron/test_oneshot_dispatch_failure_run_claim.py b/tests/cron/test_oneshot_dispatch_failure_run_claim.pyindex 05d511b94d6..9ce3c8cef28 100644--- a/tests/cron/test_oneshot_dispatch_failure_run_claim.py+++ b/tests/cron/test_oneshot_dispatch_failure_run_claim.py@@ -129,14 +129,3 @@ class TestDispatchFailurePathsClearClaim:n = self._tick_one(job) # must not raiseassert n == 0- def test_recurring_dispatch_failure_skips_claim_io(self, cron_store):- """Recurring jobs carry no run_claim, so the dispatch-failure paths- must not pay clear_run_claim's lock acquisition + full jobs-file read- for a guaranteed no-op — the failure paths fire exactly when the- process can least afford pointless I/O (shutdown, EMFILE)."""- from cron import scheduler as sched- job = jobs_mod.create_job(prompt="hourly", schedule="every 1h")- with patch.object(sched, "_interpreter_shutting_down", return_value=True), \- patch.object(sched, "clear_run_claim") as mock_clear:- self._tick_one(job)- mock_clear.assert_not_called()diff --git a/tests/cron/test_oneshot_grace_due_scan.py b/tests/cron/test_oneshot_grace_due_scan.pyindex c87e782d3bb..f6bb6e676fe 100644--- a/tests/cron/test_oneshot_grace_due_scan.py+++ b/tests/cron/test_oneshot_grace_due_scan.py@@ -23,10 +23,7 @@ from cron.jobs import (get_due_jobs,load_jobs,save_jobs,- save_job_output,trigger_job,- _hermes_now,- ONESHOT_GRACE_SECONDS,)FIXED_NOW = datetime(2026, 6, 22, 12, 0, 0, tzinfo=timezone.utc)@@ -73,7 +70,6 @@ class TestOneShotGraceDueScan:out_dir = cron_store / "cron" / "output" / "stale"diag = list(out_dir.glob("*.md")) if out_dir.exists() else []assert diag, "expected a diagnostic file for the retired stale one-shot"- assert "outside grace window" in diag[0].read_text(encoding="utf-8")def test_within_grace_still_due(self, cron_store):recent = _oneshot("recent", FIXED_NOW - timedelta(seconds=60))diff --git a/tests/cron/test_oneshot_guard_warning.py b/tests/cron/test_oneshot_guard_warning.pyindex bea47f3d309..719f184d2a5 100644--- a/tests/cron/test_oneshot_guard_warning.py+++ b/tests/cron/test_oneshot_guard_warning.py@@ -1,14 +1,10 @@-"""Due-scan dispatch-limit guard: removal of a re-armed consumed one-shot is-operator-visible (#93524 follow-up to #93615).+"""Due-scan dispatch-limit guard: a re-armed consumed one-shot never fires twice.Pre-#93615 stores (or hand edits) can hold a record that already completed arun (last_run_at set) but was re-armed without a budget reset. The due-scan-guard removes it without firing — correct, since #93615's policy routes-re-runs through `cron resume` — but the removal must log at WARNING with a-remediation hint, never a silent INFO delete.+guard removes it without firing — re-runs go through `cron resume`."""-import loggingfrom datetime import timedeltaimport pytest@@ -34,7 +30,7 @@ def temp_home(tmp_path, monkeypatch):return tmp_path-def test_guard_warns_on_rearmed_consumed_record(temp_home, caplog):+def test_rearmed_consumed_oneshot_is_removed_without_firing(temp_home):job = create_job(prompt="x",schedule=(_hermes_now() + timedelta(hours=1)).isoformat(),@@ -54,42 +50,9 @@ def test_guard_warns_on_rearmed_consumed_record(temp_home, caplog):j["next_run_at"] = (_hermes_now() - timedelta(seconds=5)).isoformat()save_jobs(jobs)- with caplog.at_level(logging.INFO, logger="cron"):- due = get_due_jobs()+ due = get_due_jobs()assert jid not in [d["id"] for d in due]assert jid not in [j["id"] for j in load_jobs()]- warnings = [- r for r in caplog.records- if r.levelno == logging.WARNING and "WITHOUT firing" in r.getMessage()- ]- assert warnings, "expected WARNING on removal of a re-armed consumed one-shot"- assert "cron resume" in warnings[0].getMessage()-def test_guard_stays_info_for_never_ran_stale_record(temp_home, caplog):- """The dead-tick recovery case (no last_run_at) keeps its quiet INFO."""- job = create_job(- prompt="x",- schedule=(_hermes_now() + timedelta(hours=1)).isoformat(),- name="quiet-guard",- deliver="local",- )- jid = job["id"]-- jobs = load_jobs()- for j in jobs:- if j["id"] == jid:- j["repeat"] = {"times": 1, "completed": 1}- j["last_run_at"] = None- j["next_run_at"] = (_hermes_now() - timedelta(seconds=5)).isoformat()- save_jobs(jobs)-- with caplog.at_level(logging.INFO, logger="cron"):- get_due_jobs()-- warns = [- r for r in caplog.records- if r.levelno == logging.WARNING and "WITHOUT firing" in r.getMessage()- ]- assert not warns, "never-ran stale record must not trip the WARNING path"diff --git a/tests/cron/test_owner_start_time_drift.py b/tests/cron/test_owner_start_time_drift.pyindex d8bc14f8807..f12fd1ab0b2 100644--- a/tests/cron/test_owner_start_time_drift.py+++ b/tests/cron/test_owner_start_time_drift.py@@ -41,10 +41,7 @@ def _status(execution_id: str) -> str:@pytest.mark.parametrize("drift,expect_live",[- (0, True), # exact match: the historical guarantee(100, True), # 1 s drift: the reported macOS boot-time step (#117505)- (200, True), # tolerance boundary- (201, False), # just outside tolerance: presumed recycled PID(3600, False), # PID-reuse scale],)diff --git a/tests/cron/test_parallel_pool.py b/tests/cron/test_parallel_pool.pyindex 4a7515655d3..e81566590fc 100644--- a/tests/cron/test_parallel_pool.py+++ b/tests/cron/test_parallel_pool.py@@ -7,41 +7,9 @@ prevented the ticker thread from firing, causing all other jobs to be fast-forwaimport concurrent.futuresimport threadingimport time-from unittest.mock import patch-import pytest-class TestPersistentPool:- """_get_parallel_pool returns a persistent ThreadPoolExecutor."""-- def test_pool_is_reused(self, monkeypatch):- """Same pool instance returned when max_workers doesn't change."""- import cron.scheduler as sched-- # Reset module state.- sched._parallel_pools.clear()- sched._parallel_pool_max_workers.clear()-- pool1 = sched._get_parallel_pool(4)- pool2 = sched._get_parallel_pool(4)- assert pool1 is pool2-- # Cleanup.- sched._shutdown_parallel_pool()--- def test_shutdown_clears_pool(self, monkeypatch):- """_shutdown_parallel_pool resets state."""- import cron.scheduler as sched-- sched._parallel_pools.clear()- sched._parallel_pool_max_workers.clear()- sched._get_parallel_pool(2)-- sched._shutdown_parallel_pool()- assert not sched._parallel_pools- assert not sched._parallel_pool_max_workersclass TestRunningJobGuard:@@ -274,123 +242,4 @@ class TestSyncMode:sched._shutdown_parallel_pool()-class TestWorkdirParallelPool:- """Task-scoped workdir jobs use the normal persistent parallel pool."""-- def test_workdir_job_does_not_block_ticker(self, tmp_path, monkeypatch):- """sync=False returns immediately even when a workdir job is slow."""- import cron.scheduler as sched-- sched._parallel_pools.clear()- sched._parallel_pool_max_workers.clear()- sched._running_job_ids.clear()-- job = {- "id": "slow-workdir",- "name": "slow-workdir",- "prompt": "test",- "schedule": "every 5m",- "enabled": True,- "next_run_at": "2020-01-01T00:00:00",- "deliver": "local",- "workdir": str(tmp_path),- }-- barrier = threading.Barrier(2, timeout=5)-- def slow_run(j, *, defer_agent_teardown=None, **_kw):- barrier.wait()- return True, "out", "resp", None-- monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])- monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)- monkeypatch.setattr(sched, "run_job", slow_run)- monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: "/tmp/out")- monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)- monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)-- start = time.monotonic()- n = sched.tick(verbose=False, sync=False)- elapsed = time.monotonic() - start-- assert n == 1 # optimistic count- assert elapsed < 1.0 # did NOT block on the slow workdir job-- barrier.wait()- time.sleep(0.1)- sched._shutdown_parallel_pool()-- def test_workdir_running_guard_prevents_double_dispatch(self, tmp_path, monkeypatch):- """A workdir job already in _running_job_ids is skipped on next tick."""- import cron.scheduler as sched- sched._parallel_pools.clear()- sched._parallel_pool_max_workers.clear()- sched._running_job_ids.clear()-- job = {- "id": "guard-seq",- "name": "guard-seq",- "prompt": "test",- "schedule": "every 5m",- "enabled": True,- "next_run_at": "2020-01-01T00:00:00",- "deliver": "local",- "workdir": str(tmp_path),- }-- # Simulate the job already running.- sched._running_job_ids.add(sched._inflight_key("guard-seq"))-- dispatched = []- monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])- monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)- monkeypatch.setattr(sched, "run_job", lambda j, **_kw: dispatched.append(j["id"]) or (True, "out", "resp", None))- monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: None)- monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)- monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)-- n = sched.tick(verbose=False)- assert n == 0 # skipped, not dispatched- assert dispatched == []-- sched._running_job_ids.discard(sched._inflight_key("guard-seq"))- sched._shutdown_parallel_pool()--class TestTickBatchAdvance:- """The tick's pre-dispatch advance must go through advance_next_runs- exactly once with the whole due set — a revert to the per-job loop- (or back to advance_next_run) must fail this test, not slip past the- helper-level I/O pin."""-- def test_tick_calls_advance_next_runs_once_with_all_due_ids(self, tmp_path, monkeypatch):- import cron.scheduler as sched-- sched._parallel_pools.clear()- sched._parallel_pool_max_workers.clear()- sched._running_job_ids.clear()-- jobs = [- {"id": f"job-{i}", "name": f"Job {i}", "prompt": "test",- "schedule": "every 5m", "enabled": True,- "next_run_at": "2020-01-01T00:00:00", "deliver": "local"}- for i in range(4)- ]-- advance_calls = []- monkeypatch.setattr(sched, "get_due_jobs", lambda: jobs)- monkeypatch.setattr(- sched, "advance_next_runs",- lambda ids: advance_calls.append(list(ids)) or len(list(ids)))- monkeypatch.setattr(sched, "run_job", lambda j, **_kw: (True, "out", "resp", None))- monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: "/tmp/out")- monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)- monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)-- n = sched.tick(verbose=False)-- assert n == 4- assert advance_calls == [["job-0", "job-1", "job-2", "job-3"]], (- f"tick must batch-advance the due set in ONE call; got {advance_calls}")-- sched._shutdown_parallel_pool()diff --git a/tests/cron/test_preflight_config.py b/tests/cron/test_preflight_config.pyindex 1847bcd2925..9aafdb7d74e 100644--- a/tests/cron/test_preflight_config.py+++ b/tests/cron/test_preflight_config.py@@ -159,7 +159,6 @@ class TestMissingProviderKeyBlocks:f"expected exactly one alert across two ticks, got {len(deliveries)}: "f"{deliveries!r}")- assert "did not run" in deliveries[0].lower()def test_fallback_chain_rescues_missing_primary_key(self, tmp_path):"""A configured fallback chain means a missing primary key does NOTdiff --git a/tests/cron/test_preflight_credential_verdict_names_home.py b/tests/cron/test_preflight_credential_verdict_names_home.pyindex 24780b66e27..9cc009d72f6 100644--- a/tests/cron/test_preflight_credential_verdict_names_home.py+++ b/tests/cron/test_preflight_credential_verdict_names_home.py@@ -37,7 +37,7 @@ def test_missing_codex_credential_verdict_names_the_home_it_read(two_homes):root, alpha = two_homesreason = _preflight_check_provider_key(JOB, {"cron": {}})- assert reason and "No Codex credentials stored" in reason+ assert reasonassert _scope(reason) == ("default", str(root))# Multiplex tick of a satellite profile: the verdict names alpha, not the gateway's launch home.diff --git a/tests/cron/test_quota_hold.py b/tests/cron/test_quota_hold.pyindex 73fbe91edde..dc730c709d6 100644--- a/tests/cron/test_quota_hold.py+++ b/tests/cron/test_quota_hold.py@@ -85,8 +85,7 @@ def test_quota_hold_parks_past_window_survives_stale_rearm_and_clears_on_model_r_tick(get_job(job_id), tmp_cron_home, deliveries, _raise_quota)j = get_job(job_id)assert j["last_status"] == "error"- assert len(deliveries) == 1 and "This job is held" in deliveries[0], deliveries- assert "provider credential missing" not in deliveries[0]+ assert len(deliveries) == 1, deliveriesparked = datetime.fromisoformat(j["next_run_at"])assert parked - now >= timedelta(seconds=123518), "next_run_at must land past the window"assert j[qh.STATE_KEY] == j["next_run_at"]diff --git a/tests/cron/test_reasoning_config_per_model.py b/tests/cron/test_reasoning_config_per_model.pydeleted file mode 100644index 40caf1d7869..00000000000--- a/tests/cron/test_reasoning_config_per_model.py+++ /dev/null@@ -1,89 +0,0 @@-"""Tests for per-model reasoning_effort override in cron scheduler."""--import pytest---class TestCronPerModelReasoningConfig:- """Test cron scheduler respects per-model reasoning overrides.-- Rather than spinning up a full CronScheduler (heavy), we verify the- resolution logic by testing the helper directly against a config dict- shaped the same way the scheduler reads it.- """-- def test_per_model_override_resolves_for_cron_model(self):- """The spelling-tolerant helper resolves the cron config's model."""- from hermes_constants import resolve_per_model_reasoning_effort-- # Simulate cron scheduler config shape- _cfg = {- "model": {"default": "anthropic/claude-opus-4.5"},- "agent": {- "reasoning_effort": "medium",- "reasoning_overrides": {- "anthropic/claude-opus-4.5": "xhigh",- },- },- }- _model_cfg = _cfg.get("model", {})- _model = str(_model_cfg.get("default", "") or "").strip()- _overrides = (_cfg.get("agent", {}) or {}).get("reasoning_overrides", {}) or {}-- result = resolve_per_model_reasoning_effort(_model, _overrides)- assert result is not None- assert result["effort"] == "xhigh"-- def test_cron_falls_back_to_global_when_no_override(self):- """When no per-model override matches, global effort is used."""- from hermes_constants import parse_reasoning_effort, resolve_per_model_reasoning_effort-- _cfg = {- "model": {"default": "gpt-5"},- "agent": {- "reasoning_effort": "low",- "reasoning_overrides": {- "anthropic/claude-opus-4.5": "xhigh",- },- },- }- _model = _cfg["model"]["default"]- _overrides = _cfg["agent"]["reasoning_overrides"]-- per_model = resolve_per_model_reasoning_effort(_model, _overrides)- assert per_model is None # no match-- # Scheduler falls back to global- effort = _cfg["agent"]["reasoning_effort"]- result = parse_reasoning_effort(effort)- assert result is not None- assert result["effort"] == "low"--- def test_global_fallback_with_yaml_false(self):- """YAML boolean False must reach parse_reasoning_effort uncoerced.-- Regression: str(... or "").strip() turned False into "", silently- re-enabling thinking. The raw value must pass through so- parse_reasoning_effort(False) returns {'enabled': False}.- """- from hermes_constants import parse_reasoning_effort, resolve_per_model_reasoning_effort-- _cfg = {- "model": {"default": "gpt-5"},- "agent": {- "reasoning_effort": False, # YAML boolean, not string- "reasoning_overrides": {"claude-opus-4.5": "xhigh"},- },- }- _model = _cfg["model"]["default"]- _overrides = _cfg["agent"]["reasoning_overrides"]-- per_model = resolve_per_model_reasoning_effort(_model, _overrides)- assert per_model is None # no match-- # Scheduler global fallback — raw value, no coercion- result = parse_reasoning_effort(- _cfg.get("agent", {}).get("reasoning_effort", "")- )- assert result is not None- assert result.get("enabled") is Falsediff --git a/tests/cron/test_recurring_eagain_redispatch.py b/tests/cron/test_recurring_eagain_redispatch.pydeleted file mode 100644index 4bf56a0eccc..00000000000--- a/tests/cron/test_recurring_eagain_redispatch.py+++ /dev/null@@ -1,174 +0,0 @@-"""Deterministic reproduction of the recurring-cron EAGAIN in-memory wedge (t_8b5480b3).--Scenario modelled on the 2026-08-14 incident: a recurring no_agent interval job-whose script subprocess raises EAGAIN ([Errno 11] Resource temporarily-unavailable) during a substrate thread-exhaustion spike. After the failure is-recorded (terminal 'failed' execution row), the job must be re-dispatched on-the NEXT tick once the substrate recovers — with no force-run.--SCOPE NOTE (honest): this file exercises the in-memory EAGAIN-release class —-the claim taken by ``_submit_with_guard`` is released when the submit/init-path fails, so the NEXT tick re-dispatches. It passes on unfixed base because-a terminal ``failed`` execution row does not itself suppress a recurring job's-next due fire; that is pre-existing behavior, not the fix. The persisted-state-(restart-surviving) half of the incident — a recurring job whose persisted-``last_status=error`` and ``next_run_at`` parked in the future is never-re-dispatched without force-run/resume — is covered by-``test_recurring_persisted_error_recovery.py``, which provides the clean-behavioral RED (unfixed: no execution) / GREEN (fixed: re-dispatched) for the-new recovery path.--This file drives the REAL `tick()` end-to-end against a throwaway HERMES_HOME:- tick 1 -> script EAGAINs (subprocess.run raises OSError 11) -> failed exec row- tick 2 -> substrate recovered (script runs clean) -> job MUST fire again-"""-from __future__ import annotations--import json-import os-import subprocess-from datetime import datetime, timedelta, timezone-from pathlib import Path-from unittest import mock--import pytest--# Ensure project root importable-import sys-sys.path.insert(0, str(Path(__file__).parent.parent.parent))---def wedge_env(tmp_path, monkeypatch):- """Isolated cron env + a recurring no_agent interval job, due NOW."""- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- (hermes_home / "cron").mkdir()- (hermes_home / "cron" / "output").mkdir()- (hermes_home / "scripts").mkdir()- monkeypatch.setenv("HERMES_HOME", str(hermes_home))-- import cron.jobs as jobs_mod- monkeypatch.setattr(jobs_mod, "HERMES_DIR", hermes_home)- monkeypatch.setattr(jobs_mod, "CRON_DIR", hermes_home / "cron")- monkeypatch.setattr(jobs_mod, "JOBS_FILE", hermes_home / "cron" / "jobs.json")- monkeypatch.setattr(jobs_mod, "OUTPUT_DIR", hermes_home / "cron" / "output")-- # Create a recurring no_agent interval job.- job = jobs_mod.create_job(- prompt="probe",- schedule="every 10m",- no_agent=True,- script="probe.py",- )- # Force it due now.- now = datetime.now(timezone.utc)- jobs_mod.update_job(job["id"], {"next_run_at": (now - timedelta(minutes=1)).isoformat()})-- script = hermes_home / "scripts" / "probe.py"- script.write_text("print('ok')\n")-- return {"home": hermes_home, "job_id": job["id"]}---class TestEAGAINRecurringRedispatches:- def _make_script_eagain(self, env, monkeypatch):- """Make the next subprocess.Popen raise EAGAIN once, then pass.-- The script runner spawns via Popen (polling loop for cancel/timeout),- so the substrate-failure injection point is the Popen constructor.- """- import cron.scheduler as sched_mod- state = {"n": 0}-- class _OkProc:- def __init__(self, argv, **kwargs):- self.returncode = 0-- def poll(self):- return self.returncode-- def communicate(self, timeout=None):- return ("ok\n", "")-- def wait(self, timeout=None):- return 0-- def fake_popen(argv, **kwargs):- state["n"] += 1- if state["n"] == 1:- raise OSError(11, "Resource temporarily unavailable")- return _OkProc(argv, **kwargs)-- monkeypatch.setattr(sched_mod.subprocess, "Popen", fake_popen)- return state-- def test_eagain_then_redispatched_on_next_tick(self, wedge_env, monkeypatch, tmp_path):- """Tick 1 records a failed execution (EAGAIN); tick 2 must re-fire."""- from cron import scheduler as S- from cron import executions as E-- env = wedge_env- # Point the executions ledger at the throwaway home.- monkeypatch.setattr(E, "EXECUTIONS_FILE", env["home"] / "cron" / "executions.db")- monkeypatch.setattr(S, "_hermes_home", env["home"])- monkeypatch.setattr(S, "get_due_jobs", S.get_due_jobs) # no-op, keep real-- state = self._make_script_eagain(env, monkeypatch)-- # Tick 1: EAGAIN failure.- n1 = S.tick(verbose=False, sync=True)- # Assert the failure was recorded.- latest = E.latest_execution(env["job_id"])- assert latest is not None, "tick 1 must create an execution"- assert latest["status"] == "failed", f"expected failed, got {latest['status']}"-- # The job must still be scheduled (recurring), next_run_at advanced.- import cron.jobs as J- job = J.get_job(env["job_id"])- assert job["enabled"] is True- assert job["state"] == "scheduled"- assert job["next_run_at"] is not None-- # Force next_run_at due again (simulate the substrate recovery tick).- now = datetime.now(timezone.utc)- J.update_job(env["job_id"], {"next_run_at": (now - timedelta(minutes=1)).isoformat()})-- # Tick 2: script passes -> job must fire (completed execution).- n2 = S.tick(verbose=False, sync=True)- latest2 = E.latest_execution(env["job_id"])- assert latest2 is not None- assert latest2["status"] == "completed", (- f"job must be re-dispatched after EAGAIN recovery, got {latest2['status']}"- )- assert state["n"] >= 2-- def test_trigger_job_unwedges_persisted_state(self, wedge_env, monkeypatch, tmp_path):- """The incident force-run (`cron run <id>` -> trigger_job) resets the- persisted due state so the next tick fires the job. This is the- operator escape that cleared each wedge."""- from cron import scheduler as S- from cron import executions as E- from cron.jobs import trigger_job, update_job-- env = wedge_env- monkeypatch.setattr(E, "EXECUTIONS_FILE", env["home"] / "cron" / "executions.db")- monkeypatch.setattr(S, "_hermes_home", env["home"])-- self._make_script_eagain(env, monkeypatch)- n1 = S.tick(verbose=False, sync=True)-- # Simulate the persisted non-dispatch state: next_run_at far in the- # future (job not due) but still enabled/scheduled — the observed- # wedge where get_due_jobs never returns it.- from datetime import timezone as tz- far = datetime.now(tz.utc) + timedelta(days=1)- update_job(env["job_id"], {"next_run_at": far.isoformat()})- n2 = S.tick(verbose=False, sync=True) # not due -> no dispatch-- # Force-run (trigger_job) sets next_run_at = now -> due again.- triggered = trigger_job(env["job_id"])- assert triggered is not None- n3 = S.tick(verbose=False, sync=True)- latest = E.latest_execution(env["job_id"])- assert latest["status"] == "completed", "force-run must clear the wedge"diff --git a/tests/cron/test_recurring_persisted_error_recovery.py b/tests/cron/test_recurring_persisted_error_recovery.pyindex 78efb07e03b..3a89ba48e63 100644--- a/tests/cron/test_recurring_persisted_error_recovery.py+++ b/tests/cron/test_recurring_persisted_error_recovery.py@@ -29,7 +29,6 @@ execution row, no re-dispatch); with the recovery it re-fires and completes.from __future__ import annotationsimport sys-import timefrom datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom unittest import mock@@ -118,29 +117,6 @@ class TestPersistedStaleErrorRecovery:stats = Jmod.get_persisted_error_recovery_stats()assert stats["persisted_error_recoveries"] >= 1- def test_two_consecutive_auto_fires_after_persisted_recovery(- self, cron_env, monkeypatch- ):- """GREEN: after the persisted recovery re-arms the job, it fires on- consecutive ticks (no manual intervention)."""- S, E, J, env = _setup(cron_env, monkeypatch)- job_id = env["job_id"]-- _persist_stale_error(J, job_id, error_age_minutes=110)- job = J.get_job(job_id)- with mock.patch("cron.jobs.load_jobs", return_value=[job]):- S.tick(verbose=False, sync=True)- latest1 = E.latest_execution(job_id)- assert latest1["status"] == "completed"-- # Re-arm due normally and tick again: fire #2.- now = datetime.now(timezone.utc)- J.update_job(job_id, {"next_run_at": (now - timedelta(minutes=1)).isoformat()})- with mock.patch("cron.jobs.load_jobs", return_value=[J.get_job(job_id)]):- S.tick(verbose=False, sync=True)- latest2 = E.latest_execution(job_id)- assert latest2["status"] == "completed"- assert latest2["id"] != latest1["id"], "two distinct executions"def test_recent_error_within_cadence_not_force_rearmed(self, cron_env, monkeypatch):"""The discriminator must NOT re-arm a normal transient error whosediff --git a/tests/cron/test_recurring_wedge_selfheal.py b/tests/cron/test_recurring_wedge_selfheal.pyindex 99f98075796..8a733ddb2a2 100644--- a/tests/cron/test_recurring_wedge_selfheal.py+++ b/tests/cron/test_recurring_wedge_selfheal.py@@ -86,8 +86,6 @@ class TestStaleInflightSelfHeal:job_id = env["job_id"]import cron.jobs as J- if not hasattr(S, "sweep_stale_inflight"):- pytest.skip("guard not present on this build")# Simulate the incident leak: job id claimed with no owning future,# old enough to be past its allowance.@@ -111,42 +109,11 @@ class TestStaleInflightSelfHeal:"wedged job must fire again without force-run")- def test_two_consecutive_auto_fires_after_guard(self, cron_env, monkeypatch):- """GREEN: after the guard releases a stale claim, the job fires on- consecutive ticks (no manual intervention)."""- S, E, env = self._setup(cron_env, monkeypatch)- job_id = env["job_id"]- import cron.jobs as J-- if not hasattr(S, "sweep_stale_inflight"):- pytest.skip("guard not present on this build")-- S._running_job_ids.clear()- S._running_since.clear()- S._running_futures.clear()- S._running_job_ids.add(S._inflight_key(job_id))- S._running_since[S._inflight_key(job_id)] = time.time() - 6 * 60 * 60-- job = J.get_job(job_id)- with mock.patch("cron.jobs.load_jobs", return_value=[job]):- n1 = S.tick(verbose=False, sync=True)- latest1 = E.latest_execution(job_id)- assert latest1["status"] == "completed"-- # Re-arm due and tick again: fire #2.- now = datetime.now(timezone.utc)- J.update_job(job_id, {"next_run_at": (now - timedelta(minutes=1)).isoformat()})- n2 = S.tick(verbose=False, sync=True)- latest2 = E.latest_execution(job_id)- assert latest2["status"] == "completed"- assert latest2["id"] != latest1["id"], "two distinct executions"def test_guard_stats_reported(self, cron_env, monkeypatch):"""The guard must surface a countable forced-release signal."""S, E, env = self._setup(cron_env, monkeypatch)import cron.jobs as J- if not hasattr(S, "sweep_stale_inflight"):- pytest.skip("guard not present on this build")S._running_job_ids.clear()S._running_since.clear()@@ -164,38 +131,6 @@ class TestEAGAINCreateExecutionLeak:in-flight claim and execution creation (create_execution / pool.submit).The claim must be released immediately so the next tick re-dispatches."""- def test_create_execution_failure_releases_claim(self, cron_env, monkeypatch, tmp_path):- from cron import scheduler as S- from cron import executions as E- import cron.jobs as J-- env = cron_env- monkeypatch.setattr(E, "EXECUTIONS_FILE", env["home"] / "cron" / "executions.db")- monkeypatch.setattr(S, "_hermes_home", env["home"])- job_id = env["job_id"]- job = J.get_job(job_id)-- S._running_job_ids.clear()- S._running_since.clear()- S._running_futures.clear()-- # Simulate EAGAIN during create_execution (substrate thread exhaustion- # at 12:50): the in-flight claim was taken but execution creation fails.- def boom(*a, **k):- raise OSError(11, "Resource temporarily unavailable")- monkeypatch.setattr(S, "create_execution", boom)-- with mock.patch("cron.jobs.load_jobs", return_value=[job]):- # The failure is contained per-job (#86482 follow-up): the tick- # logs an ERROR, skips this fire, and moves on to the remaining- # due jobs instead of aborting the whole dispatch loop.- S.tick(verbose=False, sync=True)-- # The claim must be released (not leaked) so the NEXT tick can retry.- assert job_id not in S.get_running_job_ids(), (- "claim must be released when execution creation fails, so the "- "next tick re-dispatches instead of wedging on 'already running'"- )def test_pool_submit_eagain_releases_claim_and_redispatches(self, cron_env, monkeypatch, tmp_path):from cron import scheduler as Sdiff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.pyindex af9881c1212..aa3d0b2505c 100644--- a/tests/cron/test_restart_safe_worker.py+++ b/tests/cron/test_restart_safe_worker.py@@ -74,7 +74,6 @@ def test_genuine_external_worker_crash_is_recovered_unknown(assert execution_ledger.recover_interrupted_executions() == 1recovered = execution_ledger.latest_execution("job-crash")assert recovered["status"] == "unknown"- assert "whether side effects ran is unknown" in recovered["error"]@pytest.mark.linux_only@@ -129,22 +128,6 @@ def test_restart_safe_gateway_child_is_unchanged_outside_managed_gateway(monkeypassert dispatch.argv is command-def test_restart_safe_gateway_child_never_probes_systemd_off_linux(monkeypatch):- import tools.process_registry as process_registry-- command = ["python", "worker.py"]- probe = Mock(side_effect=AssertionError("systemd probe ran off Linux"))- monkeypatch.setattr(process_registry, "_IS_LINUX", False)- monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: True)- monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", probe)- monkeypatch.setenv("INVOCATION_ID", "managed-service")-- dispatch = process_registry.restart_safe_gateway_child_argv(- command, unit_suffix="cron-job-1", require_restart_safe_scope=False- )- assert dispatch.mode == "in_process"- assert dispatch.argv is command- probe.assert_not_called()def test_external_worker_adopts_execution_and_runs_payload_once(@@ -518,39 +501,6 @@ def test_external_worker_crash_recovers_uncertain_attempt(monkeypatch):assert get.call_count == 2-def test_terminal_early_return_still_reaps_the_worker(monkeypatch):- """The ledger can turn terminal while the worker is still tearing down; the- waiter returns then, but the gateway stays the worker's parent, so the exit- must still be waited for somewhere — otherwise the worker lingers as a- zombie under the gateway until it is restarted (#114509)."""- import cron.scheduler as scheduler-- monkeypatch.setattr(- scheduler,- "get_execution",- lambda _execution_id: {"id": "exec-1", "status": "completed"},- raising=False,- )-- def wait(timeout=None):- if wait.calls == 0:- wait.calls += 1- raise subprocess.TimeoutExpired(cmd="worker", timeout=timeout)- return 0-- wait.calls = 0- process = Mock()- process.pid = 4321- process.wait.side_effect = wait-- assert scheduler._wait_for_external_cron_worker_body(- process, execution_id="exec-1"- ) is True- # the background reaper owns the second and final wait(); no third caller appears- deadline = time.monotonic() + 5.0- while process.wait.call_count < 2 and time.monotonic() < deadline:- time.sleep(0.05)- assert process.wait.call_count == 2def test_terminal_early_return_reaps_a_real_worker_process(monkeypatch):@@ -779,7 +729,7 @@ def test_worker_delivery_queue_is_keyed_by_the_delivering_jobs_own_execution(adapters=None,loop=None,)- assert error == "failed to load gateway config: standalone path reached"+ assert "standalone path reached" in errorassert queued == ["exec-outer"]@@ -802,20 +752,6 @@ def test_gateway_tool_run_without_adapter_objects_hands_off(monkeypatch):run.assert_not_called()-def test_shared_run_path_creates_execution_before_managed_handoff(monkeypatch):- import cron.scheduler as scheduler-- created = Mock(return_value={"id": "exec-new"})- launch = Mock(return_value=True)- monkeypatch.setattr(scheduler, "create_execution", created)- monkeypatch.setattr(scheduler, "_launch_external_cron_worker", launch)- job = {"id": "manual-job"}-- assert scheduler.run_one_job(job, adapters={"discord": object()}) is True-- created.assert_called_once_with("manual-job", source="direct", scheduled_instant=None)- assert job["execution_id"] == "exec-new"- launch.assert_called_once_with(job)def test_lost_execution_start_cas_prevents_side_effects(monkeypatch):diff --git a/tests/cron/test_rewrite_skill_refs.py b/tests/cron/test_rewrite_skill_refs.pyindex cb19aea96ac..36bc524dc12 100644--- a/tests/cron/test_rewrite_skill_refs.py+++ b/tests/cron/test_rewrite_skill_refs.py@@ -37,23 +37,6 @@ def cron_env(tmp_path, monkeypatch):return hermes_home-class TestRewriteSkillRefsNoop:- """No jobs, no rewrites, no map — every combination of empty inputs."""-- def test_empty_map_and_no_jobs(self, cron_env):- from cron.jobs import rewrite_skill_refs-- report = rewrite_skill_refs(consolidated={}, pruned=[])- assert report == {"rewrites": [], "jobs_updated": 0, "jobs_scanned": 0}-- def test_jobs_exist_but_map_empty(self, cron_env):- from cron.jobs import create_job, rewrite_skill_refs-- create_job(prompt="", schedule="every 1h", skills=["foo"])- report = rewrite_skill_refs(consolidated={}, pruned=[])- assert report["jobs_updated"] == 0- # Early return: we don't even scan when there's nothing to apply.- assert report["jobs_scanned"] == 0class TestRewriteSkillRefsConsolidation:@@ -238,17 +221,6 @@ class TestRewriteSkillRefsMultipleJobs:class TestRewriteSkillRefsPersistence:"""Rewrites persist to disk and survive a reload."""- def test_changes_persist_across_reload(self, cron_env):- import json- from cron.jobs import create_job, rewrite_skill_refs, JOBS_FILE-- create_job(prompt="", schedule="every 1h", skills=["legacy"])- rewrite_skill_refs(consolidated={"legacy": "umbrella"}, pruned=[])-- # Read raw file contents- data = json.loads(JOBS_FILE.read_text())- assert data["jobs"][0]["skills"] == ["umbrella"]- assert data["jobs"][0]["skill"] == "umbrella"def test_noop_does_not_rewrite_file(self, cron_env):from cron.jobs import create_job, rewrite_skill_refs, JOBS_FILEdiff --git a/tests/cron/test_run_one_job.py b/tests/cron/test_run_one_job.pyindex 60fd0f66be5..65450a51d63 100644--- a/tests/cron/test_run_one_job.py+++ b/tests/cron/test_run_one_job.py@@ -43,17 +43,6 @@ def _patch_pipeline(monkeypatch, *, success=True, output="out", final="final resreturn calls-def test_tick_process_job_sequence(monkeypatch):- """Characterization: a single due job driven through tick() runs the- sequence run_job → save → deliver → mark, in that order."""- calls = _patch_pipeline(monkeypatch)- monkeypatch.setattr(s, "get_due_jobs", lambda: [{"id": "j1", "name": "t"}])- monkeypatch.setattr(s, "claim_job_for_fire", lambda _job_id, **_kwargs: True)-- s.tick(verbose=False, sync=True)-- assert [c[0] for c in calls] == ["run_job", "save", "deliver", "mark"]- assert calls[-1] == ("mark", "j1", True)def test_tick_skips_job_when_durable_fire_claim_is_lost(monkeypatch):@@ -259,7 +248,6 @@ def test_escaped_failure_delivery_carries_the_streak_nudge(monkeypatch):assert ok is Falseassert len(delivered) == 1assert "cannot import name X" in delivered[0]- assert "failed 3 runs in a row" in delivered[0]assert "hermes cron pause scout" in delivered[0]@@ -282,8 +270,8 @@ def test_escaped_failure_delivery_stays_quiet_below_the_threshold(monkeypatch):assert ok is Falseassert len(delivered) == 1- assert delivered[0].startswith("⚠️ Cron 'scout' failed: provider failed")- assert "hermes cron runs j6" in delivered[0]+ assert "provider failed" in delivered[0]+ assert "hermes cron pause scout" not in delivered[0]def test_run_one_job_exception_after_delivery_does_not_redeliver(monkeypatch):diff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.pyindex afab9c477c9..8fa216b0989 100644--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@ -4,7 +4,6 @@ import contextlibimport contextvarsimport itertoolsimport json-import loggingimport osfrom unittest.mock import AsyncMock, patch, MagicMock@@ -23,7 +22,6 @@ from cron.scheduler import ()from cron.scheduler_delivery import _resolve_origin, _send_media_via_adapterfrom tools.env_passthrough import clear_env_passthrough-from tools.credential_files import clear_credential_filesdef test_cron_cleanup_worker_inherits_caller_contextvars():@@ -81,7 +79,6 @@ class TestSummarizeCronFailureForDelivery:)assert "script timed out" in summary- assert "No model was invoked" in summaryassert "did not respond in time" not in summaryassert "backup provider" not in summary.lower()@@ -120,19 +117,6 @@ class TestPerJobToolsetMcpMerge:assert not (set(result) & self._enabled_names())- def test_resolver_empty_per_job_falls_through_to_platform(self):- # No per-job list -> must delegate to _get_platform_tools (the platform- # fallback), NOT the per-job merge. Stub the platform resolver and assert- # it is the path taken and its result is returned.- job = {"enabled_toolsets": None}- sentinel = ["web", "finnhub"]- with patch("hermes_cli.tools_config._get_platform_tools",- return_value=set(sentinel)) as m_platform:- result = _resolve_cron_enabled_toolsets(job, self.CFG)- m_platform.assert_called_once()- # _get_platform_tools args: (cfg, "cron")- assert m_platform.call_args[0][1] == "cron"- assert set(result) == set(sentinel)def test_resolver_keeps_memory_in_per_job_list(self):result = _resolve_cron_enabled_toolsets(@@ -165,22 +149,6 @@ class TestPerJobToolsetMcpMerge:class TestResolveOrigin:- def test_full_origin(self):- job = {- "origin": {- "platform": "telegram",- "chat_id": "123456",- "chat_name": "Test Chat",- "thread_id": "42",- }- }- result = _resolve_origin(job)- assert isinstance(result, dict)- assert result == job["origin"]- assert result["platform"] == "telegram"- assert result["chat_id"] == "123456"- assert result["chat_name"] == "Test Chat"- assert result["thread_id"] == "42"@pytest.mark.parametrize(@@ -385,32 +353,6 @@ class TestDeliverResultWrapping:)return media_file.resolve()- def test_delivery_wraps_content_with_header_and_footer(self):- """Delivered content should include task name header and agent-invisible note."""- from gateway.config import Platform-- pconfig = MagicMock()- pconfig.enabled = True- mock_cfg = MagicMock()- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}-- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \- patch("tools.send_message_tool._send_to_platform", new=AsyncMock(return_value={"success": True})) as send_mock:- job = {- "id": "test-job",- "name": "daily-report",- "deliver": "origin",- "origin": {"platform": "telegram", "chat_id": "123"},- }- _deliver_result(job, "Here is today's summary.")-- send_mock.assert_called_once()- sent_content = send_mock.call_args.kwargs.get("content") or send_mock.call_args[0][-1]- assert "Cronjob Response: daily-report" in sent_content- assert "(job_id: test-job)" in sent_content- assert "-------------" in sent_content- assert "Here is today's summary." in sent_content- assert "To stop or manage this job" in sent_contentdef test_relay_fronted_home_uses_relay_config_and_live_adapter(self, monkeypatch, tmp_path):@@ -568,7 +510,6 @@ class TestDeliverResultErrorReturns:}result = _deliver_result(job, "Output.")assert result is not None- assert "not configured" in resultclass TestRunJobSessionPersistence:@@ -740,22 +681,6 @@ class TestRunJobSessionPersistence:"memory toolset must not be policy-denied in cron")- def test_run_job_keeps_per_job_memory_toolset(self, tmp_path):- """A per-job enabled_toolsets naming memory keeps it."""- job = {- "id": "memory-toolset-job",- "name": "test",- "prompt": "remember what you learn",- "enabled_toolsets": ["memory", "file"],- }- with self._run_job_patches(tmp_path) as (fake_db, mock_agent_cls):- run_job(job)-- kwargs = mock_agent_cls.call_args.kwargs- assert kwargs["skip_memory"] is False- assert "memory" in (kwargs["enabled_toolsets"] or [])- assert "file" in (kwargs["enabled_toolsets"] or [])- assert "memory" not in kwargs["disabled_toolsets"]def test_tick_skips_due_jobs_while_dispatch_is_paused(self, tmp_path):"""The drain gate runs before advancing a due job's schedule."""@@ -794,8 +719,6 @@ class TestRunJobSessionPersistence:"last_status": None,}- fake_db = MagicMock()-with patch("cron.scheduler._hermes_home", tmp_path), \patch("cron.scheduler.get_due_jobs", return_value=[job]), \patch("cron.scheduler.claim_job_for_fire", return_value=True), \@@ -1112,45 +1035,6 @@ class TestRunJobSessionPersistence:assert fake_db.close.call_count == 2-class TestRunJobConfigLogging:- """Verify that config.yaml parse failures are logged, not silently swallowed."""-- def test_bad_config_yaml_is_logged(self, caplog, tmp_path):- """When config.yaml is malformed, the shared config loader warns loudly (and serves the- last known-good copy instead of silently dropping the user's overrides)."""- bad_yaml = tmp_path / "config.yaml"- bad_yaml.write_text("invalid: yaml: [[[bad")-- job = {- "id": "test-job",- "name": "test",- "prompt": "hello",- }-- # Mock heavy post-yaml work so the test only exercises the warning- # path. Without these mocks, run_job continues into provider- # resolution and MCP discovery, both of which can spawn subprocesses- # / hit the network and have caused this test to time out on CI- # (>30s wall clock) under load. See PR #33661 follow-up.- 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_cli.runtime_provider.resolve_runtime_provider",- return_value={"provider": "openrouter", "api_key": "x",- "base_url": "https://example.invalid",- "api_mode": "chat_completions"}), \- patch("tools.mcp_tool_discovery.discover_mcp_tools", return_value=[]), \- 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-- with caplog.at_level(logging.WARNING):- run_job(job)-- assert any("formatting error" in r.message and "config.yaml" in r.message for r in caplog.records), \- f"Expected a config.yaml parse warning in logs, got: {[r.message for r in caplog.records]}"class TestRunJobConfigEnvVarExpansion:@@ -1311,31 +1195,6 @@ class TestRunJobConfigEnvVarExpansion:assert kwargs["model"] == "z-ai/glm-5.2"- def test_unexpanded_ref_passthrough_when_var_unset(self, tmp_path, monkeypatch):- """When the env var is not set, the literal ${VAR} is kept verbatim (not crashed)."""- (tmp_path / "config.yaml").write_text("model: ${_HERMES_TEST_CRON_UNSET_VAR}\n")- monkeypatch.delenv("_HERMES_TEST_CRON_UNSET_VAR", raising=False)-- job = {"id": "unset-job", "name": "unset var test", "prompt": "hi"}- fake_db = MagicMock()-- 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", return_value=fake_db), \- patch("hermes_cli.runtime_provider.resolve_runtime_provider",- return_value=self._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, _, _, error = run_job(job)-- assert success is True- kwargs = mock_agent_cls.call_args.kwargs- # Unresolved refs are kept verbatim — _expand_env_vars contract- assert kwargs["model"] == "${_HERMES_TEST_CRON_UNSET_VAR}"class TestRunJobModelResolution:@@ -1402,7 +1261,6 @@ class TestRunJobModelResolution:assert success is Falseassert error is not None- assert "no model configured" in error# AIAgent must never be constructed with an empty model — that's# precisely the bug we're guarding against.mock_agent_cls.assert_not_called()@@ -1533,7 +1391,7 @@ class TestSilentDelivery:"origin": {"platform": "telegram", "chat_id": "123"},}- def test_silent_response_suppresses_delivery(self, caplog):+ def test_silent_response_suppresses_delivery(self):with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \patch("cron.scheduler.claim_job_for_fire", return_value=True), \patch("cron.scheduler.run_job", return_value=(True, "# output", "[SILENT]", None)), \@@ -1541,22 +1399,10 @@ class TestSilentDelivery:patch("cron.scheduler._deliver_result") as deliver_mock, \patch("cron.scheduler.mark_job_run"):from cron.scheduler import tick- with caplog.at_level(logging.INFO, logger="cron.scheduler"):- tick(verbose=False)- deliver_mock.assert_not_called()- assert any(SILENT_MARKER in r.message for r in caplog.records)-- def test_silent_with_note_suppresses_delivery(self):- with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \- patch("cron.scheduler.claim_job_for_fire", return_value=True), \- patch("cron.scheduler.run_job", return_value=(True, "# output", "[SILENT] No changes detected", None)), \- patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \- patch("cron.scheduler._deliver_result") as deliver_mock, \- patch("cron.scheduler.mark_job_run"):- from cron.scheduler import ticktick(verbose=False)deliver_mock.assert_not_called()+def test_silent_trailing_suppresses_delivery(self):"""Agent appended [SILENT] after explanation text — must still suppress."""response = "2 deals filtered out (like<10, reply<15).\n\n[SILENT]"@@ -1647,12 +1493,8 @@ class TestSilentDelivery:tick(verbose=False)deliver_mock.assert_not_called()- mark_mock.assert_called_once_with(- "monitor-job",- False,- "Agent completed but produced empty response (model error, timeout, or misconfiguration)",- delivery_error=None,- )+ mark_mock.assert_called_once()+ assert mark_mock.call_args[0][:2] == ("monitor-job", False)class TestOneShotDispatchClaim:@@ -1697,41 +1539,9 @@ class TestOneShotDispatchClaim:mark_mock.assert_not_called()-class TestBuildJobPromptSilentHint:- """Verify _build_job_prompt always injects [SILENT] guidance."""- def test_hint_always_present(self):- job = {"prompt": "Check for updates"}- result = _build_job_prompt(job)- assert "[SILENT]" in result- assert "Check for updates" in result-class TestBuildJobPromptRecursionGuard:- """Verify _build_job_prompt tells the agent this is an execution, not a- request to schedule — recurring language in a task prompt must not spawn- another cron job (recursive scheduled tasks)."""-- def test_recursion_guard_always_present(self):- job = {"prompt": "Check for updates"}- result = _build_job_prompt(job)- assert "run of an EXISTING scheduled job" in result- assert "NEVER create or update a cron job" in result-- def test_recurring_language_treated_as_context(self):- job = {- "prompt": (- "Each Monday, review my calendar for the upcoming "- "Monday-through-Sunday week and summarize it."- )- }- result = _build_job_prompt(job)- # The guard precedes the task prompt so the model reads it first.- guard_pos = result.index("run of an EXISTING scheduled job")- task_pos = result.index("Each Monday, review my calendar")- assert guard_pos < task_pos- assert 'phrasing like "each Monday"' in result-class TestParseWakeGate:"""Unit tests for _parse_wake_gate — pure function, no side effects."""@@ -1788,7 +1598,6 @@ class TestRunJobWakeGate:"""When _run_job_script output ends with {wakeAgent: false}, the agentis not invoked and run_job returns the SILENT marker so delivery issuppressed."""- from cron.scheduler import SILENT_MARKERimport cron.scheduler as schedulerfrom cron import scheduler_script as sched_script@@ -1800,7 +1609,6 @@ class TestRunJobWakeGate:assert success is Trueassert err is Noneassert final == SILENT_MARKER- assert "Script gate returned `wakeAgent=false`" in docagent_cls.assert_not_called()def test_wake_true_runs_agent_with_injected_output(self):@@ -1985,45 +1793,6 @@ class TestParallelTick:assert len(ends) == 2assert max(starts) < min(ends), f"Jobs not concurrent: {call_order}"- def test_parallel_jobs_isolated_contextvars(self):- """Each job's ContextVars must be isolated — no cross-contamination."""- from gateway.session_context import get_session_env- seen = {}-- def mock_run_job(job, *, defer_agent_teardown=None, **kw):- origin = job.get("origin", {})- # run_job sets ContextVars — verify each job sees its own- from gateway.session_context import set_session_vars, clear_session_vars- tokens = set_session_vars(- platform=origin.get("platform", ""),- chat_id=str(origin.get("chat_id", "")),- )- import time- time.sleep(0.05) # give other thread time to set its vars- platform = get_session_env("HERMES_SESSION_PLATFORM")- chat_id = get_session_env("HERMES_SESSION_CHAT_ID")- seen[job["id"]] = {"platform": platform, "chat_id": chat_id}- clear_session_vars(tokens)- return (True, "output", "response", None)-- jobs = [- {"id": "tg-job", "name": "tg", "deliver": "local",- "origin": {"platform": "telegram", "chat_id": "111"}},- {"id": "dc-job", "name": "dc", "deliver": "local",- "origin": {"platform": "discord", "chat_id": "222"}},- ]-- with patch("cron.scheduler.get_due_jobs", return_value=jobs), \- patch("cron.scheduler.claim_job_for_fire", return_value=True), \- patch("cron.scheduler.run_job", side_effect=mock_run_job), \- patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \- patch("cron.scheduler._deliver_result", return_value=None), \- patch("cron.scheduler.mark_job_run"):- from cron.scheduler import tick- tick(verbose=False)-- assert seen["tg-job"] == {"platform": "telegram", "chat_id": "111"}- assert seen["dc-job"] == {"platform": "discord", "chat_id": "222"}def test_max_parallel_env_var(self, monkeypatch):"""HERMES_CRON_MAX_PARALLEL=1 should restore serial behaviour."""@@ -2210,7 +1979,6 @@ class TestDeliverOriginUnresolvableIsLocal:"""def _deliver(self, job, monkeypatch):- import cron.scheduler as schedfrom cron import scheduler_delivery as sched_delivery# No home channel for any platform → origin is unresolvable.monkeypatch.setattr(sched_delivery, "_get_home_target_chat_id", lambda *_: "")@@ -2335,13 +2103,6 @@ class TestCronDeliveryTargets:assert all(t["home_target_set"] for t in bot_chat)-class TestHomeTargetEnvVarRegistry:- """Regression: ``_HOME_TARGET_ENV_VARS`` must include every gateway- platform that supports cron-driven outbound delivery. Missing an- entry means ``hermes cron create --deliver=<platform>`` silently- fails to route through the platform's home channel."""--class TestCronDeliveryMirror:"""cron.mirror_delivery / per-job attach_to_session: opt-in append of acron delivery into the target chat's gateway session transcript.@@ -2412,28 +2173,6 @@ class TestCronDeliveryMirror:# --- continuable cron: thread-preferred (Teknium's interface) ---- def test_open_thread_returns_id_on_thread_platform(self):- """On a thread-capable adapter, _open_continuable_cron_thread returns- the new thread id from create_handoff_thread."""- from cron.scheduler_delivery import _open_continuable_cron_thread-- adapter = MagicMock()- adapter.create_handoff_thread = AsyncMock(return_value="9001")-- # safe_schedule_threadsafe hands the coro to the gateway loop and- # returns a future. Patch it to close the coro and return a ready- # future carrying the adapter's thread id.- def _run_now(coro, _loop):- coro.close()- fut = MagicMock()- fut.result.return_value = "9001"- return fut-- with patch("agent.async_utils.safe_schedule_threadsafe", side_effect=_run_now):- tid = _open_continuable_cron_thread(- {"id": "j1", "name": "Brief"}, adapter, "123", loop=MagicMock(),- )- assert tid == "9001"def test_seed_thread_session_creates_session_and_mirrors(self):@@ -2890,7 +2629,6 @@ class TestBuildJobPromptExtraPrompt:job = {"prompt": "stored prompt"}result = _build_job_prompt(job, extra_prompt="CONTEXT: client=Foo")assert "stored prompt" in result- assert "## Run Context" in resultassert "CONTEXT: client=Foo" in resultdef test_extra_prompt_does_not_mutate_job(self):@@ -2899,12 +2637,6 @@ class TestBuildJobPromptExtraPrompt:_build_job_prompt(job, extra_prompt="transient context")assert job["prompt"] == "original"- def test_no_extra_prompt_omits_header(self):- """Without extra_prompt, no '## Run Context' header is injected."""- job = {"prompt": "just the stored prompt"}- result = _build_job_prompt(job)- assert "## Run Context" not in result- assert "just the stored prompt" in resultclass TestSetCronSessionTitle:@@ -2935,13 +2667,6 @@ class TestFailureStreakNudge:"schedule": {"kind": kind},}- def test_nudges_at_threshold(self):- from cron.scheduler import _failure_streak_nudge- # stored streak 2 + this run = 3 >= default threshold 3- with patch("cron.scheduler.load_config", return_value={}):- out = _failure_streak_nudge(self._job(2))- assert "failed 3 runs in a row" in out- assert "hermes cron pause scout" in outdef test_silent_below_threshold(self):from cron.scheduler import _failure_streak_nudge@@ -2959,7 +2684,7 @@ class TestFailureStreakNudge:cfg5 = {"cron": {"failure_nudge_threshold": 5}}with patch("cron.scheduler.load_config", return_value=cfg5):assert _failure_streak_nudge(self._job(3)) == ""- assert "failed 5 runs" in _failure_streak_nudge(self._job(4))+ assert _failure_streak_nudge(self._job(4))with patch("cron.scheduler.load_config", return_value={"cron": {"failure_nudge_threshold": 0}}):assert _failure_streak_nudge(self._job(50)) == ""@@ -2969,7 +2694,3 @@ class TestFailureStreakNudge:with patch("cron.scheduler.load_config", return_value={}):assert _failure_streak_nudge(job) == ""- def test_config_load_failure_falls_back(self):- from cron.scheduler import _failure_streak_nudge- with patch("cron.scheduler.load_config", side_effect=RuntimeError("boom")):- assert "failed 3 runs" in _failure_streak_nudge(self._job(2))diff --git a/tests/cron/test_scheduler_mcp_init.py b/tests/cron/test_scheduler_mcp_init.pydeleted file mode 100644index 9f46cfbec69..00000000000--- a/tests/cron/test_scheduler_mcp_init.py+++ /dev/null@@ -1,53 +0,0 @@-"""Regression tests for MCP server availability in cron jobs.--Background-==========-``cron/scheduler.py:run_job()`` constructs ``AIAgent(...)`` directly without-calling ``discover_mcp_tools()`` — the initialization that CLI and gateway-paths do at startup. Cron jobs therefore never saw any MCP tools from-``mcp_servers`` in config.yaml. See #4219.--The fix inserts ``discover_mcp_tools()`` before the ``AIAgent(...)`` call,-wrapped in try/except so a broken MCP server can't kill an otherwise-working cron job. ``discover_mcp_tools`` is idempotent — subsequent ticks-short-circuit on already-connected servers.-"""--from __future__ import annotations--from unittest.mock import patch--------def test_no_agent_cron_job_does_not_initialize_mcp():- """Cron jobs with no_agent=True are script-only — no AIAgent, no MCP- tools needed. We must NOT pay the MCP init cost for those."""- from cron import scheduler-- job = {- "id": "noagent-job",- "name": "noagent-job",- "no_agent": True,- "script": "/nonexistent/script.sh",- }-- discover_called = []-- def fake_discover():- discover_called.append(True)- return []-- # _run_job_script returns (ok, output); make it fail cleanly so we- # don't need a real script file.- with patch("tools.mcp_tool_discovery.discover_mcp_tools", side_effect=fake_discover), \- patch("cron.scheduler_script._run_job_script", return_value=(False, "no such file")):- scheduler.run_job(job)-- assert not discover_called, (- "discover_mcp_tools was called for a no_agent job — wasted MCP init "- "for a script-only cron tick"- )diff --git a/tests/cron/test_scheduler_provider.py b/tests/cron/test_scheduler_provider.pyindex 88549f7ca49..8995fc03721 100644--- a/tests/cron/test_scheduler_provider.py+++ b/tests/cron/test_scheduler_provider.py@@ -104,13 +104,6 @@ def test_desktop_ticker_calls_tick_then_stops():# ── Phase 1: CronScheduler ABC + InProcessCronScheduler ──────────────────────-def test_cronscheduler_is_abstract():- """name + start are abstract — the bare ABC can't be instantiated."""- import pytest- from cron.scheduler_provider import CronScheduler-- with pytest.raises(TypeError):- CronScheduler()def test_abc_growth_stays_additive():@@ -193,29 +186,10 @@ def test_inprocess_provider_ticks_and_stops():# ── Phase 2: config key, discovery, resolver ─────────────────────────────────-def test_default_config_cron_provider_is_empty():- """The new cron.provider key defaults to empty (= built-in)."""- from hermes_cli.config import DEFAULT_CONFIG-- assert DEFAULT_CONFIG["cron"]["provider"] == ""---def test_discover_cron_schedulers_returns_list():- """Discovery returns bundled non-default providers.-- The built-in is core, not discovered here.- """- from plugins.cron_providers import discover_cron_schedulers- result = discover_cron_schedulers()- assert isinstance(result, list)- assert any(name == "chronos" for name, _desc, _available in result)-def test_load_unknown_cron_scheduler_returns_none():- from plugins.cron_providers import load_cron_scheduler- assert load_cron_scheduler("does-not-exist-xyz") is Nonedef test_cron_provider_package_does_not_shadow_core_cron_package(monkeypatch):@@ -342,24 +316,8 @@ def test_external_provider_falls_back_to_builtin_under_multiplex():# ── Phase 4B: additive hooks (on_jobs_changed / fire_due / reconcile) ────────-def test_hooks_did_not_change_required_surface():- """The additive hooks must NOT become abstractmethods — the Phase-1 guard- still holds (required surface is exactly name + start)."""- from cron.scheduler_provider import CronScheduler-- assert set(CronScheduler.__abstractmethods__) == {"name", "start"}--def test_builtin_inherits_hook_defaults():- """The built-in inherits no-op defaults for the new hooks (it never needs- to override them)."""- from cron.scheduler_provider import InProcessCronScheduler- p = InProcessCronScheduler()- assert p.on_jobs_changed() is None- assert p.reconcile() is None- # built-in does not override fire_due; it simply isn't called for built-in.- assert hasattr(p, "fire_due")def test_fire_due_default_claims_then_runs(monkeypatch):@@ -465,23 +423,6 @@ def test_fire_due_lost_claim_does_not_run(monkeypatch):assert ran == []-def test_fire_due_missing_job_does_not_run(monkeypatch):- """If the job vanished before atomic claim, fire_due does not run it."""- import cron.jobs as jobs- import cron.scheduler as sched- from cron.scheduler_provider import InProcessCronScheduler-- ran = []- monkeypatch.setattr(- jobs,- "claim_job_for_fire",- lambda jid, **kw: False,- raising=False,- )- monkeypatch.setattr(sched, "run_one_job", lambda job, **kw: ran.append(job["id"]) or True)-- assert InProcessCronScheduler().fire_due("gone") is False- assert ran == []# ── F2a: ticker liveness — survival, heartbeat, honest status (#32612, #32895) ──diff --git a/tests/cron/test_scheduler_shutdown_guard.py b/tests/cron/test_scheduler_shutdown_guard.pyindex 117b480ace2..fad3c15e8bf 100644--- a/tests/cron/test_scheduler_shutdown_guard.py+++ b/tests/cron/test_scheduler_shutdown_guard.py@@ -15,24 +15,12 @@ sites so they skip gracefully with a warning instead of raising.from __future__ import annotations-import sysfrom unittest.mock import AsyncMock, MagicMock, patch-import pytestclass TestInterpreterShuttingDownHelper:- def test_true_when_finalizing(self):- from cron.scheduler import _interpreter_shutting_down-- with patch("sys.is_finalizing", return_value=True):- assert _interpreter_shutting_down() is True- def test_false_when_not_finalizing_and_no_exc(self):- from cron.scheduler import _interpreter_shutting_down-- with patch("sys.is_finalizing", return_value=False):- assert _interpreter_shutting_down() is Falsedef test_matches_shutdown_error_text_as_fallback(self):"""The concurrent.futures module-global flag can be set a hair before@@ -83,39 +71,8 @@ class TestStandaloneDeliverySkipsDuringShutdown:send_mock.assert_not_called()assert result is not None- assert "shutting down" in result-- def test_normal_delivery_still_works_when_not_finalizing(self):- """Guard must not regress the happy path: a normal (non-finalizing)- run still delivers via the standalone send."""- from cron.scheduler import _deliver_result-- job = {- "id": "gov-job",- "name": "model-governor",- "deliver": "origin",- "origin": {"platform": "telegram", "chat_id": "123"},- }- send_mock = AsyncMock(return_value={"success": True})- with patch("gateway.config.load_gateway_config", return_value=self._telegram_cfg()), \- patch("tools.send_message_tool._send_to_platform", new=send_mock), \- patch("sys.is_finalizing", return_value=False):- result = _deliver_result(job, "daily report body")-- send_mock.assert_called_once()- assert result is None--class TestSourceGuardrail:- @pytest.fixture- def source(self) -> str:- from pathlib import Path- return (- Path(__file__).resolve().parents[2] / "cron" / "scheduler.py"- ).read_text(encoding="utf-8")- def test_helper_defined(self, source):- assert "def _interpreter_shutting_down(" in sourcediff --git a/tests/cron/test_sessiondb_init_hang.py b/tests/cron/test_sessiondb_init_hang.pyindex 56c0c31982a..2189d15407b 100644--- a/tests/cron/test_sessiondb_init_hang.py+++ b/tests/cron/test_sessiondb_init_hang.py@@ -154,43 +154,6 @@ class TestSessionDbInitTimeout:assert final_response == "ok"assert mock_agent_cls.call_args.kwargs["session_db"] is None- def test_invalid_timeout_env_falls_back_to_default(self, tmp_path, monkeypatch, caplog):- """A malformed HERMES_CRON_SESSION_DB_TIMEOUT logs a warning and still- bounds the call (mirrors HERMES_CRON_TIMEOUT's own fallback)."""- monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "not-a-number")- fake_db = MagicMock()- job = {"id": "bad-timeout-env", "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", return_value=fake_db), \- 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, instant_timeout=False),- ):- mock_agent = MagicMock()- mock_agent.run_conversation.return_value = {"final_response": "ok"}- mock_agent_cls.return_value = mock_agent-- with caplog.at_level("WARNING"):- success, output, final_response, error = run_job(job)-- # Invalid env → fall back to default 10s bound (still passed to result).- assert timeouts == [10.0]- assert success is True- assert mock_agent_cls.call_args.kwargs["session_db"] is fake_db- assert any(- "HERMES_CRON_SESSION_DB_TIMEOUT" in rec.message- for rec in caplog.records- ), f"Expected warning about invalid timeout env var; got: {[r.message for r in caplog.records]}"def test_timeout_resolved_from_config_yaml(self, tmp_path, monkeypatch):"""cron.session_db_timeout_seconds in config.yaml is respected when@@ -299,40 +262,6 @@ class TestDispatchGuardReleasedAfterHang:# Bug #72782: late SessionDB result leaks FDs after timeout abandonment# ===========================================================================-class TestCloseLateSessionDbResult:- """Unit tests for the done-callback that closes a SessionDB whose- constructor completed after run_job's timeout."""-- def test_closes_db_from_completed_future(self):- """A completed future holding a SessionDB is closed."""- import concurrent.futures- from cron.scheduler import _close_late_session_db_result-- mock_db = MagicMock()- fut = concurrent.futures.Future()- fut.set_result(mock_db)-- _close_late_session_db_result(fut)-- mock_db.close.assert_called_once()-- def test_safe_when_result_is_none(self):- """No error when the future's result is None."""- import concurrent.futures- from cron.scheduler import _close_late_session_db_result-- fut = concurrent.futures.Future()- fut.set_result(None)- _close_late_session_db_result(fut) # must not raise-- def test_safe_when_future_raised(self):- """No error when the future itself raised (e.g. connect failed)."""- import concurrent.futures- from cron.scheduler import _close_late_session_db_result-- fut = concurrent.futures.Future()- fut.set_exception(RuntimeError("connect failed"))- _close_late_session_db_result(fut) # must not raiseclass TestLateSessionDbClosedAfterTimeout:diff --git a/tests/cron/test_shutdown_interrupt.py b/tests/cron/test_shutdown_interrupt.pyindex 81571333d54..b522d72deb2 100644--- a/tests/cron/test_shutdown_interrupt.py+++ b/tests/cron/test_shutdown_interrupt.py@@ -33,10 +33,6 @@ def _reset_scheduler_state():class TestGetRunningJobIds:- def test_empty_when_nothing_running(self):- import cron.scheduler as sched-- assert sched.get_running_job_ids() == frozenset()def test_reflects_in_flight_jobs(self):import cron.scheduler as sched@@ -260,17 +256,7 @@ class TestIsInterrupted:"""Peek-only check used at the delivery gate -- must NOT clear theflag, unlike _consume_interrupted_flag."""- def test_false_when_not_marked(self):- import cron.scheduler as sched- assert sched._is_interrupted("job-1") is False-- def test_true_when_marked(self):- import cron.scheduler as sched-- sched._interrupted_job_ids.add(sched._inflight_key("job-1"))-- assert sched._is_interrupted("job-1") is Truedef test_does_not_clear_the_flag(self):import cron.scheduler as scheddiff --git a/tests/cron/test_stale_module_leaf_imports.py b/tests/cron/test_stale_module_leaf_imports.pyindex 2b58428ef25..63bd63a926e 100644--- a/tests/cron/test_stale_module_leaf_imports.py+++ b/tests/cron/test_stale_module_leaf_imports.py@@ -7,9 +7,7 @@ These tests model the field failure directly: a foundational module remains infrom __future__ import annotations-import importlibimport logging-import sysfrom types import SimpleNamespace@@ -54,22 +52,3 @@ def test_primary_client_ignores_stale_auxiliary_router(monkeypatch):assert captured["default_headers"]["originator"] == "hermes-agent"-def test_docker_import_ignores_stale_base_environment(monkeypatch):- from tools.environments import base- from tools.environments.path_utils import sanitize_task_id_for_path-- # base.py no longer defines the sanitizer at all (it lives in the leaf module); a Docker- # module imported later by tool discovery must bind the helper from that leaf, never- # from base's namespace.- assert "sanitize_task_id_for_path" not in vars(base)- previous = sys.modules.pop("tools.environments.docker", None)- try:- docker = importlib.import_module("tools.environments.docker")- assert docker._sandbox_dir_name is sanitize_task_id_for_path- assert docker._sandbox_dir_name("session:cron:job") == sanitize_task_id_for_path(- "session:cron:job"- )- finally:- sys.modules.pop("tools.environments.docker", None)- if previous is not None:- sys.modules["tools.environments.docker"] = previousdiff --git a/tests/cron/test_suggestions.py b/tests/cron/test_suggestions.pyindex 3abaf54d313..2267db6c876 100644--- a/tests/cron/test_suggestions.py+++ b/tests/cron/test_suggestions.py@@ -6,8 +6,6 @@ HERMES_HOME so the real suggestions.json is never touched."""import importlib-import json-from pathlib import Pathfrom unittest.mock import patchimport pytest@@ -194,17 +192,14 @@ class TestCatalog:assert len(store.list_pending()) == min(len(CATALOG), store.MAX_PENDING)- def test_monitor_entry_references_classifier_script(self):+ def test_no_catalog_prompt_bakes_in_absolute_script_path(self):from cron.suggestion_catalog import CATALOG, classify_items_script_path- monitor = next(e for e in CATALOG if e.key == "catalog:important-mail-monitor")- # The prompt must reference the classifier by module path (resolvable- # at run time on any backend), never by a baked-in absolute path —- # absolute paths go stale after relocation and don't exist on remote- # terminal backends (Docker/Modal).- assert "cron.scripts.classify_items" in monitor.job_spec["prompt"]- assert classify_items_script_path() not in monitor.job_spec["prompt"]- assert Path(classify_items_script_path()).name == "classify_items.py"+ # Absolute install paths go stale after relocation and don't exist on+ # remote terminal backends (Docker/Modal); prompts must reference+ # scripts by module path instead.+ for entry in CATALOG:+ assert classify_items_script_path() not in entry.job_spec.get("prompt", ""), entry.keyclass TestBlueprintBridge:@@ -231,14 +226,4 @@ class TestCommandHandler:assert "Daily thing" in out- def test_empty_list_message(self, store):- from hermes_cli.suggestions_cmd import handle_suggestions_command- out = handle_suggestions_command("")- assert "No suggested automations" in out-- def test_aux_monitor_config_default(self):- from hermes_cli.config import DEFAULT_CONFIG-- assert "monitor" in DEFAULT_CONFIG["auxiliary"]- assert DEFAULT_CONFIG["auxiliary"]["monitor"]["provider"] == "auto"diff --git a/tests/cron/test_terminal_job_rearm.py b/tests/cron/test_terminal_job_rearm.pyindex 3f4afe1eb65..d6e84a39c3f 100644--- a/tests/cron/test_terminal_job_rearm.py+++ b/tests/cron/test_terminal_job_rearm.py@@ -88,15 +88,6 @@ def test_terminal_jobs_are_not_due_or_advanced(tmp_cron_dir):assert load_jobs() == before-def test_terminal_refusal_survives_reload(tmp_cron_dir):- job = create_job("done", "in 30m", repeat=1)- mark_job_run(job["id"], success=True)- before = copy.deepcopy(load_jobs())- assert get_job(job["id"])["state"] == "completed"-- with pytest.raises(ValueError):- trigger_job(job["id"])- assert load_jobs() == beforedef test_update_cannot_reactivate_terminal_record(tmp_cron_dir):@@ -109,7 +100,6 @@ def test_update_cannot_reactivate_terminal_record(tmp_cron_dir):def test_rearm_completed_oneshot_restores_schedule_and_preserves_history(tmp_cron_dir):- from cron.jobs import rearm_oneshotjob = create_job("done", "in 30m", repeat=3)mark_job_run(job["id"], success=True)@@ -128,7 +118,6 @@ def test_rearm_completed_oneshot_restores_schedule_and_preserves_history(tmp_crodef test_rearm_refuses_recurring_and_live_claim(tmp_cron_dir):- from cron.jobs import rearm_oneshotrecurring = create_job("recurring", "every 1h")future = (datetime.now(timezone.utc) + timedelta(minutes=5)).isoformat()diff --git a/tests/cron/test_ticker_stall.py b/tests/cron/test_ticker_stall.pyindex db9828c423a..8532bbdd0e5 100644--- a/tests/cron/test_ticker_stall.py+++ b/tests/cron/test_ticker_stall.py@@ -15,8 +15,6 @@ Three fixes under test:"already being fired"."""-import json-import osimport threadingimport timefrom datetime import timedelta@@ -29,7 +27,6 @@ from cron.jobs import (_jobs_lock,claim_job_for_fire,create_job,- get_due_jobs,get_job,load_jobs,save_jobs,@@ -91,21 +88,13 @@ class TestBoundedJobsLock:assert entered, "critical section must still run in degraded mode"assert elapsed < 10, f"lock wait was not bounded (took {elapsed:.1f}s)"- assert any("Timed out" in r.message for r in caplog.records), (+ assert any(r.levelname == "ERROR" for r in caplog.records), ("degraded-mode fallback must be logged at ERROR")finally:release.set()holder.join(timeout=10)- def test_uncontended_lock_is_fast_and_silent(self, caplog):- jobs_mod.ensure_dirs()- start = time.monotonic()- with caplog.at_level("ERROR", logger="cron.jobs"):- with _jobs_lock():- pass- assert time.monotonic() - start < 5- assert not [r for r in caplog.records if "Timed out" in r.message]def test_reentrant_nesting_still_works(self):with _jobs_lock():diff --git a/tests/cron/test_timezone.py b/tests/cron/test_timezone.pyindex c4dfa320a58..09e0b86593d 100644--- a/tests/cron/test_timezone.py+++ b/tests/cron/test_timezone.py@@ -10,12 +10,10 @@ Covers:"""import os-import loggingimport sysimport pytestfrom datetime import datetime, timedelta, timezonefrom unittest.mock import patch-from zoneinfo import ZoneInfoimport hermes_time@@ -48,20 +46,7 @@ class TestHermesTimeNow:offset = result.utcoffset()assert offset == timedelta(hours=5, minutes=30)- def test_utc_timezone(self):- """UTC timezone works."""- os.environ["HERMES_TIMEZONE"] = "UTC"- result = hermes_time.now()- assert result.utcoffset() == timedelta(0)- def test_us_eastern(self):- """US/Eastern timezone works (DST-aware zone)."""- os.environ["HERMES_TIMEZONE"] = "America/New_York"- result = hermes_time.now()- assert result.tzinfo is not None- # Offset is -5h or -4h depending on DST- offset_hours = result.utcoffset().total_seconds() / 3600- assert offset_hours in {-5, -4}@@ -78,11 +63,6 @@ class TestGetTimezone:_reset_hermes_time_cache()os.environ.pop("HERMES_TIMEZONE", None)- def test_returns_zoneinfo_for_valid(self):- os.environ["HERMES_TIMEZONE"] = "Europe/London"- tz = hermes_time.get_timezone()- assert isinstance(tz, ZoneInfo)- assert str(tz) == "Europe/London"def test_cache_isolated_by_active_profile_config(self, tmp_path, monkeypatch):"""Switching HERMES_HOME must not reuse another profile's timezone."""@@ -249,19 +229,6 @@ class TestCodeExecutionTZ:"HERMES_TIMEZONE should not leak into child env (only TZ)")- def test_tz_not_injected_when_empty(self):- """When HERMES_TIMEZONE is not set, child process has no TZ."""- import json as _json- os.environ.pop("HERMES_TIMEZONE", None)-- with patch("model_tools.handle_function_call", side_effect=self._mock_handle):- result = _json.loads(self._execute_code(- code='import os; print(os.environ.get("TZ", "NOT_SET"))',- task_id="tz-test-empty",- enabled_tools=[],- ))- assert result["status"] == "success"- assert "NOT_SET" in result["output"]# =========================================================================@@ -287,14 +254,6 @@ class TestCronTimezone:# The stored timestamp should be tz-awareassert run_at.tzinfo is not None- def test_compute_next_run_tz_aware(self):- """compute_next_run returns tz-aware timestamps."""- os.environ["HERMES_TIMEZONE"] = "Asia/Kolkata"- from cron.jobs import compute_next_run- schedule = {"kind": "interval", "minutes": 60}- result = compute_next_run(schedule)- next_dt = datetime.fromisoformat(result)- assert next_dt.tzinfo is not Nonedef test_ensure_aware_naive_preserves_absolute_time(self):diff --git a/tests/cron/test_usage_audit_logger.py b/tests/cron/test_usage_audit_logger.pyindex 2b39c99ddea..70355f1655f 100644--- a/tests/cron/test_usage_audit_logger.py+++ b/tests/cron/test_usage_audit_logger.py@@ -39,12 +39,6 @@ class TestUsageAuditPath:p = scheduler._usage_audit_path()assert p == tmp_hermes_home / "cron" / "usage_audit.jsonl"- def test_does_not_use_path_home(self, tmp_hermes_home):- """Audit path must NOT hardcode Path.home() — it bypasses profile-aware resolution."""- with patch.object(Path, "home") as mock_home:- p = scheduler._usage_audit_path()- mock_home.assert_not_called()- assert p == tmp_hermes_home / "cron" / "usage_audit.jsonl"class TestUtcnowIsoMs:@@ -77,37 +71,14 @@ class TestWriteUsageAudit:assert len(lines) == 1assert lines[0] == record- def test_missing_token_info_writes_line_with_null_fields(self, tmp_hermes_home):- record = {- "ts": "2026-05-01T04:23:11.123Z",- "job_id": "j",- "fire_id": "f",- "prompt_tokens": None,- "completion_tokens": None,- "total_tokens": None,- "response_silent": True,- "deliver_target": "telegram",- "model": None,- "duration_ms": 12,- "error": "boom",- }- scheduler._write_usage_audit(record)- lines = _read_jsonl(scheduler._usage_audit_path())- assert len(lines) == 1- assert lines[0]["prompt_tokens"] is None- assert lines[0]["completion_tokens"] is None- assert lines[0]["total_tokens"] is None- assert lines[0]["error"] == "boom"- def test_writer_exception_swallowed(self, tmp_hermes_home, caplog):+ def test_writer_exception_swallowed(self, tmp_hermes_home):# Force json.dumps to raise — writer must NOT propagate.with patch("cron.scheduler.json.dumps", side_effect=RuntimeError("kaboom")):scheduler._write_usage_audit({"job_id": "x"})# File never created.assert not scheduler._usage_audit_path().exists()- # Warning logged with our marker.- assert any("usage_audit write failed" in rec.message for rec in caplog.records)def test_parent_dir_created_if_missing(self, tmp_hermes_home):# Ensure the cron path does not exist yet.diff --git a/tests/dashboard/test_ws_client_host.py b/tests/dashboard/test_ws_client_host.pyindex f5c1883599b..85d6bd4bd7b 100644--- a/tests/dashboard/test_ws_client_host.py+++ b/tests/dashboard/test_ws_client_host.py@@ -21,7 +21,6 @@ The contract these tests pin down:from __future__ import annotations-import osimport pytest@@ -65,15 +64,6 @@ def _set_bound(saved_app_state, host: str, port: int = 9119):web_server.app.state.auth_required = False-def _netloc(ws_url: str) -> str:- """Pull the ``host:port`` (or ``[host]:port``) segment out of a ws URL."""- assert ws_url is not None, "expected a URL, got None"- # ws://host:port/path?qs — strip the scheme, then take netloc up to "/".- after_scheme = ws_url.split("://", 1)[1]- netloc = after_scheme.split("/", 1)[0]- return netloc--# ---------------------------------------------------------------------------# _resolve_client_ws_host — direct unit tests# ---------------------------------------------------------------------------@@ -98,8 +88,6 @@ class TestResolveClientWsHost:assert _web_server_chat._resolve_client_ws_host() == "fly-app.example.dev"--def test_blank_env_falls_back_to_bind(self, saved_app_state, monkeypatch):@@ -111,17 +99,6 @@ class TestResolveClientWsHost:assert _web_server_chat._resolve_client_ws_host() == "127.0.0.1"- def test_bind_host_unchanged_after_wildcard_resolution(- self, saved_app_state, clear_ws_host_env- ):- """Resolution only affects the client netloc — ``bound_host`` on- ``app.state`` (used by the listener and host-header middleware) is- NOT mutated."""- _set_bound(saved_app_state, "0.0.0.0")- _web_server_chat._resolve_client_ws_host()- assert web_server.app.state.bound_host == "0.0.0.0"--# ---------------------------------------------------------------------------# _build_gateway_ws_url — end-to-end URL contract# ---------------------------------------------------------------------------@@ -140,12 +117,6 @@ class TestGatewayWsUrlHost:assert "::" not in url------# ---------------------------------------------------------------------------# _build_sidecar_url — end-to-end URL contract# ---------------------------------------------------------------------------@@ -154,28 +125,9 @@ class TestGatewayWsUrlHost:class TestSidecarUrlHost:----def test_no_bound_host_returns_none(self, saved_app_state, clear_ws_host_env):web_server.app.state.bound_host = Noneweb_server.app.state.bound_port = Noneassert _web_server_chat._build_sidecar_url("ch-1") is None---# ----------------------------------------------------------------------------# _netloc helper is exposed only because it's useful for tests; if the-# production code ever changes the URL shape the tests catch the regression-# above without needing to assert on the full string.-# ------------------------------------------------------------------------------def test_netloc_helper_handles_ipv6_bracket_form():- """The IPv6 netloc path is exercised by the production ``[host]:port``- branch when ``HERMES_DASHBOARD_WS_HOST`` points at an IPv6 address.- Verify the helper doesn't choke on the bracket form."""- assert _netloc("ws://[::1]:9119/api/ws?x=1") == "[::1]:9119"- assert _netloc("ws://127.0.0.1:9119/api/ws?x=1") == "127.0.0.1:9119"\ No newline at end of filediff --git a/tests/desktop/test_bots_chat_live_append.py b/tests/desktop/test_bots_chat_live_append.pydeleted file mode 100644index b57be0d4c37..00000000000--- a/tests/desktop/test_bots_chat_live_append.py+++ /dev/null@@ -1,79 +0,0 @@-"""Regression tests for #93942 slice 1 — Bot Mode open chat pane never picks-up background deliveries.--Mechanism (traced on 85a55e2b30-era main, re-verified through 03b87d666d):--* Background DMs deliver via a separate ``hermes -p <profile> chat``- subprocess (``tools/bot_relay.py::local_delivery_command``) that writes the- turn straight to the session DB. No gateway stream event reaches the desktop.-* The gateway broadcasts ``sessions.changed`` on state.db mtime movement, and- the desktop's tick handler calls ``requestActiveTranscriptRefresh(true)`` —- but that refresh covers ONLY the MAIN pane's selection- (``activeStoredSessionId = selectedStoredSessionId``, wiring.tsx).-* Bot canonical chats open as workspace tiles (``workspaceMode: 'bots'``,- never the main selection), AND ``resolveActiveTranscriptSession()`` bails- when the session is absent from ``$sessions``/``$messagingSessions`` — which- bot chats always are (they carry the core ``hidden`` flag,- plugin.js "Bot Mode sessions are ALWAYS hidden").--Double exclusion ⇒ the sessions.changed refresh silently no-ops for exactly-the conversation the user is staring at.--Fix contract (slice 1): the sessions.changed tick must also reconcile the-transcripts of VISIBLE workspace tiles — signature-gated like the main pane,-keyed off each tile's stored↔runtime id pair — without touching messaging-polls, roster cadence, or the main-pane path.-"""--from __future__ import annotations--import re-from pathlib import Path---def _bg_sync_source() -> str:- return (- Path(__file__).resolve().parents[2]- / "apps"- / "desktop"- / "src"- / "app"- / "contrib"- / "hooks"- / "use-background-sync.ts"- ).read_text(encoding="utf-8")---def test_sessions_changed_tick_covers_workspace_tiles():- """The $sessionsChangeTick listener must refresh tile transcripts too, not- only the main pane's active transcript."""- src = _bg_sync_source()-- # Locate the tick listener block.- m = re.search(r"\$sessionsChangeTick\.listen\(", src)- assert m, "sessions.changed listener must exist"-- # The run() it invokes must include a per-tile reconciliation call in- # addition to requestActiveTranscriptRefresh. Pre-fix, `run()` touches- # refreshSessions/refreshMessagingSessions/requestActiveTranscriptRefresh- # only — no tile path.- run_start = src.rfind("const run = () => {", 0, m.start())- body = src[run_start : src.find("}", m.start())]-- assert re.search(r"[Tt]ile", body), (- "pre-fix state: sessions.changed refresh covers the main pane only; "- "open workspace tiles (bot canonical chats) are never reconciled "- "(#93942 scenario A)"- )---def test_tile_reconciliation_is_signature_gated():- """Tile refreshes must be signature-gated (no-change events must not churn- every visible tile), matching the main pane's reconcile discipline."""- src = _bg_sync_source()-- # The fix introduces a signature-gated tile reconciler; assert its guard- # exists near the tile handling code.- assert re.search(r"[Tt]ile[A-Za-z]*Signature|signature.*tile", src, re.IGNORECASE) or (- "signatureRef" in src and "[Tt]ile" in src- ), "tile reconciliation must be signature-gated like the main pane path"diff --git a/tests/desktop/test_bots_chat_stream_rekey.py b/tests/desktop/test_bots_chat_stream_rekey.pydeleted file mode 100644index 27c6e715074..00000000000--- a/tests/desktop/test_bots_chat_stream_rekey.py+++ /dev/null@@ -1,117 +0,0 @@-"""Regression tests for #93942 slice 2 — open chat pane never follows a runtime-rebuild after a mid-conversation model switch.--Mechanism (traced on 41447a6d70):--* A mid-conversation model/provider switch rebuilds the agent runtime. The- rebuilt runtime emits its ``session.info`` (and all later stream events)- under a NEW explicit ``session_id``; the old id is dead.-* The pane's identity is the pair ``(activeSessionIdRef, selectedStoredSessionIdRef)``.- After the rebuild, incoming events carry an explicit sid that no longer- equals ``activeSessionIdRef.current``, so ``isActiveEvent`` is False for every- subsequent event of the SAME conversation — view-scoped side effects stop,- and the pane keeps listening on a dead runtime until a full resume.-* Existing machinery covers compression rotation only:- ``ensureSessionState`` fires the stored-id rotation signal when the SAME- runtime's stored id rotates — but a model-switch rebuild produces a NEW- runtime with a NEW stored id, which is invisible to that path.--Fix contract: when a ``session.info`` event's lineage-(``sessionMatchesStoredId`` on ``stored_session_id``) matches the currently-selected conversation but its runtime id differs from the active one, re-bind-the pane: adopt the new runtime id as the active session id (keeping the same-durable selection), so live events keep flowing to the view without a resume.-Guarded to only fire when the old runtime is dead (no busy/streaming state) so-an overlapping turn is never hijacked mid-flight.--Together with #94255 (slice 1), this closes #93942.-"""--from __future__ import annotations--import re-from pathlib import Path--ROOT = Path(__file__).resolve().parents[2] / "apps" / "desktop" / "src"---def _session_info_source() -> str:- return (- ROOT / "app" / "session" / "hooks" / "use-message-stream" / "gateway-event" / "session-info.ts"- ).read_text(encoding="utf-8")---def test_session_info_rebinds_pane_to_rebuilt_runtime():- """A session.info whose lineage matches the selected conversation but whose- runtime id differs from the active one must trigger the re-bind path."""- src = _session_info_source()-- # The fix adds a lineage-checked re-bind call in handleSessionInfoEvent,- # distinct from the cwd-claim helper (#71254). Pre-fix there is exactly one- # sessionInfoDescribesSelectedSession use site (cwd claim); post-fix a- # second consumer exists for the re-bind.- uses = len(re.findall(r"sessionInfoDescribesSelectedSession\(", src))-- assert uses >= 3, (- "pre-fix state: session.info lineage matching is used only for the cwd "- "claim; a rebuilt runtime (model switch) under a new session_id is "- "never adopted back into the open pane (#93942 scenario B)"- )---def test_rebind_is_guarded_against_live_turns():- """The re-bind must not hijack a conversation while its OLD runtime is- still streaming/busy — only a dead runtime may be adopted over."""- src = _session_info_source()-- # Locate the rebind helper's body precisely, then assert its guard inside.- fn = re.search(- r"function maybeRebindPaneToRebuiltRuntime\([^)]*\): boolean \{", src- )- assert fn, (- "pre-fix state: no maybeRebindPaneToRebuiltRuntime adoption path "- "exists; the rebuilt runtime is never adopted into the open pane"- )-- body_start = fn.end()- next_fn = min(- (i for i in (src.find("\nfunction ", body_start), src.find("\nexport function ", body_start)) if i != -1),- default=-1,- )- assert next_fn != -1, "re-anchor needed: rebind helper is no longer followed by another function"-- body = src[body_start:next_fn]-- # The busy/awaiting/streaming guard must appear INSIDE the helper body —- # not merely somewhere in the file (fixes the precedence hazard the- # #94417 review flagged in the original draft of this assertion).- guard = re.search(r"oldState\?\.(busy|awaitingResponse|streamId)", body)-- assert guard, (- "the re-bind helper must check the outgoing runtime's busy/streaming "- "state before switching; adopting over a live turn would split one "- "conversation across two panes"- )---def test_rebind_requires_stored_session_id_lineage():- """The gateway always stamps stored_session_id on session.info (server.py:- 'stored_session_id': session_key or ''), but an empty string must NOT be- adopted as lineage proof — only a real stored id may trigger the re-bind."""- src = _session_info_source()-- fn = re.search(r"function maybeRebindPaneToRebuiltRuntime\([^)]*\): boolean \{", src)- assert fn, "rebind helper missing"- body_start = fn.end()- body = src[body_start : min(- (i for i in (src.find("\nfunction ", body_start), src.find("\nexport function ", body_start)) if i != -1),- default=-1,- )]-- # The early return guards on the field being a non-empty usable string via- # the typeof check + downstream sessionInfoDescribesSelectedSession('' →- # null → wildcard refusal).- assert 'typeof payload?.stored_session_id !== "string"' in body or (- "typeof payload?.stored_session_id !== 'string'" in body- ), "rebind must refuse events without a string stored_session_id"-diff --git a/tests/docker/test_config_migration.py b/tests/docker/test_config_migration.pyindex c526476fb02..5dfa9919b02 100644--- a/tests/docker/test_config_migration.py+++ b/tests/docker/test_config_migration.py@@ -6,7 +6,7 @@ user."""from __future__ import annotations-from tests.docker.conftest import docker_exec, docker_exec_sh, start_container+from tests.docker.conftest import docker_exec_sh, start_containerdef test_config_migration_runs_on_boot(@@ -27,17 +27,6 @@ def test_config_migration_runs_on_boot(f"config.yaml not found in $HERMES_HOME: {r.stdout}")- # Verify the migration script exists in the image- r = docker_exec_sh(- container_name,- "test -f /opt/hermes/scripts/docker_config_migrate.py && "- "echo SCRIPT_EXISTS || echo SCRIPT_MISSING",- timeout=10,- )- assert "SCRIPT_EXISTS" in r.stdout, (- f"docker_config_migrate.py not found in image: {r.stdout}"- )-# Verify config.yaml is owned by hermes (migration ran as hermes)r = docker_exec_sh(container_name,diff --git a/tests/docker/test_container_restart.py b/tests/docker/test_container_restart.pyindex 6cc458a2b30..dd38bba8f67 100644--- a/tests/docker/test_container_restart.py+++ b/tests/docker/test_container_restart.py@@ -17,11 +17,10 @@ the conftest module docstring.from __future__ import annotationsimport subprocess-import timeimport pytest-from tests.docker.conftest import docker_exec, docker_exec_sh, wait_for_path, wait_for_log, wait_for_docker_logs, poll_container+from tests.docker.conftest import docker_exec, docker_exec_sh, wait_for_path, wait_for_logdef _docker(*args: str, **kw) -> subprocess.CompletedProcess[str]:diff --git a/tests/docker/test_docker_exec_privilege_drop.py b/tests/docker/test_docker_exec_privilege_drop.pyindex 057abb737a1..44fac426147 100644--- a/tests/docker/test_docker_exec_privilege_drop.py+++ b/tests/docker/test_docker_exec_privilege_drop.py@@ -17,12 +17,12 @@ These tests verify:as hermes:hermes — the actual user-visible invariant.4. The HERMES_DOCKER_EXEC_AS_ROOT opt-out lets diagnostic sessions keeprunning as root deliberately.-5. The main CMD path (``docker run <image> …``) is unaffected by the- PATH-shim ordering — no recursion, no behavior change.++The main CMD path through the shim is covered by+test_main_invocation.py::test_chat_subcommand_passthrough."""from __future__ import annotations-from tests.docker.conftest import docker_execimport subprocessimport time@@ -152,26 +152,6 @@ def test_shim_drops_root_to_hermes_uid(sleep_container: str) -> None:-def test_main_cmd_path_unaffected(built_image: str) -> None:- """The CMD path (docker run <image> <args>) must still work.-- The shim sits at /opt/hermes/bin earliest on PATH; main-wrapper.sh- invokes `s6-setuidgid hermes hermes <args>` which resolves `hermes`- through PATH. With the shim in the way, this could regress if the- shim recurses or interferes with TTY/exit-code propagation.-- `chat --help` is cheap and exercises the full subcommand- passthrough path. The duplicate of test_main_invocation's- pre-existing test is intentional — that one would have passed- pre-shim too; this one specifically guards against shim regressions- in the CMD-as-main-program codepath.- """- r = subprocess.run(- ["docker", "run", "--rm", built_image, "chat", "--help"],- capture_output=True, text=True, timeout=60,- )- assert r.returncode == 0, f"CMD path broken by shim: stderr={r.stderr!r}"- assert "Traceback" not in r.stderrdef test_e2e_login_then_supervised_gateway_can_read_auth(diff --git a/tests/docker/test_gateway_bootstrap_state.py b/tests/docker/test_gateway_bootstrap_state.pyindex 17882c83824..d8ddf680287 100644--- a/tests/docker/test_gateway_bootstrap_state.py+++ b/tests/docker/test_gateway_bootstrap_state.py@@ -79,8 +79,12 @@ def test_no_seed_when_env_unset(def test_non_running_value_ignored(built_image: str, container_name: str,) -> None:- """Only literal 'running' is honored; any other value is ignored."""- for bogus in ("stopped", "Running", "1", "true", "starting"):+ """Only literal 'running' is honored; any other value is ignored.++ One representative non-running value: each value costs a full container+ boot, and the shell comparison has no per-value branches worth pinning.+ """+ for bogus in ("stopped",):# Need a fresh container per iterationname = f"{container_name}-{bogus}"_start_container(diff --git a/tests/docker/test_gateway_run_supervised.py b/tests/docker/test_gateway_run_supervised.pyindex 5b74aaefe3f..889e194b159 100644--- a/tests/docker/test_gateway_run_supervised.py+++ b/tests/docker/test_gateway_run_supervised.py@@ -119,9 +119,6 @@ def test_gateway_run_redirects_to_supervised(assert "s6 supervision" in logs, (f"expected loud breadcrumb in docker logs; got:\n{logs}")- assert "--no-supervise" in logs, (- f"breadcrumb missing opt-out hint; got:\n{logs}"- )# Container should still be running. If the redirect didn't fire,# the foreground gateway would have crashed and the containerdiff --git a/tests/docker/test_home_override_scripts.py b/tests/docker/test_home_override_scripts.pyindex 1b5ff4cdc64..2507661dd86 100644--- a/tests/docker/test_home_override_scripts.py+++ b/tests/docker/test_home_override_scripts.py@@ -2,16 +2,18 @@Build the real image and verify the actual runtime behavior:- 1. main-wrapper preserves the Docker ``-w`` working directory- 2. dashboard service resets HOME to /opt/data before privilege drop- 3. dashboard does not auto-add ``--insecure`` from a non-loopback bind host- 4. stage2 hook repairs profiles/ and cron/ ownership on every boot+ 1. dashboard service resets HOME to /opt/data before privilege drop+ 2. stage2 hook repairs profiles/ and cron/ ownership on every boot"""from __future__ import annotations-import subprocess--from tests.docker.conftest import docker_exec, docker_exec_sh, start_container, restart_container+from tests.docker.conftest import (+ docker_exec,+ docker_exec_sh,+ poll_container,+ restart_container,+ start_container,+)@@ -23,11 +25,8 @@ def test_dashboard_service_resets_home(privileges, so HOME-anchored state (discord lockfile, XDG dirs) doesn'ttry to write to /root (the /init context's HOME).- We check this by inspecting the environment of the dashboard service- process if it's running, or by verifying the run script sets HOME- before the exec. At runtime, the cleanest check is: start the- container with HERMES_DASHBOARD=1 and verify the dashboard process- (if it starts) has HOME=/opt/data.+ Start the container with HERMES_DASHBOARD=1 and verify the running+ dashboard process has HOME=/opt/data in its real environment.Since the dashboard requires an auth provider on non-loopback binds,we bind to 127.0.0.1 where the auth gate doesn't engage, and check@@ -35,61 +34,20 @@ def test_dashboard_service_resets_home("""start_container(built_image, container_name, "HERMES_DASHBOARD=1", "HERMES_DASHBOARD_HOST=127.0.0.1")- # Check if the dashboard process is running and inspect its HOME.- r = docker_exec_sh(+ # Wait for the supervised dashboard process, then read its HOME from+ # /proc/<pid>/environ (the real runtime environment, not the script text).+ ok, out = poll_container(container_name,- # Find the dashboard process (hermes dashboard) and read its HOME- # from /proc/<pid>/environ. If not running, verify the run script- # itself exports HOME=/opt/data by grepping the script source.'pid=$(pgrep -f "hermes dashboard" | head -1); '- 'if [ -n "$pid" ]; then '- ' tr "\\0" "\\n" < /proc/$pid/environ | grep "^HOME="; '- 'else '- ' grep -q "export HOME=/opt/data" '- ' /opt/hermes/docker/s6-rc.d/dashboard/run && '- ' echo "HOME=/opt/data"; '- 'fi',- timeout=15,+ '[ -n "$pid" ] && tr "\\0" "\\n" < /proc/$pid/environ | grep "^HOME="',+ deadline_s=60.0,)- assert "HOME=/opt/data" in r.stdout, (- f"dashboard process or run script does not set HOME=/opt/data: "- f"stdout={r.stdout!r} stderr={r.stderr!r}"+ assert ok, f"dashboard process never started (last probe output: {out!r})"+ assert "HOME=/opt/data" in out, (+ f"dashboard process does not run with HOME=/opt/data: {out!r}")-def test_dashboard_does_not_auto_insecure_from_host(- built_image: str, container_name: str,-) -> None:- """The dashboard MUST NOT auto-add ``--insecure`` based on- HERMES_DASHBOARD_HOST. The auth gate is the authority now.-- The auth gate is the authority on whether non-loopback binds are- safe; ``--insecure`` must never be auto-derived from the bind host.-- We start the container with a non-loopback bind host and verify- the dashboard process does NOT receive ``--insecure`` in its- command line. If the dashboard fails to start (because the auth- gate correctly blocks an unauthenticated non-loopback bind), that's- also acceptable — the point is no auto-insecure.- """- start_container(built_image, container_name, "HERMES_DASHBOARD=1", "HERMES_DASHBOARD_HOST=0.0.0.0")-- # Check the dashboard process command line for --insecure.- r = docker_exec_sh(- container_name,- 'pid=$(pgrep -f "hermes dashboard" | head -1); '- 'if [ -n "$pid" ]; then '- ' tr "\\0" " " < /proc/$pid/cmdline; '- 'fi',- timeout=10,- )- cmdline = r.stdout.strip()- # If the process is running, it must NOT have --insecure.- if cmdline:- assert "--insecure" not in cmdline, (- f"dashboard process has --insecure in cmdline (auto-derived "- f"from host): {cmdline!r}"- )def test_stage2_repairs_profiles_and_cron_ownership(diff --git a/tests/docker/test_immutable_install.py b/tests/docker/test_immutable_install.pyindex e2fae89e08a..f432d058eb7 100644--- a/tests/docker/test_immutable_install.py+++ b/tests/docker/test_immutable_install.py@@ -3,10 +3,11 @@Build the real image and verify at runtime:1. /opt/hermes is not writable by the hermes user (immutable install tree)- 2. PYTHONDONTWRITEBYTECODE and HERMES_DISABLE_LAZY_INSTALLS are set- 3. /opt/hermes/.install_method contains "docker" (code-scoped stamp)- 4. $HERMES_HOME/.install_method is NOT stamped as "docker" by stage2- 5. A stale "docker" stamp in $HERMES_HOME is healed (removed) on boot+ 2. A stale "docker" stamp in $HERMES_HOME is healed (removed) on boot++The hosted write-policy env (PYTHONDONTWRITEBYTECODE,+HERMES_DISABLE_LAZY_INSTALLS, ...) is covered by+test_immutable_install_permissions.py."""from __future__ import annotations@@ -53,25 +54,6 @@ def test_install_tree_not_writable_by_hermes()-def test_hermes_disable_lazy_installs_and_dont_write_bytecode(- built_image: str, container_name: str,-) -> None:- """The container must set PYTHONDONTWRITEBYTECODE and- HERMES_DISABLE_LAZY_INSTALLS=1 so no .pyc files are written to the- immutable install tree and no lazy installs attempt to modify it."""- start_container(built_image, container_name)-- r = docker_exec_sh(- container_name,- 'test "$PYTHONDONTWRITEBYTECODE" = "1" && '- 'test "$HERMES_DISABLE_LAZY_INSTALLS" = "1" && '- 'echo ENV_OK || echo ENV_MISSING',- timeout=10,- )- assert "ENV_OK" in r.stdout, (- f"expected PYTHONDONTWRITEBYTECODE=1 and "- f"HERMES_DISABLE_LAZY_INSTALLS=1, got: {r.stdout} stderr={r.stderr}"- )diff --git a/tests/docker/test_log_dir_seed.py b/tests/docker/test_log_dir_seed.pyindex 65cb7b5be17..ba4d9ec2ddd 100644--- a/tests/docker/test_log_dir_seed.py+++ b/tests/docker/test_log_dir_seed.py@@ -12,7 +12,6 @@ from __future__ import annotationsfrom tests.docker.conftest import (docker_exec_sh,- restart_container,start_container,)diff --git a/tests/docker/test_main_invocation.py b/tests/docker/test_main_invocation.pyindex 1f9189d234c..74be1faef04 100644--- a/tests/docker/test_main_invocation.py+++ b/tests/docker/test_main_invocation.py@@ -12,21 +12,6 @@ from __future__ import annotationsimport subprocess-def test_no_args_starts_hermes(built_image: str) -> None:- """``docker run <image>`` should start hermes cleanly.-- We invoke ``--version`` so the call exits without needing a configured- model. Exit code may be 0 (printed version) or 1 (config bootstrapping- failure on a fresh volume), but never a stack trace.- """- r = subprocess.run(- ["docker", "run", "--rm", built_image, "--version"],- capture_output=True, text=True, timeout=60,- )- assert r.returncode in (0, 1), (- f"Unexpected exit {r.returncode}: stderr={r.stderr!r}"- )- assert "Traceback" not in r.stderrdef test_chat_subcommand_passthrough(built_image: str) -> None:diff --git a/tests/docker/test_profile_gateway.py b/tests/docker/test_profile_gateway.pyindex 7834f9e8539..5339fbc1e97 100644--- a/tests/docker/test_profile_gateway.py+++ b/tests/docker/test_profile_gateway.py@@ -91,8 +91,6 @@ def test_named_profile_gateway_start_refuses_without_force(r = _sh(container_name, f"hermes -p {PROFILE} gateway start", timeout=60)assert r.returncode != 0, f"a named profile started its own gateway: {r.stdout!r}"- assert "does not get a gateway of its own" in r.stdout- assert "--force" in r.stdout and "migrate --multiplex" in r.stdoutassert not _svstat_wants_up(container_name), (f"refused start still flipped the slot's want-state: {_svstat(container_name)!r}")diff --git a/tests/docker/test_puid_pgid_remap.py b/tests/docker/test_puid_pgid_remap.pyindex d2492eefe31..1a231c3f3d4 100644--- a/tests/docker/test_puid_pgid_remap.py+++ b/tests/docker/test_puid_pgid_remap.py@@ -37,6 +37,16 @@ def test_puid_pgid_remaps_hermes_user(f"expected hermes GID 1000 after PGID remap, got: {r.stdout.strip()}")+ # The remapped user must still be able to write to the data volume.+ r = docker_exec_sh(+ container_name,+ "touch /opt/data/test_write && echo WRITE_OK || echo WRITE_FAIL",+ timeout=10,+ )+ assert "WRITE_OK" in r.stdout, (+ f"hermes user cannot write to /opt/data after remap: {r.stdout}"+ )+@@ -57,17 +67,3 @@ def test_nas_low_uid_accepted()-def test_remap_enables_data_volume_writes(- built_image: str, container_name: str,-) -> None:- """After remap, the hermes user must be able to write to /opt/data."""- start_container(built_image, container_name, "PUID=1000", "PGID=1000")-- r = docker_exec_sh(- container_name,- "touch /opt/data/test_write && echo WRITE_OK || echo WRITE_FAIL",- timeout=10,- )- assert "WRITE_OK" in r.stdout, (- f"hermes user cannot write to /opt/data after remap: {r.stdout}"- )\ No newline at end of filediff --git a/tests/docker/test_s6_profile_gateway_integration.py b/tests/docker/test_s6_profile_gateway_integration.pyindex 9b9eb7129fc..166bd2e610d 100644--- a/tests/docker/test_s6_profile_gateway_integration.py+++ b/tests/docker/test_s6_profile_gateway_integration.py@@ -33,13 +33,6 @@ S6ServiceManager().register_profile_gateway("phase3test")print("REGISTERED")"""-_UNREGISTER_SCRIPT = """-import sys-sys.path.insert(0, "/opt/hermes")-from hermes_cli.service_manager import S6ServiceManager-S6ServiceManager().unregister_profile_gateway("phase3test")-print("UNREGISTERED")-"""def test_s6_register_creates_service_dir_in_live_container(@@ -79,43 +72,3 @@ def test_s6_register_creates_service_dir_in_live_container("print(S6ServiceManager().list_profile_gateways())"))assert "phase3test" in r.stdout, f"list output: {r.stdout!r}"-----# Shell probe: build a service-shaped staging dir under the live scandir-# with a given NAME, fire a real `s6-svscanctl -a` rescan, wait, and-# report whether s6-svscan supervised it (which would create a root-owned-# supervise/ dir). Used to prove the dot-prefixed staging name is INVISIBLE-# to a concurrent rescan while a non-dotted one is not.-#-# Echoes one of: SUPERVISED / NOT-SUPERVISED, plus the supervise/ owner.-_SVSCAN_PICKUP_PROBE = r"""-set -eu-NAME="$1"-SCANDIR=/run/service-DIR="$SCANDIR/$NAME"-rm -rf "$DIR"-mkdir -p "$DIR"-printf 'longrun\n' > "$DIR/type"-printf '#!/command/execlineb -P\n/command/s6-sleep 600\n' > "$DIR/run"-chmod 755 "$DIR/run"-# Trigger a full rescan, exactly as register/reconcile do.-/command/s6-svscanctl -a "$SCANDIR"-# Give s6-svscan time to act (its scan is async; 200ms is the manager's-# own settle delay, use 2s here to be comfortably past it on any arch).-/command/s6-sleep 2-if [ -d "$DIR/supervise" ]; then- owner=$(stat -c '%U' "$DIR/supervise" 2>/dev/null || echo '?')- echo "SUPERVISED owner=$owner"-else- echo "NOT-SUPERVISED"-fi-# Best-effort teardown so the probe leaves no live supervisor behind.-/command/s6-svc -d "$DIR" 2>/dev/null || true-/command/s6-svscanctl -an "$SCANDIR" 2>/dev/null || true-/command/s6-sleep 1-rm -rf "$DIR" 2>/dev/null || true-"""--diff --git a/tests/docker/test_tini_compat_shim.py b/tests/docker/test_tini_compat_shim.pyindex ff72e3039f0..98749fe035f 100644--- a/tests/docker/test_tini_compat_shim.py+++ b/tests/docker/test_tini_compat_shim.py@@ -1,80 +1,35 @@"""Runtime smoke test for the Docker tini compatibility shim (#34192, #66679).-Build the real image and verify:-- 1. /usr/bin/tini exists as an executable shim (not a bare symlink to- /init — that forwarded tini's ``-g`` into s6 and boot-looped)- 2. The actual ENTRYPOINT is /init (s6-overlay), not /usr/bin/tini- 3. Legacy ``tini -g -- <cmd>`` entrypoints boot without- ``rc.init: -g: not found``+Build the real image and verify that legacy ``/usr/bin/tini -g -- <cmd>``+entrypoints still boot the image (no ``rc.init: -g: not found`` boot loop)."""from __future__ import annotationsimport subprocess-def test_tini_compat_shim_exists(built_image: str) -> None:- """/usr/bin/tini must be an executable shim script.+def test_legacy_tini_entrypoint_boots(built_image: str) -> None:+ """``--entrypoint /usr/bin/tini <image> -g -- --help`` must run hermes.Regression for #34192 / #66679: orchestration templates (e.g.Hostinger's 'Hermes WebUI' catalog, NAS compose projects that keepan old entrypoint across image updates) still pin /usr/bin/tini as- the entrypoint, often with ``-g --``. The shim must exist *and*- strip those flags before exec'ing /init.- """- r = subprocess.run(- ["docker", "run", "--rm", "--entrypoint", "sh",- built_image, "-c",- 'test -x /usr/bin/tini && '- # Must NOT be a raw symlink to /init — that reintroduces #66679.- 'if [ -L /usr/bin/tini ]; then '- ' target="$(readlink -f /usr/bin/tini)"; '- ' test "$target" != "/init"; '- 'fi && '- 'head -n1 /usr/bin/tini | grep -q "^#!"'],- capture_output=True, text=True, timeout=60,- )- assert r.returncode == 0, (- f"/usr/bin/tini is not a usable tini shim: "- f"stdout={r.stdout[-500:]!r} stderr={r.stderr[-500:]!r}"- )---def test_entrypoint_is_dispatcher_not_tini(built_image: str) -> None:- """The image's actual ENTRYPOINT must be the PID-1 dispatcher.-- Since #38349 the ENTRYPOINT is ``entrypoint-dispatch.sh``, which- exec's the canonical ``/init`` (s6-overlay) when the image owns- PID 1 and falls back to a direct bootstrap on wrapped runtimes- (Fly Machines, ``docker run --init``). The tini shim is only for- legacy external wrappers; the image's own runtime must route- through the dispatcher, never through /usr/bin/tini.+ the entrypoint, often with ``-g --``. A missing shim fails to exec; a+ bare symlink to /init forwards ``-g`` into s6 and boot-loops. The shim+ must strip the tini flags and hand the remaining args to /init ++ main-wrapper, so the requested command runs normally."""r = subprocess.run(- ["docker", "inspect", built_image,- "--format", "{{json .Config.Entrypoint}}"],- capture_output=True, text=True, timeout=30,- )- assert r.returncode == 0, f"docker inspect failed: {r.stderr}"- entrypoint = r.stdout.strip()- assert "entrypoint-dispatch.sh" in entrypoint, (- f"ENTRYPOINT is not the PID-1 dispatcher: {entrypoint!r}"- )- # /usr/bin/tini should NOT be in the entrypoint.- assert "tini" not in entrypoint.lower(), (- f"ENTRYPOINT references tini instead of the dispatcher: {entrypoint!r}"+ ["docker", "run", "--rm", "--entrypoint", "/usr/bin/tini",+ built_image, "-g", "--", "--help"],+ capture_output=True, text=True, timeout=120,)- # The dispatcher must still hand PID-1 execution to /init inside- # the image, preserving the supervision tree.- r2 = subprocess.run(- ["docker", "run", "--rm", "--entrypoint", "sh", built_image, "-c",- "grep -q 'exec /init /opt/hermes/docker/main-wrapper.sh' "- "/opt/hermes/docker/entrypoint-dispatch.sh"],- capture_output=True, text=True, timeout=60,+ combined = r.stdout + r.stderr+ assert "-g: not found" not in combined, (+ f"tini flags leaked into s6 rc.init (#66679): {combined[-2000:]!r}")- assert r2.returncode == 0, (- "entrypoint-dispatch.sh in the image does not delegate the "- f"PID-1 path to /init: stderr={r2.stderr[-500:]!r}"+ assert r.returncode == 0, (+ f"legacy tini entrypoint failed (exit {r.returncode}): "+ f"stdout={r.stdout[-2000:]!r} stderr={r.stderr[-2000:]!r}")--+ assert "Traceback" not in r.stderrdiff --git a/tests/docker/test_tui_passthrough.py b/tests/docker/test_tui_passthrough.pyindex 3f7887ae15b..3843a173637 100644--- a/tests/docker/test_tui_passthrough.py+++ b/tests/docker/test_tui_passthrough.py@@ -55,11 +55,3 @@ def test_tty_passthrough_to_container(built_image: str) -> None:assert int(value) > 0-def test_tui_flag_recognized(built_image: str) -> None:- """``docker run -it <image> --help`` should run without crashing."""- cmd = f"docker run --rm -t {built_image} --help"- r = subprocess.run(- ["script", "-qc", cmd, "/dev/null"],- capture_output=True, text=True, timeout=60,- )- assert r.returncode == 0diff --git a/tests/docker/test_tui_prebuilt_bundle.py b/tests/docker/test_tui_prebuilt_bundle.pyindex 93e778cf407..1c77535f504 100644--- a/tests/docker/test_tui_prebuilt_bundle.py+++ b/tests/docker/test_tui_prebuilt_bundle.py@@ -39,17 +39,6 @@ def _exec_py(image: str, py: str) -> str:return r.stdout.strip()-def test_hermes_tui_dir_env_is_set(built_image: str) -> None:- """HERMES_TUI_DIR must point at the prebuilt bundle dir in the image."""- r = subprocess.run(- ["docker", "run", "--rm", "--entrypoint", "sh", built_image,- "-c", 'printf "%s" "$HERMES_TUI_DIR"'],- capture_output=True, text=True, timeout=60,- )- assert r.returncode == 0, r.stderr[-2000:]- assert r.stdout.strip() == "/opt/hermes/ui-tui", (- f"HERMES_TUI_DIR={r.stdout.strip()!r} (expected /opt/hermes/ui-tui)"- )def test_prebuilt_bundle_present_and_no_runtime_install(built_image: str) -> None:diff --git a/tests/docker/test_user_flag_guard.py b/tests/docker/test_user_flag_guard.pyindex 4aa7eba6c7b..b9a870ca44f 100644--- a/tests/docker/test_user_flag_guard.py+++ b/tests/docker/test_user_flag_guard.py@@ -3,8 +3,9 @@Build the real image and verify the actual runtime behavior:1. docker run --user <arbitrary-uid> is rejected with actionable guidance- 2. Root start (default) works fine- 3. --user <hermes-uid> (10000) is allowed (supported non-root start)+ 2. --user <hermes-uid> (10000) is allowed (supported non-root start)++Root start (the default) is covered by test_main_invocation.py."""from __future__ import annotations@@ -27,25 +28,12 @@ def test_arbitrary_user_uid_rejected(f"container ran despite --user rejection: {r.stdout}")combined = r.stdout + r.stderr- assert "not supported" in combined.lower(), (- f"rejection message missing 'not supported': {combined[-500:]}"- )# Must mention the remediation env varsassert "HERMES_UID" in combined or "PUID" in combined, (f"rejection message missing remediation guidance: {combined[-500:]}")-def test_root_start_works(- built_image: str,-) -> None:- """Root start (the default) must work without issues."""- r = subprocess.run(- ["docker", "run", "--rm", built_image, "sh", "-c", "echo OK"],- capture_output=True, text=True, timeout=60,- )- assert r.returncode == 0, f"root start failed: {r.stderr[-500:]}"- assert "OK" in r.stdoutdef test_user_pinned_to_hermes_uid_works(diff --git a/tests/docker/test_zombie_reaping.py b/tests/docker/test_zombie_reaping.pyindex e136a510891..1cd106ffd6d 100644--- a/tests/docker/test_zombie_reaping.py+++ b/tests/docker/test_zombie_reaping.py@@ -14,7 +14,7 @@ from __future__ import annotationsimport time-from tests.docker.conftest import docker_exec, docker_exec_sh, start_container, start_container+from tests.docker.conftest import docker_exec, docker_exec_sh, start_containerdef test_orphan_zombies_reaped(diff --git a/tests/e2e/matrix_xsign_bootstrap/README.md b/tests/e2e/matrix_xsign_bootstrap/README.mddeleted file mode 100644index 0400edd7dea..00000000000--- a/tests/e2e/matrix_xsign_bootstrap/README.md+++ /dev/null@@ -1,49 +0,0 @@-# Matrix cross-signing bootstrap — E2E test--Self-contained end-to-end test for the auto-bootstrap behavior added in-`gateway/platforms/matrix.py`. Spins up a real Continuwuity homeserver-in Docker, registers a fresh bot, runs the patched bootstrap path-against it, and asserts:--1. Cross-signing keys get published with **unpadded** base64 keyids- (the bug this PR fixes — padded keyids are silently rejected by- matrix-rust-sdk in Element).-2. On a second startup with the same crypto store, bootstrap is- skipped.-3. When `MATRIX_RECOVERY_KEY` is set, the existing recovery-key path- takes precedence and no fresh bootstrap happens.--## Run--```bash-# from repo root-docker compose -f tests/e2e/matrix_xsign_bootstrap/docker-compose.yml up -d-python tests/e2e/matrix_xsign_bootstrap/test_bootstrap.py-docker compose -f tests/e2e/matrix_xsign_bootstrap/docker-compose.yml down -v-```--The `down -v` step removes the persistent volume so the next run gets-a fresh homeserver — important because Continuwuity's one-time admin-registration token is only valid before the first user is created.--## Port--The compose binds Continuwuity to `127.0.0.1:26167` by default. Override-with `HOMESERVER_HOST_PORT=NNNNN docker compose up -d` if that port is-busy locally.--## What the test exercises--The test mirrors the bootstrap snippet from-`gateway/platforms/matrix.py` (the "if MATRIX_RECOVERY_KEY else-get_own_cross_signing_public_keys / generate_recovery_key" branch)-inline so it runs without importing the entire hermes gateway and its-many dependencies. **If the source diverges from what's in-`_connect_with_bootstrap`, this test must be updated to match.** A-small price for not requiring the full hermes-agent runtime in CI.--## Skipped when--- `mautrix` Python package is not installed-- The homeserver isn't reachable at `$E2E_MATRIX_HS` (default- `http://127.0.0.1:26167`)diff --git a/tests/e2e/matrix_xsign_bootstrap/docker-compose.yml b/tests/e2e/matrix_xsign_bootstrap/docker-compose.ymldeleted file mode 100644index 4477a8163d3..00000000000--- a/tests/e2e/matrix_xsign_bootstrap/docker-compose.yml+++ /dev/null@@ -1,21 +0,0 @@-services:- homeserver:- image: ghcr.io/continuwuity/continuwuity:latest- environment:- CONTINUWUITY_SERVER_NAME: localhost- CONTINUWUITY_DATABASE_PATH: /var/lib/conduwuit/conduwuit.db- CONTINUWUITY_PORT: "6167"- CONTINUWUITY_ADDRESS: "0.0.0.0"- CONTINUWUITY_ALLOW_REGISTRATION: "true"- CONTINUWUITY_REGISTRATION_TOKEN: testreg- CONTINUWUITY_ALLOW_FEDERATION: "false"- CONTINUWUITY_TRUSTED_SERVERS: "[]"- CONTINUWUITY_LOG: "warn,conduwuit=info"- CONTINUWUITY_ALLOW_CHECK_FOR_UPDATES: "false"- ports:- - "127.0.0.1:${HOMESERVER_HOST_PORT:-26167}:6167"- healthcheck:- test: ["CMD-SHELL", "exec 3<>/dev/tcp/127.0.0.1/6167 && echo -e 'GET /_matrix/client/versions HTTP/1.0\\r\\n\\r\\n' >&3 && head -1 <&3 | grep -q '200 OK' || exit 1"]- interval: 2s- timeout: 3s- retries: 30diff --git a/tests/e2e/matrix_xsign_bootstrap/test_bootstrap.py b/tests/e2e/matrix_xsign_bootstrap/test_bootstrap.pydeleted file mode 100644index c24c7292073..00000000000--- a/tests/e2e/matrix_xsign_bootstrap/test_bootstrap.py+++ /dev/null@@ -1,331 +0,0 @@-"""End-to-end test for Matrix cross-signing auto-bootstrap.--Spins a real Continuwuity homeserver in docker, registers a fresh bot,-runs the patched ``MatrixAdapter.connect()`` against it, and asserts:-- 1. cross-signing keys get published with **unpadded** base64 keyids- (the bug this PR fixes — padded keyids are silently rejected by- matrix-rust-sdk in Element);- 2. on a second startup with the same crypto store, bootstrap is- skipped (``get_own_cross_signing_public_keys`` finds the keys);- 3. the bot's current device is signed by the new SSK, so Element- considers the device "verified by its owner".--Self-contained: ``docker compose up -d`` brings up Continuwuity on-127.0.0.1:26167; this script registers a fresh bot using the-homeserver's one-time admin registration token (printed once at first-boot, parsed from the container logs); then drives the gateway code.--Run from repo root::-- docker compose -f tests/e2e/matrix_xsign_bootstrap/docker-compose.yml up -d- python tests/e2e/matrix_xsign_bootstrap/test_bootstrap.py- docker compose -f tests/e2e/matrix_xsign_bootstrap/docker-compose.yml down -v--Skipped automatically if mautrix isn't installed or the homeserver-isn't reachable.-"""-from __future__ import annotations--import json-import logging-import os-import re-import secrets-import shutil-import subprocess-import sys-import tempfile-import unittest-import urllib.error-import urllib.request-from pathlib import Path--REPO_ROOT = Path(__file__).resolve().parents[3]-sys.path.insert(0, str(REPO_ROOT))--HS = os.environ.get("E2E_MATRIX_HS", "http://127.0.0.1:26167")-COMPOSE_DIR = Path(__file__).parent-CONTAINER_NAME = "matrix_xsign_bootstrap-homeserver-1"---def _hs_reachable() -> bool:- try:- urllib.request.urlopen(f"{HS}/_matrix/client/versions", timeout=2).read()- return True- except Exception:- return False---def _first_time_token() -> str | None:- """Continuwuity prints a one-time registration token on first boot.-- The configured CONTINUWUITY_REGISTRATION_TOKEN does NOT activate- until an account exists, so we have to pull this token out of the- docker logs to bootstrap the very first user.- """- try:- out = subprocess.run(- ["docker", "logs", CONTAINER_NAME],- capture_output=True, text=True, check=True,- ).stdout + subprocess.run(- ["docker", "logs", CONTAINER_NAME],- capture_output=True, text=True, check=True,- ).stderr- except Exception:- return None- cleaned = re.sub(r"\x1b\[[0-9;]*m", "", out)- m = re.search(r"registration token ([A-Za-z0-9]+)", cleaned)- return m.group(1) if m else None---def _post_json(url: str, body: dict, headers: dict | None = None) -> tuple[int, dict]:- req = urllib.request.Request(- url, data=json.dumps(body).encode(),- headers={"Content-Type": "application/json", **(headers or {})},- method="POST",- )- try:- r = urllib.request.urlopen(req)- return r.status, json.load(r)- except urllib.error.HTTPError as e:- return e.code, json.loads(e.read().decode())---CONFIG_REG_TOKEN = "testreg" # matches docker-compose.yml---def _register_bot(*, prefer_token: str = CONFIG_REG_TOKEN, fallback_token: str | None = None) -> dict:- """Register a fresh bot. Tries the configured token first; falls back to- the homeserver's one-time admin token (only valid until the first user- is created)."""- user = "bot" + secrets.token_hex(3)- password = secrets.token_urlsafe(20)- last_err = None- for tok in (prefer_token, fallback_token):- if tok is None:- continue- st, b = _post_json(f"{HS}/_matrix/client/v3/register", {})- if st != 401 or "session" not in b:- last_err = (st, b); continue- session = b["session"]- st, b = _post_json(f"{HS}/_matrix/client/v3/register", {- "auth": {"type": "m.login.registration_token", "token": tok, "session": session},- "username": user, "password": password,- "initial_device_display_name": "e2e-bootstrap-test",- })- if st == 200:- return b- last_err = (st, b)- raise AssertionError(f"register failed for both tokens: {last_err}")---def _query_keys(token: str, mxid: str) -> dict:- return _post_json(- f"{HS}/_matrix/client/v3/keys/query",- {"device_keys": {mxid: []}},- headers={"Authorization": f"Bearer {token}"},- )[1]--[email protected](_hs_reachable(), f"homeserver not reachable at {HS}")-class XsignBootstrapE2E(unittest.IsolatedAsyncioTestCase):- """Drive the patched MatrixAdapter.connect() against real continuwuity."""-- @classmethod- def setUpClass(cls):- try:- import mautrix # noqa: F401- except ImportError:- raise unittest.SkipTest("mautrix not installed")- cls.first_tok = _first_time_token()- # If no user has ever been created, the configured `testreg` token- # won't activate yet — burn the one-time admin token first to- # bootstrap the homeserver into a usable state.- if cls.first_tok:- try:- _register_bot(prefer_token=cls.first_tok, fallback_token=None)- except AssertionError:- pass # Already burnt previously; testreg should now work.-- async def _connect_with_bootstrap(self, creds: dict, store_dir: Path) -> tuple[list[str], str | None]:- """Drive matrix.py's bootstrap branch directly.-- We import the gateway module and execute the same OlmMachine init +- bootstrap sequence, capturing log lines so we can assert what fired.- Returns (log_lines, recovery_key_or_None).- """- from mautrix.api import HTTPAPI- from mautrix.client import Client- from mautrix.client.state_store.memory import MemoryStateStore- from mautrix.crypto import OlmMachine, PgCryptoStore- from mautrix.types import TrustState- from mautrix.util.async_db import Database-- # The actual bootstrap snippet from gateway/platforms/matrix.py- # (copied so we can run it without importing the full hermes- # gateway and its many deps). If the source code drifts from this,- # the test should be updated to match.- log_lines: list[str] = []- captured_recovery_key: str | None = None-- class _Capture(logging.Handler):- def emit(self, record):- log_lines.append(self.format(record))-- logger = logging.getLogger("e2e.bootstrap")- logger.setLevel(logging.DEBUG)- handler = _Capture()- handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))- logger.addHandler(handler)-- api = HTTPAPI(base_url=creds["homeserver"], token=creds["access_token"])- client = Client(- mxid=creds["user_id"], api=api,- device_id=creds["device_id"], state_store=MemoryStateStore(),- )- client.api.token = creds["access_token"]-- store_dir.mkdir(parents=True, exist_ok=True)- db_path = store_dir / "crypto.db"- crypto_db = Database.create(f"sqlite:///{db_path}", upgrade_table=PgCryptoStore.upgrade_table)- await crypto_db.start()- crypto_store = PgCryptoStore(account_id=creds["user_id"], pickle_key="e2e-test", db=crypto_db)- await crypto_store.open()-- olm = OlmMachine(client, crypto_store, MemoryStateStore())- olm.share_keys_min_trust = TrustState.UNVERIFIED- olm.send_keys_min_trust = TrustState.UNVERIFIED- await olm.load()-- # --- The patched bootstrap block, mirrored from matrix.py ---- recovery_key = os.getenv("MATRIX_RECOVERY_KEY", "").strip()- if recovery_key:- try:- await olm.verify_with_recovery_key(recovery_key)- logger.info("Matrix: cross-signing verified via recovery key")- except Exception as exc:- logger.warning("Matrix: recovery key verification failed: %s", exc)- else:- try:- own_xsign = await olm.get_own_cross_signing_public_keys()- except Exception as exc:- own_xsign = None- logger.warning("Matrix: cross-signing key lookup failed: %s", exc)- if own_xsign is None:- try:- new_recovery_key = await olm.generate_recovery_key()- captured_recovery_key = new_recovery_key- logger.warning(- "Matrix: bootstrapped cross-signing for %s. "- "SAVE THIS RECOVERY KEY: %s",- client.mxid, new_recovery_key,- )- except Exception as exc:- logger.warning("Matrix: cross-signing bootstrap failed: %s", exc)-- # --- /end patched block ---- # Clean teardown — without this the asyncio loop never exits.- await crypto_db.stop()- await api.session.close()- return log_lines, captured_recovery_key-- async def asyncSetUp(self):- self.creds = _register_bot(prefer_token=CONFIG_REG_TOKEN, fallback_token=self.first_tok)- self.creds["homeserver"] = HS- self.tmp = Path(tempfile.mkdtemp(prefix="e2e-xsign-"))- # mautrix.generate_recovery_key requires account.shared, which means- # we must share device keys (one-time keys) first. Do that via a- # short bootstrap to publish device keys.- await self._publish_device_keys(self.creds, self.tmp)-- async def _publish_device_keys(self, creds, store_dir):- """Tiny helper: open OlmMachine, share device keys, close."""- from mautrix.api import HTTPAPI- from mautrix.client import Client- from mautrix.client.state_store.memory import MemoryStateStore- from mautrix.crypto import OlmMachine, PgCryptoStore- from mautrix.util.async_db import Database-- api = HTTPAPI(base_url=creds["homeserver"], token=creds["access_token"])- client = Client(mxid=creds["user_id"], api=api, device_id=creds["device_id"],- state_store=MemoryStateStore())- store_dir.mkdir(parents=True, exist_ok=True)- crypto_db = Database.create(f"sqlite:///{store_dir / 'crypto.db'}",- upgrade_table=PgCryptoStore.upgrade_table)- await crypto_db.start()- crypto_store = PgCryptoStore(account_id=creds["user_id"], pickle_key="e2e-test", db=crypto_db)- await crypto_store.open()- olm = OlmMachine(client, crypto_store, MemoryStateStore())- await olm.load()- await olm.share_keys() # publishes device keys (precondition for generate_recovery_key)- await crypto_db.stop()- await api.session.close()-- async def asyncTearDown(self):- shutil.rmtree(self.tmp, ignore_errors=True)-- async def test_bootstrap_publishes_unpadded_keys(self):- """Fresh bot → bootstrap fires, keys published unpadded, device signed."""- log_lines, rec_key = await self._connect_with_bootstrap(self.creds, self.tmp)- # 1. Bootstrap must have produced a recovery key- self.assertIsNotNone(rec_key, "expected recovery key from bootstrap")- self.assertTrue(any("bootstrapped cross-signing" in l for l in log_lines),- f"expected bootstrap log line, got: {log_lines}")- # 2. Homeserver should now serve a master + ssk for the bot- d = _query_keys(self.creds["access_token"], self.creds["user_id"])- self.assertIn(self.creds["user_id"], d.get("master_keys", {}),- "no master_keys after bootstrap")- self.assertIn(self.creds["user_id"], d.get("self_signing_keys", {}),- "no self_signing_keys after bootstrap")- # 3. The keyids must be UNPADDED (this is the bug this PR exists to fix)- master_kid = next(iter(d["master_keys"][self.creds["user_id"]]["keys"]))- ssk_kid = next(iter(d["self_signing_keys"][self.creds["user_id"]]["keys"]))- self.assertFalse(master_kid.endswith("="),- f"master keyid is padded: {master_kid!r}")- self.assertFalse(ssk_kid.endswith("="),- f"ssk keyid is padded: {ssk_kid!r}")- # 4. The current device must be signed by the new SSK- dev = d["device_keys"][self.creds["user_id"]][self.creds["device_id"]]- sig_kids = list(dev["signatures"][self.creds["user_id"]].keys())- self.assertIn(ssk_kid, sig_kids,- f"device {self.creds['device_id']} not signed by new SSK; "- f"signatures: {sig_kids}")-- async def test_second_startup_skips_bootstrap(self):- """Second startup with same crypto store → no second recovery key."""- # First connect bootstraps.- _, rec1 = await self._connect_with_bootstrap(self.creds, self.tmp)- self.assertIsNotNone(rec1, "first connect should have bootstrapped")- # Second connect on same crypto store should NOT re-bootstrap.- log2, rec2 = await self._connect_with_bootstrap(self.creds, self.tmp)- self.assertIsNone(rec2, f"second connect re-bootstrapped! logs: {log2}")- self.assertFalse(any("bootstrapped cross-signing" in l for l in log2),- f"second connect re-bootstrapped! logs: {log2}")-- async def test_recovery_key_path_takes_precedence(self):- """If MATRIX_RECOVERY_KEY is set, no fresh bootstrap happens."""- # First, bootstrap to get a real recovery key.- _, rec_key = await self._connect_with_bootstrap(self.creds, self.tmp)- self.assertIsNotNone(rec_key)- # Fresh store directory + recovery key set in env: must take the- # verify_with_recovery_key path, NOT bootstrap a new identity.- fresh_store = Path(tempfile.mkdtemp(prefix="e2e-xsign-fresh-"))- try:- await self._publish_device_keys(self.creds, fresh_store)- os.environ["MATRIX_RECOVERY_KEY"] = rec_key- try:- log, rec2 = await self._connect_with_bootstrap(self.creds, fresh_store)- self.assertIsNone(rec2, "bootstrap fired despite MATRIX_RECOVERY_KEY being set")- self.assertTrue(- any("verified via recovery key" in l for l in log),- f"expected recovery-key verify log, got: {log}",- )- finally:- del os.environ["MATRIX_RECOVERY_KEY"]- finally:- shutil.rmtree(fresh_store, ignore_errors=True)---if __name__ == "__main__":- unittest.main(verbosity=2)diff --git a/tests/e2e/test_platform_commands.py b/tests/e2e/test_platform_commands.pyindex ffd9db601fc..30f2b12b78b 100644--- a/tests/e2e/test_platform_commands.py+++ b/tests/e2e/test_platform_commands.py@@ -32,13 +32,6 @@ class TestSlashCommands:assert "/new" in response_textassert "/status" in response_text- @pytest.mark.asyncio- async def test_status_shows_session_info(self, adapter, platform):- send = await send_and_capture(adapter, "/status", platform)-- send.assert_called_once()- response_text = send.call_args[1].get("content") or send.call_args[0][1]- assert "session" in response_text.lower() or "Session" in response_text@pytest.mark.asyncioasync def test_new_resets_session(self, adapter, runner, platform):@@ -47,14 +40,6 @@ class TestSlashCommands:send.assert_called_once()runner.session_store.reset_session.assert_called_once()- @pytest.mark.asyncio- async def test_stop_when_no_agent_running(self, adapter, platform):- send = await send_and_capture(adapter, "/stop", platform)-- send.assert_called_once()- response_text = send.call_args[1].get("content") or send.call_args[0][1]- response_lower = response_text.lower()- assert "no" in response_lower or "stop" in response_lower or "not running" in response_lower@pytest.mark.asyncioasync def test_leading_space_stop_is_still_a_command(self, adapter, platform):@@ -66,32 +51,8 @@ class TestSlashCommands:response_lower = response_text.lower()assert "no" in response_lower or "stop" in response_lower or "not running" in response_lower- @pytest.mark.asyncio- async def test_commands_shows_listing(self, adapter, platform):- send = await send_and_capture(adapter, "/commands", platform)-- send.assert_called_once()- response_text = send.call_args[1].get("content") or send.call_args[0][1]- # Should list at least some commands- assert "/" in response_text-- @pytest.mark.asyncio- async def test_sequential_commands_share_session(self, adapter, platform):- """Two commands from the same chat_id should both succeed."""- send_help = await send_and_capture(adapter, "/help", platform)- send_help.assert_called_once()-- send_status = await send_and_capture(adapter, "/status", platform)- send_status.assert_called_once()- @pytest.mark.asyncio- async def test_verbose_responds(self, adapter, platform):- send = await send_and_capture(adapter, "/verbose", platform)- send.assert_called_once()- response_text = send.call_args[1].get("content") or send.call_args[0][1]- # Either shows the mode cycle or tells user to enable it in config- assert "verbose" in response_text.lower() or "tool_progress" in response_text@pytest.mark.asyncioasync def test_plaintext_restart_gateway_routes_to_safe_restart_command(self, adapter, runner, platform, monkeypatch):@@ -124,29 +85,8 @@ class TestSlashCommands:assert response_text == "agent-handled"runner.request_restart.assert_not_called()- @pytest.mark.asyncio- async def test_personality_lists_options(self, adapter, platform):- send = await send_and_capture(adapter, "/personality", platform)-- send.assert_called_once()- response_text = send.call_args[1].get("content") or send.call_args[0][1]- assert "personalit" in response_text.lower() # matches "personality" or "personalities"-- @pytest.mark.asyncio- async def test_yolo_toggles_mode(self, adapter, platform):- send = await send_and_capture(adapter, "/yolo", platform)-- send.assert_called_once()- response_text = send.call_args[1].get("content") or send.call_args[0][1]- assert "yolo" in response_text.lower()- @pytest.mark.asyncio- async def test_compress_command(self, adapter, platform):- send = await send_and_capture(adapter, "/compress", platform)- send.assert_called_once()- response_text = send.call_args[1].get("content") or send.call_args[0][1]- assert "compress" in response_text.lower() or "context" in response_text.lower()@pytest.mark.asyncioasync def test_quick_command_alias_targets_builtin_command_with_args(@@ -187,12 +127,6 @@ class TestSessionLifecycle:# Session ID from the entry should appear in the status outputassert session_entry.session_id[:8] in response_text- @pytest.mark.asyncio- async def test_new_is_idempotent(self, adapter, runner, platform):- """/new called twice should not crash."""- await send_and_capture(adapter, "/new", platform)- await send_and_capture(adapter, "/new", platform)- assert runner.session_store.reset_session.call_count == 2class TestAuthorization:diff --git a/tests/evals/test_codebase_navigability.py b/tests/evals/test_codebase_navigability.pyindex 1c012e84209..38e4b1c407b 100644--- a/tests/evals/test_codebase_navigability.py+++ b/tests/evals/test_codebase_navigability.py@@ -20,27 +20,6 @@ def mods():return bench.source_modules(ROOT)-def test_resolver_follows_reexport_to_defining_sibling(mods):- cache: dict = {}- # gateway.run re-exports names it no longer defines; each must resolve to a gateway.run_* sibling- src = (ROOT / "gateway" / "run.py").read_text(encoding="utf-8")- rex = bench._reexports(src)- moved = [(n, m) for n, (m, _) in rex.items() if m.startswith("gateway.run_")]- assert moved, "expected gateway.run to re-export from gateway.run_* siblings"- for name, expected in moved[:20]:- got = bench.resolve_definer(mods, name, "gateway.run", cache)- assert got == expected, (name, got, expected)---def test_resolver_keeps_facade_defined_names_on_facade(mods):- cache: dict = {}- src = (ROOT / "hermes_state.py").read_text(encoding="utf-8")- own = [n for n, (_, _, node) in bench.top_level_defs(src).items() if not bench._is_alias(node)]- assert own, "hermes_state.py should still define something at top level"- for name in own[:20]:- assert bench.resolve_definer(mods, name, "hermes_state", cache) == "hermes_state", name--def test_tokenizer_falls_back_without_crashing(monkeypatch):import builtinsreal_import = builtins.__import__diff --git a/tests/gateway/relay/stub_connector.py b/tests/gateway/relay/stub_connector.pyindex f74f5f659bd..9417429662f 100644--- a/tests/gateway/relay/stub_connector.py+++ b/tests/gateway/relay/stub_connector.py@@ -1,7 +1,6 @@"""Test-only in-memory stub connector implementing RelayTransport.-MUST stay under tests/ — never under plugins/ or gateway/ (a CI guard in-test_no_stub_leak.py asserts this). It lets Phase 1 prove the gateway side of+MUST stay under tests/ — never under plugins/ or gateway/. It lets Phase 1 prove the gateway side ofthe relay end-to-end with zero dependency on the real (Node) connector.The stub:diff --git a/tests/gateway/relay/test_contract_doc_conformance.py b/tests/gateway/relay/test_contract_doc_conformance.pydeleted file mode 100644index ccf4e89bf1f..00000000000--- a/tests/gateway/relay/test_contract_doc_conformance.py+++ /dev/null@@ -1,126 +0,0 @@-"""Cross-repo contract conformance: website/docs/developer-guide/relay-connector-contract.md ⟷ Python.--The contract doc is the formal interface the connector repo-(NousResearch/gateway-gateway) implements against. The connector's TypeScript-structs are hand-mirrored from the doc, so if the Python source of truth drifts-from the doc, the two repos silently diverge and the handshake / session-keying-breaks only at integration time.--These tests make the doc ⟷ code relationship an enforced invariant:-- * Every ``CapabilityDescriptor`` field (§2 table) is documented with the- correct required/optional flag, and the doc lists no fields the dataclass- lacks.- * Every ``SessionSource`` wire key (what ``to_dict()`` actually serializes)- is named in the contract doc's §3 discriminator section, and every- discriminator the doc calls out as a column header exists on the dataclass.--They are invariants, NOT change-detector snapshots: they assert the *relation*-between two artifacts that must move together, not a frozen list of names. Add-a field to the descriptor and the doc, and the test stays green; add it to only-one, and CI fails — which is exactly the lockstep guarantee the plan's-Cross-Repo Coordination Checklist calls for.-"""--from __future__ import annotations--import re-from pathlib import Path--import pytest--from gateway.relay.descriptor import CapabilityDescriptor-from gateway.session import SessionSource--# Repo root: tests/gateway/relay/ -> repo root is parents[3]-_CONTRACT_DOC = (- Path(__file__).resolve().parents[3] / "website" / "docs" / "developer-guide" / "relay-connector-contract.md"-)---def _doc_text() -> str:- assert _CONTRACT_DOC.exists(), (- f"Contract doc missing at {_CONTRACT_DOC}. It is the formal cross-repo "- f"interface (Phase 1, Task 1.5) and must ship with the relay adapter."- )- return _CONTRACT_DOC.read_text(encoding="utf-8")---def _parse_descriptor_table(text: str) -> dict[str, bool]:- """Parse §2's markdown table → {field_name: required}.-- Rows look like: ``| `field` | type | yes|no | meaning |``. Returns a map of- field name to whether the Required column says "yes".- """- fields: dict[str, bool] = {}- # Restrict to the §2 section so §3/§4 tables don't bleed in.- section = text.split("## 2. CapabilityDescriptor", 1)[-1].split("## 3.", 1)[0]- row_re = re.compile(r"^\|\s*`([a-z_]+)`\s*\|[^|]*\|\s*(yes|no)\s*\|", re.M)- for name, required in row_re.findall(section):- fields[name] = required.strip() == "yes"- return fields---def test_descriptor_fields_match_contract_doc():- """§2 table ⟷ CapabilityDescriptor dataclass, names + required/optional."""- documented = _parse_descriptor_table(_doc_text())- assert documented, "Failed to parse any descriptor fields from the §2 table."-- dc_fields = CapabilityDescriptor.__dataclass_fields__ # type: ignore[attr-defined]- # A dataclass field is "required" iff it has no default and no default_factory.- import dataclasses-- code_required = {- name- for name, f in dc_fields.items()- if f.default is dataclasses.MISSING- and f.default_factory is dataclasses.MISSING # type: ignore[misc]- }- code_names = set(dc_fields.keys())- doc_names = set(documented.keys())-- missing_from_doc = code_names - doc_names- assert not missing_from_doc, (- f"CapabilityDescriptor fields missing from the §2 contract-doc table: "- f"{sorted(missing_from_doc)}. Document them so the connector mirrors them."- )- extra_in_doc = doc_names - code_names- assert not extra_in_doc, (- f"Contract-doc §2 table documents fields the dataclass does not have: "- f"{sorted(extra_in_doc)}. Remove them or add them to descriptor.py."- )-- # Required/optional must agree, so the connector knows which fields it may omit.- for name, doc_required in documented.items():- assert doc_required == (name in code_required), (- f"Field '{name}': contract doc says required={doc_required}, but the "- f"dataclass says required={name in code_required}. Reconcile them."- )---def _session_source_wire_keys() -> set[str]:- """Keys ``SessionSource.to_dict()`` can emit (the actual wire surface).-- Build a maximally-populated source so conditionally-included keys (the- ``if self.x:`` branches in ``to_dict``) all appear.- """- from gateway.config import Platform-- src = SessionSource(- platform=Platform.DISCORD,- chat_id="c",- chat_name="n",- chat_type="channel",- user_id="u",- user_name="un",- thread_id="t",- chat_topic="topic",- user_id_alt="ua",- chat_id_alt="ca",- guild_id="g",- parent_chat_id="p",- message_id="m",- )- return set(src.to_dict().keys())--diff --git a/tests/gateway/relay/test_descriptor.py b/tests/gateway/relay/test_descriptor.pyindex a84905f2d4a..ded8cd2d079 100644--- a/tests/gateway/relay/test_descriptor.py+++ b/tests/gateway/relay/test_descriptor.py@@ -22,20 +22,8 @@ def _telegram_descriptor(**overrides) -> CapabilityDescriptor:return CapabilityDescriptor(**base)-def test_descriptor_is_frozen():- d = _telegram_descriptor()- try:- d.max_message_length = 1 # type: ignore[misc]- except Exception as exc: # FrozenInstanceError- assert "cannot assign" in str(exc) or "frozen" in str(exc).lower()- else: # pragma: no cover- raise AssertionError("descriptor should be immutable (frozen)")-def test_module_is_marked_experimental():- import gateway.relay.descriptor as m-- assert "EXPERIMENTAL" in (m.__doc__ or "")# ─────────────── supported_ops (op-level capability discovery, Phase 1) ───────────────diff --git a/tests/gateway/relay/test_no_stub_leak.py b/tests/gateway/relay/test_no_stub_leak.pydeleted file mode 100644index ec97bef7050..00000000000--- a/tests/gateway/relay/test_no_stub_leak.py+++ /dev/null@@ -1,44 +0,0 @@-"""CI guard: the test-only StubConnector must never leak into production paths.--The relay stub connector lives under tests/ and exists only to prove the-gateway side of the relay without the real (Node) connector. If it ever appears-under gateway/ or plugins/, that's a production leak — fail loudly.-"""--from __future__ import annotations--import pathlib-import re--_REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]-_FORBIDDEN_DIRS = ("gateway", "plugins")-# Match actual code leaks (imports / class definitions), not prose mentions in-# docstrings/comments. A production file that *imports* the stub or *defines*-# StubConnector is a real leak; a docstring that references the stub's path as-# documentation is not.-_LEAK_PATTERNS = (- re.compile(r"^\s*(?:from|import)\s+.*stub_connector", re.MULTILINE),- re.compile(r"^\s*(?:from|import)\s+.*\bStubConnector\b", re.MULTILINE),- re.compile(r"^\s*class\s+StubConnector\b", re.MULTILINE),-)---def test_stub_connector_does_not_leak_into_production_paths():- offenders: list[str] = []- for top in _FORBIDDEN_DIRS:- base = _REPO_ROOT / top- if not base.is_dir():- continue- for path in base.rglob("*.py"):- try:- text = path.read_text(encoding="utf-8", errors="ignore")- except OSError: # pragma: no cover- continue- for pat in _LEAK_PATTERNS:- if pat.search(text):- offenders.append(- f"{path.relative_to(_REPO_ROOT)} matches {pat.pattern!r}"- )- assert not offenders, (- "relay test stub leaked into production paths:\n " + "\n ".join(offenders)- )diff --git a/tests/gateway/relay/test_relay_adapter.py b/tests/gateway/relay/test_relay_adapter.pyindex 09d3c901096..0b46e535063 100644--- a/tests/gateway/relay/test_relay_adapter.py+++ b/tests/gateway/relay/test_relay_adapter.py@@ -32,8 +32,6 @@ def _adapter(**desc_kw) -> RelayAdapter:return RelayAdapter(PlatformConfig(), make_desc(**desc_kw))-def test_relay_platform_member_exists():- assert Platform("relay") is Platform.RELAYdef test_advertises_descriptor_max_length():@@ -41,21 +39,6 @@ def test_advertises_descriptor_max_length():assert a.MAX_MESSAGE_LENGTH == 2000-def test_supports_draft_streaming_follows_descriptor():- # NS-658: the flag alone no longer advertises drafts — before the- # "draft" op existed, flag=True was a latent lie (send_draft inherited- # NotImplementedError). Advertisement now requires flag AND op.- assert _adapter(supports_draft_streaming=False).supports_draft_streaming() is False- assert (- _adapter(supports_draft_streaming=False, supported_ops=("send", "draft"))- .supports_draft_streaming()- is False- ), "op without flag must not advertise"- assert (- _adapter(supports_draft_streaming=True, supported_ops=("send", "draft"))- .supports_draft_streaming()- is True- )def test_len_fn_utf16_counts_code_units():@@ -64,30 +47,8 @@ def test_len_fn_utf16_counts_code_units():assert a.message_len_fn("\U0001f600") == 2-def test_is_a_base_platform_adapter():- # stream_consumer's isinstance(adapter, BasePlatformAdapter) guard must pass.- from gateway.platforms.base import BasePlatformAdapter-- assert isinstance(_adapter(), BasePlatformAdapter)---def test_connect_signature_matches_base_contract():- """The is_reconnect parameter must be keyword-accepting and default False,- matching BasePlatformAdapter.connect, so the reconnect watcher's- ``connect(is_reconnect=...)`` call is valid for relay as for every other- adapter."""- import inspect- from gateway.platforms.base import BasePlatformAdapter- sig = inspect.signature(RelayAdapter.connect)- base_sig = inspect.signature(BasePlatformAdapter.connect)- assert "is_reconnect" in sig.parameters- param = sig.parameters["is_reconnect"]- base_param = base_sig.parameters["is_reconnect"]- # Keyword-acceptable (KEYWORD_ONLY here, matching the base) with a False default.- assert param.kind is base_param.kind- assert param.default is Falseclass _CaptureTransport:diff --git a/tests/gateway/relay/test_relay_format_hints.py b/tests/gateway/relay/test_relay_format_hints.pyindex 0c756809277..38e142b35a1 100644--- a/tests/gateway/relay/test_relay_format_hints.py+++ b/tests/gateway/relay/test_relay_format_hints.py@@ -17,7 +17,6 @@ stamp, so connectors keep rendering plain text."""import json-from types import SimpleNamespaceimport pytest@@ -67,8 +66,6 @@ def _adapter(extra=None, descriptor=None, transport=None):class TestDescriptorBit:- def test_default_false(self):- assert _descriptor().supports_block_formatting is Falsedef test_from_json_reads_flag(self):payload = dict(diff --git a/tests/gateway/relay/test_relay_going_idle.py b/tests/gateway/relay/test_relay_going_idle.pyindex fefb61bda49..1f607b6bf1d 100644--- a/tests/gateway/relay/test_relay_going_idle.py+++ b/tests/gateway/relay/test_relay_going_idle.py@@ -283,26 +283,6 @@ def test_adapter_reports_false_when_the_transport_hold_fails():assert working.calls == ["hold"]-async def test_adapter_redial_hold_delegates_to_transport(server):- """The runner only holds the adapter, so this delegation is the only thing- wiring its suspend decision to the transport."""- from gateway.config import PlatformConfig- from gateway.relay.adapter import RelayAdapter-- placeholder = _relay_descriptor()- transport = WebSocketRelayTransport(- server.url, "discord", "appShared", reconnect=True, reconnect_backoff_s=0.05- )- adapter = RelayAdapter(PlatformConfig(), placeholder, transport=transport)- await adapter.connect()- try:- adapter.hold_redial()- assert transport._redial_held is True- adapter.release_redial()- assert transport._redial_held is False- finally:- await adapter.disconnect()@pytest.mark.asynciodiff --git a/tests/gateway/relay/test_relay_inbound_dedupe.py b/tests/gateway/relay/test_relay_inbound_dedupe.pyindex 9f7118831d5..b883425ac44 100644--- a/tests/gateway/relay/test_relay_inbound_dedupe.py+++ b/tests/gateway/relay/test_relay_inbound_dedupe.py@@ -170,14 +170,6 @@ class TestWireLevelReplayDedupe:raw["source"] = {**self.WIRE["source"], **overrides["source"]}return _event_from_wire(raw)- def test_decoded_event_yields_a_dedupe_key(self):- adapter, _ = _connected_adapter()- key = adapter._inbound_dedupe_key(self._decode())- assert key is not None, (- "the wire decoder's event shape must produce a dedupe key — "- "None here means the dedupe is fail-open for ALL production "- "traffic (the original ship-broken state)"- )def test_replayed_wire_frame_dropped(self, loop):adapter, _ = _connected_adapter()diff --git a/tests/gateway/relay/test_relay_inchannel_continuable.py b/tests/gateway/relay/test_relay_inchannel_continuable.pyindex 119b93b9409..25b49fbae6c 100644--- a/tests/gateway/relay/test_relay_inchannel_continuable.py+++ b/tests/gateway/relay/test_relay_inchannel_continuable.py@@ -18,7 +18,6 @@ lane. Three gaps, each pinned here:from types import SimpleNamespace-import pytestfrom gateway.relay.descriptor import CapabilityDescriptorfrom cron.scheduler_delivery import _resolve_cron_surface_mode@@ -41,9 +40,6 @@ def _descriptor(**overrides):class TestDescriptorCapabilityBit:- def test_defaults_false(self):- d = _descriptor()- assert d.supports_inchannel_continuable is Falsedef test_from_json_reads_flag(self):import json@@ -80,13 +76,7 @@ class TestRelayAdapterCapabilityMapping:config = PlatformConfig(enabled=True, extra={})return RelayAdapter(config, descriptor)- def test_adapter_maps_descriptor_flag_true(self):- adapter = self._adapter(_descriptor(supports_inchannel_continuable=True))- assert getattr(adapter, "supports_inchannel_continuable", False) is True- def test_adapter_maps_descriptor_flag_false(self):- adapter = self._adapter(_descriptor())- assert getattr(adapter, "supports_inchannel_continuable", True) is Falsedef test_renegotiation_updates_flag(self):"""_apply_descriptor must carry the bit, like supports_code_blocks."""diff --git a/tests/gateway/relay/test_relay_passthrough.py b/tests/gateway/relay/test_relay_passthrough.pyindex e19c6d6a37f..9ceb2d465c3 100644--- a/tests/gateway/relay/test_relay_passthrough.py+++ b/tests/gateway/relay/test_relay_passthrough.py@@ -97,13 +97,6 @@ def test_passthrough_from_wire_stamps_routed_profile():assert fwd.profile == "reviewer"-async def test_connect_wires_passthrough_handler_over_ws(adapter):- """connect() registers the passthrough handler on the transport so a- connector-delivered passthrough_forward frame reaches the adapter."""- await adapter.connect()- stub = adapter._transport- assert stub._passthrough is not None@pytest.mark.asynciodiff --git a/tests/gateway/relay/test_relay_roundtrip.py b/tests/gateway/relay/test_relay_roundtrip.pyindex cbdaca12b36..3a7a4b05bf8 100644--- a/tests/gateway/relay/test_relay_roundtrip.py+++ b/tests/gateway/relay/test_relay_roundtrip.py@@ -16,11 +16,10 @@ import pytestfrom gateway.config import Platform, PlatformConfigfrom gateway.platforms.event import MessageEvent, MessageType-from gateway.session import SessionSource, build_session_key+from gateway.session import SessionSourcefrom gateway.relay.adapter import RelayAdapterfrom gateway.relay.descriptor import CONTRACT_VERSION, CapabilityDescriptor-from dataclasses import replacefrom tests.gateway.relay.stub_connector import StubConnector@@ -61,14 +60,6 @@ def wired():return adapter, stub-async def test_connect_registers_inbound_handler(wired):- adapter, stub = wired- assert stub._inbound is None- ok = await adapter.connect()- assert ok is True- assert stub.connected is True- assert stub._inbound is not None@pytest.mark.asynciodiff --git a/tests/gateway/relay/test_relay_sheds_crypto.py b/tests/gateway/relay/test_relay_sheds_crypto.pydeleted file mode 100644index 0d84c7b8ae0..00000000000--- a/tests/gateway/relay/test_relay_sheds_crypto.py+++ /dev/null@@ -1,90 +0,0 @@-"""Invariant: the relay path sheds platform crypto — it re-validates nothing.--Under the A2 trust model (see website/docs/developer-guide/relay-connector-contract.md §6), the-*connector* is the sole crypto/identity boundary: it verifies/decrypts every-inbound platform payload at the edge (it holds the tenant secrets), normalizes-it to a tenant-scoped ``MessageEvent``, and forwards only the sanitized event.-The gateway re-validates nothing — it cannot, without being handed the shared-signing secret, which would itself be the leak on a shared bot.--The relay package therefore MUST NOT import or call platform signature/crypto-verification (Discord ed25519, Twilio HMAC, WeCom BizMsgCrypt, generic webhook-signature checks). Those live in the *direct* platform adapters-(``gateway/platforms/*``) which serve non-relay deployments; the relay receives-already-trusted events. This test fails if someone bolts re-validation onto the-relay path, re-coupling the gateway to platform secrets it must never hold.--It is an invariant (asserts the *relation* "relay imports no crypto"), not a-change-detector snapshot of a frozen import list.-"""--from __future__ import annotations--import ast-import re-from pathlib import Path--# gateway/relay package directory: tests/gateway/relay/ -> repo root parents[3].-_REPO_ROOT = Path(__file__).resolve().parents[3]-_RELAY_PKG = _REPO_ROOT / "gateway" / "relay"--# Modules / symbols that mean "platform crypto re-validation". If the relay path-# imports any of these it has re-coupled the gateway to a platform secret.-_FORBIDDEN_MODULE_TOKENS = (- "wecom_crypto",- "wecom_callback",- "webhook", # gateway.platforms.webhook holds signature verification-)-_FORBIDDEN_SYMBOL_RE = re.compile(- r"(ed25519|verify_key|verifykey|verify_signature|verify_ed25519|"- r"verify_webhook|bizmsg|hmac|x[-_]signature)",- re.IGNORECASE,-)---def _relay_py_files() -> list[Path]:- assert _RELAY_PKG.is_dir(), f"relay package missing at {_RELAY_PKG}"- return sorted(_RELAY_PKG.glob("*.py"))---# ``auth.py`` is the connector⇄gateway CHANNEL authenticator (the gateway's WS-# upgrade bearer). It is net-new, intended, and the whole point of-# authenticating an untrusted/disposable gateway — it is NOT platform crypto.-# It uses HMAC over the connector's per-gateway secret (NOT any platform's-# signing secret), so it is exempt from the platform-crypto symbol scan below.-# The module-import ban (platform-crypto modules) still applies to every file-# including this one — it imports only stdlib hmac/hashlib, never a-# platform-crypto module, so it stays clean there.-_CHANNEL_AUTH_FILES = {"auth.py"}---def test_relay_package_calls_no_signature_verification():- """No relay module references a PLATFORM signature/crypto-verification symbol.-- Scoped to platform crypto (Discord ed25519, Twilio/WeCom HMAC, webhook- signature checks). The connector⇄gateway channel authenticator (``auth.py``)- is exempt: its HMAC is over the connector's own per-gateway/per-tenant- secrets to authenticate the relay channel itself — the gateway holds NO- platform secret and re-validates NO platform payload. See ``auth.py`` and- docs/connector-gateway-auth-design.md.- """- offenders: list[str] = []- for path in _relay_py_files():- if path.name in _CHANNEL_AUTH_FILES:- continue- for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):- # Skip comments / docstrings-as-prose: only flag code-like usage.- stripped = line.strip()- if stripped.startswith("#"):- continue- m = _FORBIDDEN_SYMBOL_RE.search(line)- if m:- offenders.append(f"{path.name}:{lineno}: '{m.group(0)}' in: {stripped[:80]}")- assert not offenders, (- "The relay path must not perform platform signature/crypto verification "- "(A2). Found verification-symbol references:\n "- + "\n ".join(offenders)- + "\nThe connector verifies at the edge; the gateway re-validates nothing."- )--diff --git a/tests/gateway/relay/test_relay_slack_dm_streaming.py b/tests/gateway/relay/test_relay_slack_dm_streaming.pyindex 31651f61da2..d44c026504c 100644--- a/tests/gateway/relay/test_relay_slack_dm_streaming.py+++ b/tests/gateway/relay/test_relay_slack_dm_streaming.py@@ -375,12 +375,6 @@ def test_relay_slack_flags_coerce_like_native(raw, expected):assert adapter._dm_top_level_threads_as_sessions() is expected-def test_relay_slack_flags_default_true_when_absent():- """Both knobs default ON when the operator sets nothing."""- adapter, _stub = _wire("D1", "dm")- adapter.config.extra = {}- assert adapter._effective_reply_in_thread() is True- assert adapter._dm_top_level_threads_as_sessions() is True# ---------------------------------------------------------------------------diff --git a/tests/gateway/relay/test_relay_stream_semantics_gating.py b/tests/gateway/relay/test_relay_stream_semantics_gating.pyindex b2943a35bd7..584e1c3d2eb 100644--- a/tests/gateway/relay/test_relay_stream_semantics_gating.py+++ b/tests/gateway/relay/test_relay_stream_semantics_gating.py@@ -33,17 +33,7 @@ class RecordingTransport:class TestStreamIsMessageGating:- def test_slack_descriptor_gets_stream_is_message(self):- adapter, _ = _connected_adapter() # platform="slack" default- assert adapter.draft_stream_is_message is True- def test_telegram_descriptor_does_not(self):- adapter, _ = _connected_adapter(- platform="telegram",- markdown_dialect="markdown_v2",- supported_ops=("send", "edit", "typing", "draft"),- )- assert adapter.draft_stream_is_message is False@pytest.mark.asyncioasync def test_telegram_final_is_a_real_send_not_a_seal(self):diff --git a/tests/gateway/relay/test_self_provision.py b/tests/gateway/relay/test_self_provision.pyindex 96f38e15db5..347597b675d 100644--- a/tests/gateway/relay/test_self_provision.py+++ b/tests/gateway/relay/test_self_provision.py@@ -135,15 +135,6 @@ def test_outbound_only_when_no_endpoint(monkeypatch):# ─────────────────── instance-id forwarding (Phase 6 Unit α) ───────────────────-def test_instance_id_absent_forwards_none(monkeypatch):- """No stamp (self-hosted / pre-Phase-6) -> instance_id None; the connector- stores null and per-instance routing simply has no binding yet."""- _arm(monkeypatch)- captured: dict = {}- monkeypatch.setattr(relay, "_post_provision", _stub_post(captured))-- assert relay.self_provision_relay() is True- assert captured["instance_id"] is Nonedef test_post_provision_body_includes_instanceId_only_when_set(monkeypatch):@@ -212,15 +203,6 @@ def test_forwards_wake_url_to_provision(monkeypatch):assert captured["wake_url"] == "https://wake.example/poke"-def test_wake_url_absent_forwards_none(monkeypatch):- """No stamp (self-hosted / non-suspendable) -> wake_url None; the connector- stores null and simply never pokes (it can't wake what it can't reach)."""- _arm(monkeypatch)- captured: dict = {}- monkeypatch.setattr(relay, "_post_provision", _stub_post(captured))-- assert relay.self_provision_relay() is True- assert captured["wake_url"] is None# ─────────────────────────── fail-soft ───────────────────────────diff --git a/tests/gateway/relay/test_ws_transport_hardening.py b/tests/gateway/relay/test_ws_transport_hardening.pyindex 5ae62b3f3cc..f565d77c08c 100644--- a/tests/gateway/relay/test_ws_transport_hardening.py+++ b/tests/gateway/relay/test_ws_transport_hardening.py@@ -206,52 +206,6 @@ async def test_send_allowed_once_redial_installs_fresh_socket(monkeypatch):pass-async def test_connect_passes_wan_keepalive_tuning(monkeypatch):- """connect() must pass ping_interval=30 / ping_timeout=60 explicitly —- the library defaults (20/20) caused spurious 1011 keepalive closes over- WAN paths (Coatue 2026-08-18). Both call sites (with/without auth- headers) are exercised."""- captured: list[dict] = []-- class _IdleWS:- async def send(self, data):- pass-- def __aiter__(self):- return self-- async def __anext__(self):- await asyncio.sleep(3600)-- async def close(self):- pass-- async def _fake_connect(url, **kwargs):- captured.append(kwargs)- return _IdleWS()-- monkeypatch.setattr(ws_transport_mod.websockets, "connect", _fake_connect)-- # Site 1: no upgrade secret -> the headerless connect() call.- t = WebSocketRelayTransport("ws://unused", "discord", "bot1")- await t.connect()- await t.disconnect(budget_s=0)-- # Site 2: secret + gateway_id -> the additional_headers connect() call.- t2 = WebSocketRelayTransport(- "ws://unused", "discord", "bot1", gateway_id="gw-1", upgrade_secret="s3cret"- )- await t2.connect()- await t2.disconnect(budget_s=0)-- assert len(captured) == 2- no_header_kwargs, header_kwargs = captured- assert "additional_headers" not in no_header_kwargs- assert "additional_headers" in header_kwargs- for kwargs in captured:- assert kwargs.get("ping_interval") == 30- assert kwargs.get("ping_timeout") == 60async def _run_reader_to_exit(t: WebSocketRelayTransport, fake: _DroppingWS) -> None:diff --git a/tests/gateway/test_active_session_text_merge.py b/tests/gateway/test_active_session_text_merge.pyindex acba6f479ec..4fa77352449 100644--- a/tests/gateway/test_active_session_text_merge.py+++ b/tests/gateway/test_active_session_text_merge.py@@ -246,18 +246,3 @@ async def test_control_and_clarify_messages_bypass_text_debounce():adapter._message_handler.assert_awaited_once_with(answer)assert session_key not in adapter._text_debounceassert session_key not in adapter._pending_messages---def test_adapter_defaults_to_interrupt_mode(monkeypatch):- monkeypatch.delenv("HERMES_GATEWAY_BUSY_TEXT_MODE", raising=False)- adapter = _make_initialized_adapter()- assert adapter._busy_text_mode == "interrupt"- assert not adapter._is_queue_text_debounce_candidate(_make_event("hello"))---def test_command_messages_bypass_debounce_even_in_queue_mode():- adapter = _make_adapter()- assert not adapter._is_queue_text_debounce_candidate(_make_event(""))- assert not adapter._is_queue_text_debounce_candidate(_make_event("/stop"))--diff --git a/tests/gateway/test_active_turn_recovery.py b/tests/gateway/test_active_turn_recovery.pyindex bd859325c53..5fa76c112a7 100644--- a/tests/gateway/test_active_turn_recovery.py+++ b/tests/gateway/test_active_turn_recovery.py@@ -126,29 +126,6 @@ def test_active_turn_clear_is_compare_and_swap(tmp_path):assert current.active_turn_started_at is None-def test_mark_and_clear_use_single_entry_persistence(tmp_path):- store = _make_store(tmp_path)- entry = store.get_or_create_session(_make_source())- real_save_entry = store._save_entry- store._save_entry = MagicMock(wraps=real_save_entry)-- token = store.mark_turn_active(entry.session_key)- assert token is not None- store._save_entry.assert_called_once_with(- entry.session_key,- entry_data=store._entries[entry.session_key].to_dict(),- lock_held=True,- )-- store._save_entry.reset_mock()- assert store.clear_turn_active(entry.session_key, token) is True- store._save_entry.assert_called_once_with(- entry.session_key,- entry_data=store._entries[entry.session_key].to_dict(),- lock_held=True,- )--def test_failed_mark_persistence_does_not_leak_marker_into_later_save(tmp_path):store = _make_store(tmp_path)source = _make_source()diff --git a/tests/gateway/test_adapter_connect_classification.py b/tests/gateway/test_adapter_connect_classification.pyindex ae6a5d1b2a3..a0f8bcaadfa 100644--- a/tests/gateway/test_adapter_connect_classification.py+++ b/tests/gateway/test_adapter_connect_classification.py@@ -69,8 +69,6 @@ class TestTelegramAuthClassification:def test_network_error_is_not_auth_error(self):assert _telegram_classifier()(NetworkError("dns failure")) is False- def test_timeout_is_not_auth_error(self):- assert _telegram_classifier()(TimedOut("read timeout")) is Falsedef test_generic_exception_is_not_auth_error(self):# Unknown types must stay retryable — a false terminal recreates the@@ -107,23 +105,21 @@ def _discord_classifier():class TestDiscordConnectClassification:def test_login_failure_is_terminal(self):- code, message, retryable = _discord_classifier()(LoginFailure("Improper token"))+ code, _message, retryable = _discord_classifier()(LoginFailure("Improper token"))assert code == "discord_auth_error"assert retryable is False- assert "Developer Portal" in messagedef test_privileged_intents_is_terminal(self):- code, message, retryable = _discord_classifier()(+ code, _message, retryable = _discord_classifier()(PrivilegedIntentsRequired("shard 0 requested privileged intents"))assert code == "discord_intents_required"assert retryable is False- assert "Message Content Intent" in messagedef test_unknown_exception_is_retryable_with_explicit_code(self):# The old behavior set NO fatal code at all, which the gateway read# as "probably transient". Every failure must now carry a code.- code, message, retryable = _discord_classifier()(OSError("connection reset"))+ code, _message, retryable = _discord_classifier()(OSError("connection reset"))assert code == "discord_connect_error"assert retryable is True