The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(cron): add resnap action to adopt the current global inference default
Søren L. Hansen0037a4b17a1c
diff --git a/cron/jobs.py b/cron/jobs.pyindex 31d13ed15f8..3892b35c75b 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -2009,6 +2009,78 @@ def update_job(job_id: str, updates: Dict[str, Any]) -> Optional[Dict[str, Any]]return _with_job(job_id, apply)+def resnapshot_job(job_id: str) -> Optional[Dict[str, Any]]:+ """Refresh provider/model snapshots for a job's UNPINNED axes to the+ current global resolution.++ This is the "adopt the current global default" companion to pinning+ (#44585). Where pinning a job (``provider=... model=...``) makes it stop+ tracking the global default forever, ``resnapshot_job`` re-captures the+ current resolution so an unpinned job follows the user's deliberately+ changed default — while remaining unpinned and tracking future changes.++ Semantics:+ - Pinned axes (job has an explicit provider/model) keep their snapshot+ None and are left untouched.+ - no_agent script jobs carry no snapshot and are left untouched.+ - If the current resolution fails, the previous snapshot is left in+ place (fail-open, matching create_job semantics).++ Makes no inference call — it only recomputes the snapshot string from+ config. Returns the normalized updated job, or None if not found.+ """+ job = resolve_job_ref(job_id)+ if not job:+ return None+ provider_snapshot, model_snapshot = _compute_provider_model_snapshots(+ provider=job.get("provider"),+ model=job.get("model"),+ base_url=job.get("base_url"),+ no_agent=job.get("no_agent"),+ )+ jobs = load_jobs()+ for i, stored in enumerate(jobs):+ if stored["id"] != job["id"]:+ continue+ jobs[i]["provider_snapshot"] = provider_snapshot+ jobs[i]["model_snapshot"] = model_snapshot+ save_jobs(jobs)+ return _normalize_job_record(jobs[i])+ return None+++def resnapshot_all_unpinned() -> List[Dict[str, Any]]:+ """Refresh provider/model snapshots for every job that has any unpinned+ axis, adopting the current global resolution for each.++ Skips no_agent jobs and jobs pinned on all inference axes (nothing+ unpinned to refresh). Equivalent to calling ``resnapshot_job`` for each+ eligible job. Returns the list of updated jobs.+ """+ updated: List[Dict[str, Any]] = []+ jobs = load_jobs()+ changed = False+ for job in jobs:+ if bool(job.get("no_agent")):+ continue+ if job.get("provider") and job.get("model"):+ # Pinned on every axis — nothing unpinned to refresh.+ continue+ provider_snapshot, model_snapshot = _compute_provider_model_snapshots(+ provider=job.get("provider"),+ model=job.get("model"),+ base_url=job.get("base_url"),+ no_agent=job.get("no_agent"),+ )+ job["provider_snapshot"] = provider_snapshot+ job["model_snapshot"] = model_snapshot+ changed = True+ updated.append(_normalize_job_record(job))+ if changed:+ save_jobs(jobs)+ return updated++def pause_job(job_id: str, reason: Optional[str] = None) -> Optional[Dict[str, Any]]:"""Pause a job without deleting it. Accepts a job ID or name."""job = resolve_job_ref(job_id)diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 6206ad81017..043d86a7fe1 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -1346,8 +1346,9 @@ def _snapshot_pin(job: dict, axis: str, current: str, job_id: str) -> str:if snapshot and current and snapshot.lower() != current.lower():logger.info("Job '%s': running on creation-snapshot %s %r (global default is now %r); "- "`hermes cron edit %s --%s <value>` or cron.%s in config.yaml moves it.",- job_id, axis, snapshot, current, job_id, axis,+ "`hermes cron resnap %s` adopts the new default (stays unpinned), "+ "`hermes cron edit %s --%s <value>` or cron.%s in config.yaml pins it.",+ job_id, axis, snapshot, current, job_id, job_id, axis,"model" if axis == "model" else "model_provider")return snapshotdiff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex 837fd9b63d1..6991fef1d2d 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -771,7 +771,8 @@ _CRON_SUBCOMMANDS = {"pause": lambda a: _job_action("pause", a.job_id, "Paused"),"resume": lambda a: cron_resume(a),"run": lambda a: _job_action("run", a.job_id, "Triggered"),- "remove": lambda a: _job_action("remove", a.job_id, "Removed")}+ "remove": lambda a: _job_action("remove", a.job_id, "Removed"),+ "resnap": lambda a: _cron_resnap(a)}_CRON_SUBCOMMANDS["history"] = _CRON_SUBCOMMANDS["runs"]_CRON_SUBCOMMANDS["add"] = _CRON_SUBCOMMANDS["create"]_CRON_SUBCOMMANDS["rm"] = _CRON_SUBCOMMANDS["delete"] = _CRON_SUBCOMMANDS["remove"]@@ -784,5 +785,35 @@ def cron_command(args):if handler is not None:return handler(args)print(f"Unknown cron command: {subcmd}\n"- "Usage: hermes cron [list|create|edit|pause|resume|run|remove|status|runs|doctor|tick]")+ "Usage: hermes cron [list|create|edit|pause|resume|run|remove|resnap|status|runs|doctor|tick]")sys.exit(1)+++def _cron_resnap(args) -> int:+ """Handle `hermes cron resnap [job_id] [--all]`."""+ if bool(getattr(args, "all", False)):+ result = _cron_api(action="resnap", all=True)+ if not result.get("success"):+ print(color(f"Failed to resnap: {result.get('error', 'unknown error')}", Colors.RED))+ return 1+ updated = result.get("updated_jobs", [])+ print(color(f"Resnapped {len(updated)} unpinned job(s) to the current global resolution.", Colors.GREEN))+ for job in updated:+ print(f" • {job.get('name', job.get('job_id'))} ({job.get('job_id')})")+ if not updated:+ print(" (no unpinned agent jobs found — nothing to refresh)")+ return 0++ job_id = getattr(args, "job_id", None)+ if not job_id:+ print(color("resnap requires either a <job_id> or --all.", Colors.RED))+ print("Usage: hermes cron resnap <job_id> | hermes cron resnap --all")+ return 1+ result = _cron_api(action="resnap", job_id=job_id)+ if not result.get("success"):+ print(color(f"Failed to resnap job: {result.get('error', 'unknown error')}", Colors.RED))+ return 1+ job = result.get("job", {})+ print(color(f"Resnapped job: {job.get('name', job_id)} ({job.get('job_id', job_id)})", Colors.GREEN))+ print(" Adopted the current global inference resolution; the job remains unpinned and will track future global changes.")+ return 0diff --git a/hermes_cli/subcommands/cron.py b/hermes_cli/subcommands/cron.pyindex 806c2cc27bc..2603bf57a69 100644--- a/hermes_cli/subcommands/cron.py+++ b/hermes_cli/subcommands/cron.py@@ -154,6 +154,24 @@ def build_cron_parser(subparsers, *, cmd_cron: Callable) -> None:"remove", aliases=["rm", "delete"], help="Remove a scheduled job")cron_remove.add_argument("job_id", help="Job ID to remove")+ cron_resnap = cron_subparsers.add_parser(+ "resnap",+ help=(+ "Adopt the current global inference resolution for unpinned jobs "+ "without pinning them (they keep tracking future global changes). "+ "Use after deliberately changing the default model."+ ),+ )+ cron_resnap.add_argument(+ "job_id", nargs="?", help="Job ID to resnap (omit with --all)"+ )+ cron_resnap.add_argument(+ "--all",+ action="store_true",+ help="Resnap every unpinned agent job to the current global resolution",+ )++ # cron statuscron_subparsers.add_parser("status", help="Check if cron scheduler is running")cron_runs = cron_subparsers.add_parser(diff --git a/tests/cron/test_cron_provider_pin.py b/tests/cron/test_cron_provider_pin.pyindex cd9d3e59783..cd3d90a6c68 100644--- a/tests/cron/test_cron_provider_pin.py+++ b/tests/cron/test_cron_provider_pin.py@@ -220,3 +220,134 @@ class TestRuntimeResolutionTargetModel:assert success is True, errorassert resolve_kwargs["target_model"] == "my-pinned-model"assert resolve_kwargs["requested"] == "openrouter"+++class TestResnapshot:+ """resnapshot_job / resnapshot_all_unpinned — 'adopt the current global+ default without pinning' (#44585 companion). These refresh an unpinned+ job's snapshot(s) to the CURRENT global resolution while leaving the job+ unpinned, so it keeps tracking future global changes."""++ @staticmethod+ def _install_store(monkeypatch, initial_jobs):+ """Install an in-memory cron job store backed by a real list so+ resnapshot functions can load/save against it."""+ import contextlib+ import cron.jobs as jobs++ store = [dict(j) for j in initial_jobs] # deep-ish copy per job++ @contextlib.contextmanager+ def _lock():+ yield++ monkeypatch.setattr(jobs, "_jobs_lock", _lock, raising=True)+ monkeypatch.setattr(jobs, "load_jobs", lambda: [dict(j) for j in store], raising=True)++ def _save(job_list):+ store[:] = [dict(j) for j in job_list]++ monkeypatch.setattr(jobs, "save_jobs", _save, raising=True)+ return jobs, store++ def _make_job(self, job_id, **overrides):+ job = {+ "id": job_id,+ "name": f"job {job_id}",+ "prompt": "do a thing",+ "model": None,+ "provider": None,+ "model_snapshot": "old-model",+ "provider_snapshot": "old-provider",+ "base_url": None,+ "no_agent": False,+ }+ job.update(overrides)+ return job++ def test_resnapshot_unpinned_refreshes_to_current(self, monkeypatch, tmp_path):+ jobs_mod, store = self._install_store(+ monkeypatch, [self._make_job("j1", model_snapshot="old-model")]+ )+ (tmp_path / "config.yaml").write_text("model:\n default: new-model\n")+ monkeypatch.setattr("cron.jobs.get_hermes_home", lambda: tmp_path, raising=True)+ with patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={"provider": "openrouter"},+ ):+ updated = jobs_mod.resnapshot_job("j1")++ assert updated is not None+ assert updated["model"] is None, "job must stay unpinned"+ assert updated["model_snapshot"] == "new-model"+ assert updated["provider_snapshot"] == "openrouter"+ # Persisted too.+ assert store[0]["model_snapshot"] == "new-model"+ assert store[0]["provider_snapshot"] == "openrouter"++ def test_resnapshot_pinned_job_keeps_none_snapshot(self, monkeypatch, tmp_path):+ # A fully-pinned job already carries None snapshots; resnapping must not+ # clobber them into a global default.+ jobs_mod, store = self._install_store(+ monkeypatch,+ [+ self._make_job(+ "j1",+ model="my-pinned-model",+ provider="openrouter",+ model_snapshot=None,+ provider_snapshot=None,+ )+ ],+ )+ (tmp_path / "config.yaml").write_text("model:\n default: new-model\n")+ monkeypatch.setattr("cron.jobs.get_hermes_home", lambda: tmp_path, raising=True)+ with patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={"provider": "openrouter"},+ ):+ updated = jobs_mod.resnapshot_job("j1")++ # Pinned axes stay pinned: model unchanged, snapshots still None.+ assert updated["model"] == "my-pinned-model"+ assert updated["model_snapshot"] is None+ assert updated["provider_snapshot"] is None++ def test_resnapshot_missing_job_returns_none(self, monkeypatch, tmp_path):+ jobs_mod, _store = self._install_store(monkeypatch, [])+ assert jobs_mod.resnapshot_job("nope") is None++ def test_resnapshot_all_skips_no_agent_and_fully_pinned(self, monkeypatch, tmp_path):+ jobs_mod, store = self._install_store(+ monkeypatch,+ [+ # unpinned, model-only → should be refreshed (provider axis too)+ self._make_job("j1", model_snapshot="old", provider_snapshot="old"),+ # no_agent → skipped entirely+ self._make_job("j2", no_agent=True, model_snapshot="old", provider_snapshot="old"),+ # fully pinned → skipped (nothing unpinned)+ self._make_job(+ "j3",+ model="pm", provider="pp",+ model_snapshot=None, provider_snapshot=None,+ ),+ ],+ )+ (tmp_path / "config.yaml").write_text("model:\n default: new-model\n")+ monkeypatch.setattr("cron.jobs.get_hermes_home", lambda: tmp_path, raising=True)+ with patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={"provider": "openrouter"},+ ):+ updated = jobs_mod.resnapshot_all_unpinned()++ ids = [j["id"] for j in updated]+ assert ids == ["j1"], "only the unpinned agent job is refreshed"+ by_id = {j["id"]: j for j in store}+ assert by_id["j1"]["model_snapshot"] == "new-model"+ assert by_id["j1"]["provider_snapshot"] == "openrouter"+ # no_agent job keeps its (irrelevant) old snapshot untouched.+ assert by_id["j2"]["model_snapshot"] == "old"+ # pinned job keeps None.+ assert by_id["j3"]["model_snapshot"] is None+diff --git a/tests/tools/test_cronjob_tools.py b/tests/tools/test_cronjob_tools.pyindex 5e570146574..32dc66a37bd 100644--- a/tests/tools/test_cronjob_tools.py+++ b/tests/tools/test_cronjob_tools.py@@ -645,6 +645,45 @@ class TestLocalDeliveryNotice:assert created["deliver"] == "origin"assert "local-only cron job" not in created["message"]+ def test_resnap_requires_scope(self):+ # resnap with neither job_id nor all=true must refuse to guess scope.+ result = json.loads(cronjob(action="resnap"))+ assert result["success"] is False+ assert "resnap requires either" in result["error"]++ def test_resnap_single_job(self, monkeypatch, tmp_path):+ from unittest.mock import patch as _patch+ # Deterministic global resolution for the snapshot recompute.+ (tmp_path / "config.yaml").write_text("model:\n default: new-model\n")+ monkeypatch.setattr("cron.jobs.get_hermes_home", lambda: tmp_path, raising=True)+ with _patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={"provider": "openrouter"},+ ):+ created = json.loads(+ cronjob(action="create", prompt="Check", schedule="every 1h")+ )+ job_id = created["job_id"]+ result = json.loads(cronjob(action="resnap", job_id=job_id))+ assert result["success"] is True+ assert "remains unpinned" in result["message"]+ assert result["job"]["job_id"] == job_id++ def test_resnap_all(self, monkeypatch, tmp_path):+ from unittest.mock import patch as _patch+ (tmp_path / "config.yaml").write_text("model:\n default: new-model\n")+ monkeypatch.setattr("cron.jobs.get_hermes_home", lambda: tmp_path, raising=True)+ with _patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={"provider": "openrouter"},+ ):+ cronjob(action="create", prompt="One", schedule="every 1h")+ cronjob(action="create", prompt="Two", schedule="every 2h")+ result = json.loads(cronjob(action="resnap", all=True))+ assert result["success"] is True+ assert "Refreshed inference snapshots on" in result["message"]+ assert len(result["updated_jobs"]) >= 1+class TestValidateCronBaseUrl:"""The cron base_url guard must not let a NAMED custom provider's storeddiff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex df226847ef7..78c7ac5cc91 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -41,6 +41,8 @@ from cron.jobs import (pause_job,remove_job,resolve_job_ref,+ resnapshot_all_unpinned,+ resnapshot_job,resume_job,update_job)from tools.cronjob_prompt_scan import _scan_cron_prompt@@ -823,8 +825,50 @@ def _action_update(job: Dict[str, Any], a: Dict[str, Any]) -> str:{"success": True, "job": _format_job(updated)}, updated, _normalize_deliver_param(a["deliver"])))+def _action_resnap(a: Dict[str, Any]) -> str:+ """Adopt the current global inference resolution without pinning (#44585).++ Bulk (``all=true``) refreshes every unpinned job; single-job resolves+ ``job_id`` and refreshes just that job. Refuses to guess scope.+ """+ if bool(a["all"]):+ updated = resnapshot_all_unpinned()+ _notify_provider_jobs_changed_safe()+ return _dumps({+ "success": True,+ "message": (+ f"Refreshed inference snapshots on {len(updated)} unpinned "+ "job(s) to the current global resolution. Jobs remain "+ "unpinned and will track future global changes."),+ "updated_jobs": [_format_job(j) for j in updated],+ })+ job_id = a["job_id"]+ if not job_id:+ return tool_error(+ "resnap requires either `job_id=<id>` (single job) or `all=true` "+ "(refresh every unpinned job). Refusing to guess scope.",+ success=False,+ )+ job, error = _resolve_job_or_error(job_id)+ if error is not None:+ return error+ assert job is not None # error is None ⇔ job resolved+ updated = resnapshot_job(job["id"])+ if not updated:+ return tool_error(f"Failed to resnap job '{job_id}'", success=False)+ _notify_provider_jobs_changed_safe()+ return _dumps({+ "success": True,+ "message": (+ f"Cron job '{updated['name']}' refreshed to the current "+ "global inference resolution. It remains unpinned and will "+ "track future global changes."),+ "job": _format_job(updated),+ })++# Actions that need no job_id, and job-bound actions (job resolved first).-_JOBLESS_ACTIONS = {"create": _action_create, "list": _action_list}+_JOBLESS_ACTIONS = {"create": _action_create, "list": _action_list, "resnap": _action_resnap}_JOB_ACTIONS = {"remove": _action_remove, "update": _action_update,"run": _action_run, "run_now": _action_run, "trigger": _action_run,@@ -879,6 +923,7 @@ def cronjob(monitor_url: Optional[str] = None,reasoning_effort: Optional[str] = None,failure_deliver: Optional[Union[str, List[str]]] = None,+ all: Optional[bool] = None,task_id: str = None,session_id: Optional[str] = None,paused: bool = False,@@ -925,6 +970,8 @@ CRONJOB_SCHEMA = {"name": "cronjob_manage","description": """Manage scheduled cron jobs: action='create' schedules a job from a prompt and/or skills; 'list' inspects jobs; 'update'/'pause'/'resume'/'remove' manage one by job_id (always list first — never guess job IDs); 'run' fires a job immediately in the BACKGROUND (returns a handle at once, outcome re-enters the conversation when done — do not wait or poll; optional 'prompt' adds transient context for that fire only).+'resnap' adopts the CURRENT global inference resolution for an unpinned job (job_id) or all unpinned jobs (all=true) WITHOUT pinning it, so it keeps tracking future global changes — use after deliberately changing the default model.+Jobs run in a fresh session with no current-chat context, so prompts must be self-contained, and the agent's FINAL RESPONSE is what gets delivered — cron runs are autonomous and cannot ask questions. Prefer updating an existing job over creating near-duplicates.""","parameters": {"type": "object",@@ -933,11 +980,15 @@ Jobs run in a fresh session with no current-chat context, so prompts must be sel"paused_reason": {"type": "string", "description": "Create only: auditable reason; requires paused=true."},"action": {"type": "string",- "description": "One of: create, list, update, pause, resume, remove, run. When action=create, the 'schedule' and 'prompt' fields are REQUIRED."+ "description": "One of: create, list, update, pause, resume, remove, run, resnap. When action=create, the 'schedule' and 'prompt' fields are REQUIRED. When action=resnap, pass either job_id (single job) or all=true (every unpinned job)."},"job_id": {"type": "string",- "description": "Required for update/pause/resume/remove/run"+ "description": "Required for update/pause/resume/remove/run. For resnap: the job to adopt the current global inference resolution (omit if all=true)."+ },+ "all": {+ "type": "boolean",+ "description": "Only for action='resnap'. all=true refreshes the inference snapshot of EVERY unpinned agent job to the current global resolution (bulk 'make everything follow my new default'). Must be explicitly set to true — never implied. Omit (or false) to resnap a single job via job_id."},"prompt": {"type": "string",@@ -1028,7 +1079,7 @@ def check_cronjob_requirements() -> bool:_HANDLER_FORWARDED_ARGS = ("job_id", "prompt", "schedule", "name", "repeat", "deliver", "failure_deliver", "skill", "skills", "reason","script", "context_from", "continuity", "enabled_toolsets", "workdir", "no_agent", "attach_to_session",- "paused_reason")+ "paused_reason", "all")def _cronjob_handler(args, **kw):