The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(cron): replace fail-closed drift tests with snapshot-as-pin invariants
Tekniumbcff0a920ed5
diff --git a/apps/desktop/src/store/cron-model-impact.test.ts b/apps/desktop/src/store/cron-model-impact.test.tsindex 56c101e8671..1505f8e2f3d 100644--- a/apps/desktop/src/store/cron-model-impact.test.ts+++ b/apps/desktop/src/store/cron-model-impact.test.ts@@ -43,7 +43,6 @@ function response(impact: ModelAssignmentResponse['cron_model_impact']): ModelAsfunction positive(name = 'Morning summary'): ModelAssignmentResponse['cron_model_impact'] {return {available: true,- guard_enabled: true,affected_count: 1,truncated: false,jobs: [{ id: 'job-1', name, drifted_axes: ['provider', 'model'] }]@@ -71,9 +70,9 @@ describe('setMainModelAssignment', () => {model: 'new/model'})const notification = $notifications.get().find(item => item.id === CRON_MODEL_IMPACT_NOTIFICATION_ID)- expect(notification?.kind).toBe('warning')- expect(notification?.title).toBe('Scheduled jobs need review')- expect(notification?.message).toContain('1 scheduled job will be skipped')+ expect(notification?.kind).toBe('info')+ expect(notification?.title).toBe('Scheduled jobs stay on their original model')+ expect(notification?.message).toContain('1 unpinned scheduled job keeps running on the model it was created under')expect(notification?.detail).toContain('Morning summary')expect(notification?.action?.label).toBe('Review scheduled jobs')@@ -86,8 +85,7 @@ describe('setMainModelAssignment', () => {setModelAssignment.mockResolvedValue(response({available: true,- guard_enabled: true,- affected_count: 2,+ affected_count: 2,truncated: false,jobs: [{ id: 'job-1', name: 'One', drifted_axes: ['provider'] }]})@@ -114,8 +112,7 @@ describe('setMainModelAssignment', () => {setModelAssignment.mockResolvedValueOnce(response({available: true,- guard_enabled: true,- affected_count: 0,+ affected_count: 0,truncated: false,jobs: []})@@ -265,19 +262,6 @@ describe('setMainModelAssignment', () => {expect($cronReviewRequest.get()).toBe(requestCount)})- it('clears an obsolete warning when the drift guard is disabled', async () => {- setModelAssignment.mockResolvedValueOnce(response(positive()))- await setMainModelAssignment({ provider: 'nous', model: 'one' })- expect($notifications.get()).toHaveLength(1)-- setModelAssignment.mockResolvedValueOnce(- response({ available: true, guard_enabled: false, affected_count: 0, truncated: false, jobs: [] })- )- await setMainModelAssignment({ provider: 'nous', model: 'two' })-- expect($notifications.get()).toEqual([])- })-it('does not let a dismissed notification mutate cron configuration', async () => {setModelAssignment.mockResolvedValue(response(positive()))await setMainModelAssignment({ provider: 'nous', model: 'new/model' })diff --git a/tests/cron/test_cron_drift_alert_once.py b/tests/cron/test_cron_drift_alert_once.pydeleted file mode 100644index 5beba4109fd..00000000000--- a/tests/cron/test_cron_drift_alert_once.py+++ /dev/null@@ -1,161 +0,0 @@-"""Drift-guard skips must alert once per job, not once per tick (#44585 + #73506).--Field report: a fleet-wide config change moved the global-default provider and every unpinned cron started alerting on every tick —-40 jobs x N ticks of identical "Skipped to prevent unintended spend" spam.-The #44585 drift guard correctly fails closed; this wires the existing-#73506 alert-once shape (persisted per-job bit, cleared when the condition-heals) to the drift branch, exactly as pre-dispatch preflight already does-for blocked_config.--Contract:-- First drifted tick delivers ONE loud, actionable alert.-- Subsequent drifted ticks deliver nothing.-- When drift heals (guard passes again), the bit clears, so a FUTURE drift- re-alerts instead of being silently swallowed.-- Only the drift branch gets the bit — other failures keep alerting per tick.-"""--import sys-from pathlib import Path-from unittest.mock import MagicMock, patch--sys.path.insert(0, str(Path(__file__).parent.parent.parent))--import cron.jobs as cron_jobs-import cron.scheduler as sched---def _job(**overrides):- job = {- "id": "drift-once-test",- "name": "drift once test",- "prompt": "hello",- "enabled": True,- "state": "scheduled",- "schedule": {"kind": "interval", "minutes": 5, "display": "every 5m"},- "deliver": "local",- "model": None,- "provider": None,- "provider_snapshot": "openrouter",- "base_url": None,- }- job.update(overrides)- return job---def _tick(job, tmp_path, current_provider, deliveries):- """Run one run_one_job tick with the provider resolution pinned."""- fake_db = MagicMock()-- def fake_deliver(job, content, adapters=None, loop=None, **kwargs):- deliveries.append(content)- return None-- 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("tools.mcp_tool_discovery.discover_mcp_tools", return_value=[]), \- patch("hermes_cli.runtime_provider.resolve_runtime_provider",- return_value={- "api_key": "test-key",- "base_url": "https://example.invalid/v1",- "provider": current_provider,- "api_mode": "chat_completions",- }), \- patch.object(sched, "_deliver_result", side_effect=fake_deliver), \- 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- ok = sched.run_one_job(job)- return ok, mock_agent_cls.called---class TestDriftAlertOnce:- def test_two_drifted_ticks_alert_exactly_once(self, tmp_path):- job = _job()- deliveries = []- with cron_jobs.use_cron_store(tmp_path):- cron_jobs.save_jobs([job])- for _ in range(2):- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]- ok, agent_called = _tick(fresh, tmp_path, "nous", deliveries)- assert agent_called is False, "drifted tick must not spend"-- stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]- assert stored.get("drift_alerted") is True-- assert len(deliveries) == 1, f"expected 1 alert, got {len(deliveries)}: {deliveries}"- blob = deliveries[0].lower()- assert "drift" in blob- assert "pin" in blob- assert "host running hermes" in blob- # The single alert must carry the complete supported remediation- # command — the generic summarizer's 180-char truncation must not eat it.- assert "hermes cron edit drift-once-test" in deliveries[0]- assert "cronjob action=update" not in deliveries[0]- assert "[drift_skip" not in deliveries[0]-- def test_healed_drift_clears_bit_and_redrift_realerts(self, tmp_path):- job = _job()- deliveries = []- with cron_jobs.use_cron_store(tmp_path):- cron_jobs.save_jobs([job])- # Tick 1: drifted -> one alert, bit set.- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]- _tick(fresh, tmp_path, "nous", deliveries)- assert len(deliveries) == 1-- # Tick 2: drift healed (resolution matches snapshot) -> runs, bit cleared.- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]- ok, agent_called = _tick(fresh, tmp_path, "openrouter", deliveries)- assert agent_called is True- stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]- assert not stored.get("drift_alerted")-- # Tick 3: drifts again -> re-alerts (not swallowed).- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]- _tick(fresh, tmp_path, "nous", deliveries)-- drift_alerts = [d for d in deliveries if "drift" in d.lower()]- assert len(drift_alerts) == 2, f"expected re-alert after heal: {deliveries}"-- def test_non_drift_failures_untouched_by_the_bit(self, tmp_path):- """A job with the drift bit set whose run fails for another reason- still alerts — only the drift branch consults the bit."""- job = _job(provider_snapshot=None, drift_alerted=True)- deliveries = []-- def fake_deliver(jb, content, adapters=None, loop=None, **kwargs):- deliveries.append(content)- return None-- fake_db = MagicMock()- with cron_jobs.use_cron_store(tmp_path):- cron_jobs.save_jobs([job])- fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]- 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("tools.mcp_tool_discovery.discover_mcp_tools", return_value=[]), \- patch("hermes_cli.runtime_provider.resolve_runtime_provider",- return_value={- "api_key": "test-key",- "base_url": "https://example.invalid/v1",- "provider": "openrouter",- "api_mode": "chat_completions",- }), \- patch.object(sched, "_deliver_result", side_effect=fake_deliver), \- patch("run_agent.AIAgent") as mock_agent_cls:- mock_agent = MagicMock()- mock_agent.run_conversation.side_effect = RuntimeError("boom unrelated")- mock_agent_cls.return_value = mock_agent- sched.run_one_job(fresh)-- assert len(deliveries) == 1, "non-drift failure must still deliver"- assert "boom unrelated" in deliveries[0]diff --git a/tests/cron/test_cron_failure_deliver.py b/tests/cron/test_cron_failure_deliver.pyindex e84d39be083..3bbb9226c9c 100644--- a/tests/cron/test_cron_failure_deliver.py+++ b/tests/cron/test_cron_failure_deliver.py@@ -1,7 +1,7 @@"""Per-job ``failure_deliver`` routing (NS-788).-A job's FAILURE notices (run failed, escaped scheduler exception, drift-skip /-blocked-config alerts) resolve their delivery targets from ``failure_deliver``+A job's FAILURE notices (run failed, escaped scheduler exception, blocked-config+alerts) resolve their delivery targets from ``failure_deliver``when the job sets it, falling back to ``deliver`` when unset — so existingjobs behave byte-identically. ``failure_deliver: local`` is structural silencefor failures: nothing is sent, but state (last_status, run history, outputdiff --git a/tests/cron/test_cron_incidents.py b/tests/cron/test_cron_incidents.pyindex f72d8a82017..ced68068033 100644--- a/tests/cron/test_cron_incidents.py+++ b/tests/cron/test_cron_incidents.py@@ -42,7 +42,7 @@ def _job(**overrides):def _tick_failing(job, tmp_path, deliveries, error="boom unrelated"):"""Run one run_one_job tick whose agent raises ``error`` (the failure- path that composes the per-run failure ping). Mirrors the drift-alert-once+ path that composes the per-run failure ping). Mirrors the preflight alert-onceharness so the incident gating is exercised through the real scheduler."""fake_db = MagicMock()diff --git a/tests/cron/test_cron_provider_pin.py b/tests/cron/test_cron_provider_pin.pyindex 1e014fe85ff..cd9d3e59783 100644--- a/tests/cron/test_cron_provider_pin.py+++ b/tests/cron/test_cron_provider_pin.py@@ -1,33 +1,30 @@-"""Provider-drift fail-closed guard for cron jobs (#44585).+"""Unpinned cron jobs run on their creation snapshot (#44585 follow-up).-Background: an UNPINNED cron job follows the global default provider. If that-global state is changed (e.g. a temporary switch to a paid provider like-nous/claude-fable-5), the job would silently inherit it on its next tick and-spend real money — the $7.73 incident.+Background: an UNPINNED cron job used to follow the live global default provider/model. A+temporary switch to a paid provider made every unpinned job silently inherit it on its next+tick (the $7.73 incident). The first fix failed closed on any drift, which instead killed every+unpinned job whenever the operator changed models — silently, for days.-The fix has two halves:- - create_job() snapshots the provider resolution WOULD pick at creation into- job["provider_snapshot"] (only for unpinned, agent-backed jobs).- - run_job() fails closed when an unpinned job's CURRENTLY-resolved provider- differs from that snapshot: it skips the run, makes no paid call, and- delivers a loud actionable error.+Current contract:+ - create_job() snapshots the provider/model resolution WOULD pick at creation into+ job["provider_snapshot"] / job["model_snapshot"] (unpinned, agent-backed jobs only).+ - run_job() treats the snapshot as the effective pin: an unpinned axis runs on its snapshot+ even after the global default moved. Explicit per-job pins and the cron.model /+ cron.model_provider fleet defaults still win; a job with no snapshot follows the global+ default as before.These tests exercise the full run_job path (real imports, mocked AIAgent +-resolve_runtime_provider against a temp HERMES_HOME) and the create_job-snapshot capture. They are load-bearing: without the guard, cases (b) call the-agent and "succeed" instead of failing closed.+resolve_runtime_provider against a temp HERMES_HOME) and the create_job snapshot capture."""import sysfrom pathlib import Pathfrom unittest.mock import MagicMock, patch-import pytest-# Ensure project root is importable.sys.path.insert(0, str(Path(__file__).parent.parent.parent))-from cron.scheduler import _summarize_cron_failure_for_delivery, run_job+from cron.scheduler import run_jobdef _base_job(**overrides):@@ -44,134 +41,114 @@ def _base_job(**overrides):return job-def _run_with_current_provider(job, current_provider, tmp_path):- """Drive run_job with resolve_runtime_provider pinned to ``current_provider``.+def _run(job, tmp_path, *, current_provider="openrouter", current_model=None, cron_model=None,+ cron_model_provider=None):+ """Drive run_job against a temp config.yaml whose ``model.default`` / ``model.provider`` are+ the CURRENT global defaults. Returns ``(success, error, agent_kwargs, resolve_kwargs)`` where+ the last two are the kwargs AIAgent / resolve_runtime_provider were called with (None when+ never called)."""+ config_yaml = ""+ if current_model or current_provider:+ config_yaml += "model:\n"+ if current_model:+ config_yaml += f" default: {current_model}\n"+ if current_provider:+ config_yaml += f" provider: {current_provider}\n"+ cron_lines = []+ if cron_model is not None:+ cron_lines.append(f" model: {cron_model}")+ if cron_model_provider is not None:+ cron_lines.append(f" model_provider: {cron_model_provider}")+ if cron_lines:+ config_yaml += "cron:\n" + "\n".join(cron_lines) + "\n"+ (tmp_path / "config.yaml").write_text(config_yaml)++ resolve_kwargs = {}++ def _resolve(**kwargs):+ resolve_kwargs.update(kwargs)+ return {+ "api_key": "test-key",+ "base_url": "https://example.invalid/v1",+ "provider": kwargs.get("requested") or current_provider,+ "api_mode": "chat_completions",+ }- Returns (success, output, final_response, error, agent_constructed).- """fake_db = MagicMock()with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler._get_hermes_home", return_value=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={- "api_key": "test-key",- "base_url": "https://example.invalid/v1",- "provider": current_provider,- "api_mode": "chat_completions",- },- ), \+ patch("hermes_cli.runtime_provider.resolve_runtime_provider", side_effect=_resolve), \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)- agent_constructed = mock_agent_cls.called-- return success, output, final_response, error, agent_constructed+ success, _output, _final, error = run_job(job)+ agent_kwargs = mock_agent_cls.call_args.kwargs if mock_agent_cls.called else None+ return success, error, agent_kwargs, (resolve_kwargs or None)-class TestProviderDriftGuard:- def test_a_unpinned_snapshot_matches_runs_normally(self, tmp_path):- """(a) Unpinned job whose snapshot == current provider → runs normally."""- job = _base_job(provider_snapshot="openrouter")- success, output, final_response, error, agent_constructed = \- _run_with_current_provider(job, "openrouter", tmp_path)+class TestSnapshotIsTheEffectivePin:+ def test_unpinned_job_runs_on_snapshot_after_global_default_moved(self, tmp_path):+ """Global default moved old-provider/old-model -> new-provider/new-model; the unpinned job+ still runs, on what it was created under. Neither a skip nor a silent inherit."""+ job = _base_job(provider_snapshot="old-provider", model_snapshot="old-model")+ success, error, agent_kwargs, resolve_kwargs = _run(+ job, tmp_path, current_provider="new-provider", current_model="new-model")- assert success is True- assert error is None- assert final_response == "ok"- assert agent_constructed is True+ assert success is True, error+ assert agent_kwargs["model"] == "old-model"+ assert resolve_kwargs["requested"] == "old-provider"+ assert resolve_kwargs["target_model"] == "old-model"- def test_b_unpinned_snapshot_differs_fails_closed(self, tmp_path):- """(b) Unpinned job whose snapshot != current provider → fail closed.-- The paid call must NOT be made (AIAgent never constructed), the raw- error must name both providers, and the delivered summary must tell the- user to pin.- """- job = _base_job(provider_snapshot="openrouter")- success, output, final_response, error, agent_constructed = \- _run_with_current_provider(job, "nous", tmp_path)-- # Fail closed: no agent constructed, no inference call.- assert agent_constructed is False- assert success is False- assert error is not None-- # Loud + actionable: names both providers, mentions spend + pinning.- blob = f"{error}\n{output}".lower()- assert "openrouter" in blob- assert "nous" in blob- assert "spend" in blob- assert "hermes cron edit pin-test --provider <provider> --model <model>" in blob- assert "cronjob action=update" not in blob- assert "44585" in blob-- delivered = _summarize_cron_failure_for_delivery(job, error).lower()- assert "host running hermes" in delivered- assert "hermes cron edit pin-test --provider <provider> --model <model>" in delivered- assert "cronjob action=update" not in delivered-- def test_c_no_snapshot_runs_backcompat(self, tmp_path):- """(c) Pre-existing job with NO provider_snapshot → runs (back-compat).-- Even though the current provider differs from anything, a job without a- snapshot must behave exactly as before this fix: the guard never engages.- """- # A job dict that predates the field entirely (key absent, not None).+ def test_explicit_job_pin_beats_snapshot(self, tmp_path):+ job = _base_job(+ provider="pinned-provider", model="pinned-model",+ provider_snapshot="old-provider", model_snapshot="old-model")+ success, error, agent_kwargs, resolve_kwargs = _run(+ job, tmp_path, current_provider="new-provider", current_model="new-model",+ cron_model="fleet-model")++ assert success is True, error+ assert agent_kwargs["model"] == "pinned-model"+ assert resolve_kwargs["requested"] == "pinned-provider"++ def test_cron_fleet_default_beats_snapshot(self, tmp_path):+ """cron.model / cron.model_provider deliberately route the whole unpinned fleet."""+ job = _base_job(provider_snapshot="old-provider", model_snapshot="old-model")+ success, error, agent_kwargs, resolve_kwargs = _run(+ job, tmp_path, current_provider="new-provider", current_model="new-model",+ cron_model="fleet-model", cron_model_provider="fleet-provider")++ assert success is True, error+ assert agent_kwargs["model"] == "fleet-model"+ assert resolve_kwargs["requested"] == "fleet-provider"++ def test_job_without_snapshot_follows_global_default(self, tmp_path):+ """Legacy record (keys absent) keeps tracking the live global default."""job = _base_job()job.pop("provider_snapshot", None)- success, output, final_response, error, agent_constructed = \- _run_with_current_provider(job, "nous", tmp_path)+ success, error, agent_kwargs, resolve_kwargs = _run(+ job, tmp_path, current_provider="new-provider", current_model="new-model")- assert success is True- assert error is None- assert agent_constructed is True-- def test_c2_snapshot_none_runs_backcompat(self, tmp_path):- """(c') Job with provider_snapshot explicitly None → runs (back-compat)."""- job = _base_job(provider_snapshot=None)- success, output, final_response, error, agent_constructed = \- _run_with_current_provider(job, "nous", tmp_path)-- assert success is True- assert error is None- assert agent_constructed is True+ assert success is True, error+ assert agent_kwargs["model"] == "new-model"+ assert resolve_kwargs["requested"] is Nonedef test_missing_model_guides_to_user_owned_cli(self, tmp_path, monkeypatch):"""A missing-model failure cannot advertise agent-owned pinning."""monkeypatch.delenv("HERMES_MODEL", raising=False)- success, _output, _final_response, error, agent_constructed = \- _run_with_current_provider(_base_job(), "openrouter", tmp_path)+ success, error, agent_kwargs, _ = _run(+ _base_job(), tmp_path, current_provider="openrouter", current_model=None)assert success is False- assert agent_constructed is False- assert error is not None+ assert agent_kwargs is Noneassert "hermes cron edit pin-test --model <name>" in errorassert "cronjob action=update" not in error- def test_d_explicitly_pinned_runs_regardless_of_drift(self, tmp_path):- """(d) Explicitly-pinned job (job["provider"] set) → runs regardless.-- A pinned job does not follow global state, so even a snapshot/current- mismatch must not skip it. (Snapshot would normally be None for pinned- jobs, but we set a mismatching one to prove the pin wins.)- """- job = _base_job(provider="openrouter", provider_snapshot="anthropic")- # Current resolution differs from the (stale) snapshot, but the job is- # pinned, so the guard must not engage.- success, output, final_response, error, agent_constructed = \- _run_with_current_provider(job, "nous", tmp_path)-- assert success is True- assert error is None- assert agent_constructed is True-class TestCreateJobSnapshot:"""create_job captures provider_snapshot for unpinned agent jobs only."""@@ -230,209 +207,16 @@ class TestCreateJobSnapshot:assert job["provider_snapshot"] is None-def _run_with_current_provider_and_model(- job,- current_provider,- current_model,- tmp_path,- *,- model_drift_guard=None,- cron_model=None,- cron_model_provider=None,-):- """Drive run_job with resolved provider pinned and config.yaml model.default- set to ``current_model`` (the unpinned-model fire-time source)."""- config_yaml = f"model:\n default: {current_model}\n"- cron_lines = []- if model_drift_guard is not None:- cron_lines.append(f" model_drift_guard: {str(model_drift_guard).lower()}")- if cron_model is not None:- cron_lines.append(f" model: {cron_model}")- if cron_model_provider is not None:- cron_lines.append(f" model_provider: {cron_model_provider}")- if cron_lines:- config_yaml += "cron:\n" + "\n".join(cron_lines) + "\n"- (tmp_path / "config.yaml").write_text(config_yaml)- fake_db = MagicMock()- with patch("cron.scheduler._hermes_home", tmp_path), \- patch("cron.scheduler._get_hermes_home", return_value=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={- "api_key": "test-key",- "base_url": "https://example.invalid/v1",- "provider": current_provider,- "api_mode": "chat_completions",- },- ), \- patch("run_agent.AIAgent") as mock_agent_cls:- mock_agent = MagicMock()- mock_agent.run_conversation.return_value = {"final_response": "ok"}- mock_agent_cls.return_value = mock_agent- success, output, final_response, error = run_job(job)- agent_constructed = mock_agent_cls.called- return success, output, final_response, error, agent_constructed---class TestModelDriftGuard:- """#44585 C1: model drift on the SAME provider must also fail closed —- the incident named a model (claude-fable-5), and an unpinned job reads- config.yaml model.default fresh every tick independently of provider."""-- def test_model_drift_same_provider_fails_closed(self, tmp_path):- # Provider unchanged (openrouter==openrouter), but the global default- # MODEL swapped to a premium model since creation → must fail closed.- job = _base_job(- provider_snapshot="openrouter",- model_snapshot="llama-3.3-70b-instruct:free",- )- success, output, final_response, error, agent_constructed = \- _run_with_current_provider_and_model(- job, "openrouter", "claude-fable-5", tmp_path- )- assert agent_constructed is False, "paid call must not be made on model drift"- assert success is False- blob = f"{error}\n{output}".lower()- assert "claude-fable-5" in blob- assert "llama-3.3-70b-instruct:free" in blob- assert "44585" in blob--- def test_finite_oneshot_model_drift_explains_that_recreation_is_required(self, tmp_path):- """A spent one-shot cannot be repaired in place after the guard fires."""- job = _base_job(- provider_snapshot="openrouter",- model_snapshot="old-model",- schedule={"kind": "once", "run_at": "2030-01-01T00:00:00Z"},- repeat={"times": 1, "completed": 1},- )- success, _output, _final_response, error, agent_constructed = \- _run_with_current_provider_and_model(- job, "openrouter", "new-model", tmp_path- )-- assert success is False- assert agent_constructed is False- assert error is not None- assert "create a new one-shot job" in error.lower()- assert "cronjob action=update" not in error.lower()-- delivered = _summarize_cron_failure_for_delivery(job, error).lower()- assert "create a new one-shot job" in delivered- assert "cronjob action=update" not in delivered-- def test_no_model_snapshot_backcompat(self, tmp_path):- # Pre-existing job without model_snapshot → no model-drift skip.- job = _base_job(provider_snapshot="openrouter") # no model_snapshot key set to a value- success, output, final_response, error, agent_constructed = \- _run_with_current_provider_and_model(- job, "openrouter", "claude-fable-5", tmp_path- )- assert agent_constructed is True- assert success is True-- def test_explicit_opt_out_allows_provider_and_model_drift(self, tmp_path):- """The opt-out lets large unpinned fleets track changing defaults."""- job = _base_job(- provider_snapshot="old-provider",- model_snapshot="old-model",- )- success, output, final_response, error, agent_constructed = \- _run_with_current_provider_and_model(- job,- "new-provider",- "new-model",- tmp_path,- model_drift_guard=False,- )-- assert agent_constructed is True- assert success is True- assert final_response == "ok"- assert error is None---class TestCronFleetDefaultModel:- """cron.model / cron.model_provider — an explicit cron-fleet default is- NOT drift: unpinned jobs run on it and the #44585 guard stays quiet for- the covered axis."""-- def test_cron_model_skips_model_drift_guard_and_is_used(self, tmp_path):- # Snapshot says old free model, global default swapped to a premium- # model — but cron.model is set, so the job deliberately follows it.- job = _base_job(- provider_snapshot="openrouter",- model_snapshot="llama-3.3-70b-instruct:free",- )- success, output, final_response, error, agent_constructed = \- _run_with_current_provider_and_model(- job,- "openrouter",- "claude-fable-5",- tmp_path,- cron_model="qwen-2.5-7b:free",- )- assert agent_constructed is True- assert success is True- assert final_response == "ok"--- def test_per_job_pin_still_beats_cron_model(self, tmp_path):- job = _base_job(- provider_snapshot="openrouter",- model_snapshot="old-model",- model="my-pinned-model",- )- success, output, final_response, error, agent_constructed = \- _run_with_current_provider_and_model(- job,- "openrouter",- "claude-fable-5",- tmp_path,- cron_model="qwen-2.5-7b:free",- )- assert agent_constructed is True- assert success is True--class TestRuntimeResolutionTargetModel:- """run_job must resolve the primary provider against the model the job- will actually run (per-job pin > env > config default), so providers with- model-specific api_mode routing (e.g. OpenCode Zen/Go) pick the mode for- the pinned model instead of the stale persisted default."""+ """run_job must resolve the primary provider against the model the job will actually run+ (per-job pin > cron.model > snapshot > config default), so providers with model-specific+ api_mode routing pick the mode for that model instead of the stale persisted default."""def test_primary_resolution_passes_effective_model(self, tmp_path):job = _base_job(model="my-pinned-model", provider="openrouter")- captured = {}-- def _capture(**kwargs):- captured.update(kwargs)- return {- "api_key": "test-key",- "base_url": "https://example.invalid/v1",- "provider": "openrouter",- "api_mode": "chat_completions",- }-- 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",- side_effect=_capture,- ), \- 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- run_job(job)-- assert captured.get("target_model") == "my-pinned-model"- assert captured.get("requested") == "openrouter"+ success, error, _agent_kwargs, resolve_kwargs = _run(+ job, tmp_path, current_provider="openrouter", current_model="other-model")++ assert success is True, error+ assert resolve_kwargs["target_model"] == "my-pinned-model"+ assert resolve_kwargs["requested"] == "openrouter"diff --git a/tests/cron/test_cron_reasoning_effort.py b/tests/cron/test_cron_reasoning_effort.pyindex 4f45549a050..d4eb672b2b2 100644--- a/tests/cron/test_cron_reasoning_effort.py+++ b/tests/cron/test_cron_reasoning_effort.py@@ -97,8 +97,8 @@ class TestJobStoreReasoningEffort:assert load_jobs()[0]["reasoning_effort"] == "high"def test_effort_change_does_not_trigger_snapshot_recompute(self, tmp_cron_dir):- """Effort is NOT a drift-guard axis (#44585 guard unchanged): updating- it alone must not touch provider_snapshot/model_snapshot."""+ """Effort is NOT an inference-snapshot axis: updating it alone must not+ touch provider_snapshot/model_snapshot."""job = _create()before = (job.get("provider_snapshot"), job.get("model_snapshot"))updated = update_job(job["id"], {"reasoning_effort": "low"})diff --git a/tests/cron/test_fire_forward_failure_stamp.py b/tests/cron/test_fire_forward_failure_stamp.pyindex cb205f8fb69..7743959b81f 100644--- a/tests/cron/test_fire_forward_failure_stamp.py+++ b/tests/cron/test_fire_forward_failure_stamp.py@@ -69,7 +69,7 @@ class TestNoteFireForwardFailure:def test_failed_run_keeps_stamp(self, tmp_cron_dir):"""An agent-level failure is not proof the fire hand-off healed —- only success clears (mirrors preflight_alerted / drift_alerted)."""+ only success clears (mirrors preflight_alerted)."""job = create_job(prompt="Daily invoice triage", schedule="every 1h")note_fire_forward_failure(job["id"], "gateway unreachable")diff --git a/tests/cron/test_preflight_config.py b/tests/cron/test_preflight_config.pyindex bb6d195d8b8..273d5b9a315 100644--- a/tests/cron/test_preflight_config.py+++ b/tests/cron/test_preflight_config.py@@ -13,7 +13,7 @@ delivery platform — must be blocked BEFORE any agent machinery is constructed:proceeds to resolution and fails loudly every tick).Related precedent: #27948 (fail-loud for hidden tools — same fail-before-run-spirit, different check) and #44585 (drift guard: skip-run-no-spend shape).+spirit, different check)."""import jsondiff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.pyindex 6abd13b40ea..03961ec17b6 100644--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@ -1250,9 +1250,8 @@ class TestRunJobConfigEnvVarExpansion:def resolve_runtime(**kwargs):requested.append(kwargs.get("requested"))- if kwargs.get("requested") in (None, "openai-codex"):- # Cron must retain the configured primary provider for drift- # comparison even when older/custom AuthError sites omit it.+ if kwargs.get("requested") == "openai-codex":+ # The unpinned job's provider_snapshot is its effective pin.raise AuthError("No Codex credentials stored")assert kwargs["requested"] == "openrouter"assert kwargs["target_model"] == "z-ai/glm-5.2"@@ -1274,7 +1273,7 @@ class TestRunJobConfigEnvVarExpansion:assert success is Trueassert error is None- assert requested == [None, "openrouter"]+ assert requested == ["openai-codex", "openrouter"]kwargs = mock_agent_cls.call_args.kwargsassert kwargs["provider"] == "openrouter"assert kwargs["model"] == "z-ai/glm-5.2"diff --git a/tests/hermes_cli/test_cron_model_impact.py b/tests/hermes_cli/test_cron_model_impact.pyindex 933c8d2dce3..ef097414f7f 100644--- a/tests/hermes_cli/test_cron_model_impact.py+++ b/tests/hermes_cli/test_cron_model_impact.py@@ -33,7 +33,7 @@ def _impact(jobs: object, **config: Any) -> dict[str, Any]:)-def test_drift_axes_match_unpinned_guard_semantics() -> None:+def test_drift_axes_match_unpinned_snapshot_semantics() -> None:assert cron_model_drift_axes(_job(), current_provider=" NOUS ", current_model="NEW/MODEL", config={}) == ["provider", "model"]@@ -51,7 +51,7 @@ def test_drift_axes_match_unpinned_guard_semantics() -> None:) == []-def test_fleet_defaults_and_literal_false_guard_suppress_only_intended_axes() -> None:+def test_fleet_defaults_cover_only_their_own_axis() -> None:assert cron_model_drift_axes(_job(),current_provider="nous",@@ -64,18 +64,6 @@ def test_fleet_defaults_and_literal_false_guard_suppress_only_intended_axes() ->current_model="new/model",config={"cron": {"model_provider": "openrouter"}},) == ["model"]- assert cron_model_drift_axes(- _job(),- current_provider="nous",- current_model="new/model",- config={"cron": {"model_drift_guard": False}},- ) == []- assert cron_model_drift_axes(- _job(),- current_provider="nous",- current_model="new/model",- config={"cron": {"model_drift_guard": "false"}},- ) == ["provider", "model"]def test_summary_filters_disabled_no_agent_and_mixed_pins() -> None:@@ -93,7 +81,6 @@ def test_summary_filters_disabled_no_agent_and_mixed_pins() -> None:assert impact == {"available": True,- "guard_enabled": True,"affected_count": 2,"truncated": False,"jobs": [@@ -127,7 +114,6 @@ def test_summary_handles_legacy_and_malformed_records_without_hiding_valid_siblidef test_non_list_job_collection_is_unavailable(jobs: object) -> None:assert _impact(jobs) == {"available": False,- "guard_enabled": True,"affected_count": 0,"truncated": False,"jobs": [],@@ -162,16 +148,6 @@ def test_fallback_name_respects_the_desktop_code_point_limit() -> None:assert impact["jobs"][0]["name"] == (f"Job {job_id}")[:120]-def test_guard_disabled_summary_is_available_but_empty() -> None:- assert _impact([_job()], cron={"model_drift_guard": False}) == {- "available": True,- "guard_enabled": False,- "affected_count": 0,- "truncated": False,- "jobs": [],- }--def test_effective_defaults_match_scheduler_config_over_env_precedence() -> None:assert resolve_cron_model_drift_defaults({"model": {"provider": "managed", "default": "managed/model"}},diff --git a/tests/hermes_cli/test_set_config_value.py b/tests/hermes_cli/test_set_config_value.pyindex d83a2af3ca9..ac7211cbc07 100644--- a/tests/hermes_cli/test_set_config_value.py+++ b/tests/hermes_cli/test_set_config_value.py@@ -9,7 +9,6 @@ import pytestfrom hermes_cli.config import (config_command,- cron_model_drift_guard_enabled,set_config_value,)@@ -309,7 +308,7 @@ class TestListNavigation:# ----------------------------------------------------------------------------# Cron drift guard warning — regression tests for #59031+# Unpinned-cron notice on a global model change (#59031, #44585)# ---------------------------------------------------------------------------def _write_cron_jobs(tmp_path, jobs):@@ -321,10 +320,10 @@ def _write_cron_jobs(tmp_path, jobs):)-class TestCronModelDriftConfigWarning:- """Warn operators before unpinned snapshot-bearing cron jobs fail closed."""+class TestCronModelChangeNotice:+ """A global model change tells the operator which unpinned jobs stay on their snapshot."""- def test_warning_names_the_user_owned_cli_pin_path(+ def test_notice_says_jobs_keep_running_and_names_the_user_owned_pin_path(self,_isolated_hermes_home,capsys,@@ -343,56 +342,11 @@ class TestCronModelDriftConfigWarning:set_config_value("model.default", "new-model")- warning = capsys.readouterr().out- assert "hermes cron edit <job_id> --provider <provider> --model <model>" in warning- assert "cronjob action=update" not in warning------ def test_explicit_opt_out_suppresses_warning(- self,- _isolated_hermes_home,- capsys,- ):- _write_cron_jobs(- _isolated_hermes_home,- [- {- "id": "model-drift-job",- "enabled": True,- "model": None,- "model_snapshot": "old-model",- }- ],- )-- set_config_value("cron.model_drift_guard", "false")- capsys.readouterr()- set_config_value("model.default", "new-model")-- import yaml- reloaded = yaml.safe_load(_read_config(_isolated_hermes_home))- captured = capsys.readouterr()- assert reloaded["cron"]["model_drift_guard"] is False- assert "Set model.default = new-model" in captured.out- assert "fail closed" not in captured.out--- @pytest.mark.parametrize(- ("configured_value", "expected"),- [- (False, False),- (True, True),- ("false", True),- (0, True),- (None, True),- ],- )- def test_only_literal_false_disables_guard(self, configured_value, expected):- config = {"cron": {"model_drift_guard": configured_value}}- assert cron_model_drift_guard_enabled(config) is expected+ notice = capsys.readouterr().out+ assert "keeps running" in notice+ assert "fail closed" not in notice+ assert "hermes cron edit <job_id> --provider <provider> --model <model>" in notice+ assert "cronjob action=update" not in notice# ---------------------------------------------------------------------------diff --git a/tests/hermes_cli/test_web_server_profile_unification.py b/tests/hermes_cli/test_web_server_profile_unification.pyindex 86b576fe039..ce6dd29ec31 100644--- a/tests/hermes_cli/test_web_server_profile_unification.py+++ b/tests/hermes_cli/test_web_server_profile_unification.py@@ -281,7 +281,6 @@ class TestProfileScopedModel:assert resp.status_code == 200assert resp.json()["cron_model_impact"] == {"available": True,- "guard_enabled": True,"affected_count": 1,"truncated": False,"jobs": [