Skip to content

The agent that grows with you

fix(update): restore cron agent-job prompts degraded during the update window

Brooklyn Nicholson55f616694ce1
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 29d8ae3ebc9..66ad325be78 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -1664,6 +1664,189 @@ def restore_cron_jobs_if_emptied(
return {"restored": True, "job_count": snap_count, "snapshot_id": snapshot_id}
+def _load_cron_jobs_doc(path: Path) -> Optional[Any]:
+ """Parse ``path`` as the canonical ``{"jobs": [...]}`` doc (legacy bare list honoured).
+
+ ``None`` = missing/unreadable/non-dict-with-list — same dialect rules as
+ :func:`_count_cron_jobs` (utf-8-sig for Windows BOMs). Never raises.
+ """
+ if not path.is_file():
+ return None
+ try:
+ with open(path, "r", encoding="utf-8-sig") as f:
+ data = json.load(f)
+ except (OSError, json.JSONDecodeError):
+ return None
+ if isinstance(data, dict):
+ jobs = data.get("jobs", [])
+ return data if isinstance(jobs, list) else None
+ if isinstance(data, list):
+ return data
+ return None
+
+
+def _cron_jobs_list(doc: Any) -> list[Any]:
+ """The job list out of either document shape. Empty when malformed."""
+ if isinstance(doc, list):
+ return doc
+ if isinstance(doc, dict):
+ jobs = doc.get("jobs", [])
+ return jobs if isinstance(jobs, list) else []
+ return []
+
+
+def _prompt_degraded(job: Dict[str, Any]) -> bool:
+ """True when an agent job's prompt field is unusable: blank, missing, or
+ collapsed to the job's own name (a name is not a prompt)."""
+ if job.get("no_agent"):
+ return False
+ prompt = job.get("prompt")
+ if not isinstance(prompt, str) or not prompt.strip():
+ return True
+ return prompt.strip() == str(job.get("name", "")).strip()
+
+
+def restore_cron_prompt_fields_if_degraded(
+ snapshot_id: str,
+ hermes_home: Optional[Path] = None,
+) -> Optional[Dict[str, Any]]:
+ """Safety net for field-level cron-job degradation across ``hermes update``.
+
+ A writer active during the update's mutation window replaced every
+ agent-job ``prompt`` with the job's own ``name`` while the job COUNT
+ stayed identical, so the count-based net
+ (:func:`restore_cron_jobs_if_emptied`) passed the loss undetected
+ (issue #82990): 6 jobs before, 6 jobs after, every one of them with an
+ empty prompt wearing its name.
+
+ Mirrors the field-level pattern of
+ :func:`restore_config_model_settings_if_rewritten`: compare the live
+ file against the pre-update snapshot taken minutes earlier by this same
+ update run, and restore ONLY the ``prompt`` field of a live agent job
+ whose id matches a snapshot job — never the whole record, never jobs the
+ snapshot does not know. Conservative on purpose:
+
+ - a live prompt is only restored when it is blank/missing or exactly
+ equal to the job's own name — a legitimate user edit that merely
+ differs from the snapshot is never stomped;
+ - ``no_agent`` script jobs are never touched (they have no prompt);
+ - a blank snapshot prompt restores nothing (there is nothing better to
+ put back).
+
+ Args:
+ snapshot_id: The pre-update quick-snapshot id (from
+ :func:`create_quick_snapshot`).
+ hermes_home: Override for the Hermes home directory (tests/siblings).
+
+ Returns:
+ ``None`` when no action was taken (the common, healthy path). On a
+ successful restore, ``{"restored": True, "prompts": N,
+ "snapshot_id": ...}`` so the caller can warn the user.
+ """
+ if not snapshot_id:
+ return None
+
+ home = hermes_home or get_hermes_home()
+ live_path = home / _CRON_JOBS_REL
+ snap_path = _quick_snapshot_root(home) / snapshot_id / _CRON_JOBS_REL
+
+ live_doc = _load_cron_jobs_doc(live_path)
+ if live_doc is None:
+ return None
+ snap_doc = _load_cron_jobs_doc(snap_path)
+ if snap_doc is None:
+ return None
+
+ snap_by_id: Dict[str, Dict[str, Any]] = {}
+ for job in _cron_jobs_list(snap_doc):
+ if isinstance(job, dict):
+ snap_by_id[str(job.get("id", ""))] = job
+
+ restored_ids: list[str] = []
+ live_jobs = _cron_jobs_list(live_doc)
+ for job in live_jobs:
+ if not isinstance(job, dict):
+ continue
+ snap_job = snap_by_id.get(str(job.get("id", "")))
+ if snap_job is None:
+ continue
+ if not _prompt_degraded(job):
+ continue
+ snap_prompt = snap_job.get("prompt")
+ if not isinstance(snap_prompt, str) or not snap_prompt.strip():
+ continue
+ job["prompt"] = snap_prompt
+ restored_ids.append(str(job.get("id", "")))
+
+ if not restored_ids:
+ return None
+
+ try:
+ live_path.parent.mkdir(parents=True, exist_ok=True)
+ with _atomic_output_path(live_path) as tmp_path:
+ with open(tmp_path, "w", encoding="utf-8") as f:
+ json.dump(live_doc, f, indent=2)
+ f.write("\n")
+ except (OSError, PermissionError) as exc:
+ logger.error(
+ "Cron job prompts were degraded during update but auto-restore "
+ "failed: %s",
+ exc,
+ )
+ return None
+
+ logger.warning(
+ "Restored %d cron job prompt(s) from pre-update snapshot %s — job(s) "
+ "%s had their prompt replaced by the job name (#82990)",
+ len(restored_ids),
+ snapshot_id,
+ ", ".join(restored_ids),
+ )
+ return {
+ "restored": True,
+ "prompts": len(restored_ids),
+ "job_ids": restored_ids,
+ "snapshot_id": snapshot_id,
+ }
+
+
+def restore_cron_prompt_fields_all_profiles(
+ profile_snapshots: Dict[str, str],
+ invoking_home: Optional[Path] = None,
+) -> list[Dict[str, Any]]:
+ """Run the cron prompt-field safety net for every sibling profile.
+
+ Same contract as :func:`restore_cron_jobs_all_profiles`: each profile's
+ live ``cron/jobs.json`` is compared against ITS OWN same-generation
+ pre-update snapshot. Returns one result dict per restored profile, each
+ with a ``profile`` key added. Never raises.
+ """
+ restored: list[Dict[str, Any]] = []
+ if not profile_snapshots:
+ return restored
+ home = invoking_home or get_hermes_home()
+ by_name = dict(_sibling_profile_homes(home))
+ for name, snap_id in profile_snapshots.items():
+ profile_home = by_name.get(name)
+ if profile_home is None:
+ continue
+ try:
+ result = restore_cron_prompt_fields_if_degraded(
+ snap_id, hermes_home=profile_home
+ )
+ except Exception as exc:
+ logger.debug(
+ "Cron prompt-field restore check for profile %s failed: %s",
+ name,
+ exc,
+ )
+ continue
+ if result:
+ result["profile"] = name
+ restored.append(result)
+ return restored
+
+
def _sibling_profile_homes(invoking_home: Path) -> list[tuple[str, Path]]:
"""(name, home) for every OTHER profile on this install. Never raises.
diff --git a/hermes_cli/update_cmd_config.py b/hermes_cli/update_cmd_config.py
index ac11c5739dd..fd99c81a6b1 100644
--- a/hermes_cli/update_cmd_config.py
+++ b/hermes_cli/update_cmd_config.py
@@ -78,6 +78,12 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None:
f"cron/jobs.json lost jobs during this update — restored {r['job_count']} job(s) "
f"from pre-update snapshot {r['snapshot_id']}.")
+ def _prompt_line(r):
+ return (
+ f"cron/jobs.json had agent-job prompt(s) replaced by the job name during this "
+ f"update — restored {r['prompts']} prompt(s) from pre-update snapshot "
+ f"{r['snapshot_id']}.")
+
def _cfg_line(r):
return (
f"config.yaml user model settings were rewritten during this update — restored "
@@ -93,6 +99,15 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None:
if cron_restore:
print()
print(f" ⚠️ {_cron_line(cron_restore)}")
+ with _best_effort("Cron prompt-field auto-restore check failed: %s"):
+ # Safety net: a writer in the update's mutation window replaced agent-job prompts
+ # with the job NAME while the count stayed identical, so the count-based net above
+ # passed it undetected (issue #82990). Restore only the degraded prompt fields.
+ from hermes_cli.backup import restore_cron_prompt_fields_if_degraded
+ prompt_restore = restore_cron_prompt_fields_if_degraded(pre_update_snapshot_id)
+ if prompt_restore:
+ print()
+ print(f" ⚠️ {_prompt_line(prompt_restore)}")
with _best_effort("Config model-settings auto-restore check failed: %s"):
from hermes_cli.backup import restore_config_model_settings_if_rewritten
cfg_restore = restore_config_model_settings_if_rewritten(pre_update_snapshot_id)
@@ -104,6 +119,11 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None:
for _restored in restore_cron_jobs_all_profiles(_LAST_SIBLING_SNAPSHOTS):
print()
print(f" ⚠️ Profile '{_restored['profile']}': {_cron_line(_restored)}")
+ with _best_effort('Sibling cron prompt-field auto-restore check failed: %s'):
+ from hermes_cli.backup import restore_cron_prompt_fields_all_profiles
+ for _prompt_restored in restore_cron_prompt_fields_all_profiles(_LAST_SIBLING_SNAPSHOTS):
+ print()
+ print(f" ⚠️ Profile '{_prompt_restored['profile']}': {_prompt_line(_prompt_restored)}")
with _best_effort('Sibling config auto-restore check failed: %s'):
from hermes_cli.backup import restore_config_model_settings_all_profiles
for _cfg_restored in restore_config_model_settings_all_profiles(_LAST_SIBLING_SNAPSHOTS):
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index 364ea288ac7..89113839456 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -2125,6 +2125,162 @@ class TestRestoreCronJobsIfEmptied:
assert len(restored["jobs"]) == 19
+# ---------------------------------------------------------------------------
+# Cron agent-job prompt field degradation across update (issue #82990)
+# ---------------------------------------------------------------------------
+
+class TestRestoreCronPromptFieldsIfDegraded:
+ """A writer in the update's mutation window replaced every agent-job prompt
+ with the job's own name while the count stayed identical — the count-based
+ net passed it undetected. `restore_cron_prompt_fields_if_degraded` is the
+ field-level net."""
+
+ @staticmethod
+ def _seed_jobs(path: Path, jobs):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({"jobs": jobs}))
+
+ def _make_snapshot(self, hermes_home: Path, label="pre-update"):
+ from hermes_cli.backup import create_quick_snapshot
+ return create_quick_snapshot(label=label, hermes_home=hermes_home, keep=5)
+
+ def test_restores_prompts_when_count_unchanged_but_clobbered(self, tmp_path):
+ """The reported incident: 6 jobs before, 6 after, every prompt == name."""
+ from hermes_cli.backup import restore_cron_prompt_fields_if_degraded
+ hermes_home = tmp_path / ".hermes"
+ jobs_path = hermes_home / "cron" / "jobs.json"
+ self._seed_jobs(jobs_path, [
+ {"id": f"job-{i}", "name": f"Morning brief {i}",
+ "prompt": f"Read the news and write brief {i}."}
+ for i in range(6)
+ ])
+ snap_id = self._make_snapshot(hermes_home)
+ assert snap_id
+
+ # The mutation window clobbers prompts to the name; count unchanged.
+ self._seed_jobs(jobs_path, [
+ {"id": f"job-{i}", "name": f"Morning brief {i}",
+ "prompt": f"Morning brief {i}"}
+ for i in range(6)
+ ])
+
+ result = restore_cron_prompt_fields_if_degraded(snap_id, hermes_home=hermes_home)
+ assert result is not None
+ assert result["restored"] is True
+ assert result["prompts"] == 6
+ assert result["snapshot_id"] == snap_id
+
+ restored = json.loads(jobs_path.read_text())
+ for i, job in enumerate(restored["jobs"]):
+ assert job["prompt"] == f"Read the news and write brief {i}."
+ # Only the prompt was touched — name still the live one.
+ assert job["name"] == f"Morning brief {i}"
+
+ def test_blank_prompt_is_restored_too(self, tmp_path):
+ """Missing/blank prompt on a live agent job is equally unusable."""
+ from hermes_cli.backup import restore_cron_prompt_fields_if_degraded
+ hermes_home = tmp_path / ".hermes"
+ jobs_path = hermes_home / "cron" / "jobs.json"
+ self._seed_jobs(jobs_path, [{"id": "a", "name": "Cleanup", "prompt": "Clean the tmp dir."}])
+ snap_id = self._make_snapshot(hermes_home)
+ assert snap_id
+
+ self._seed_jobs(jobs_path, [{"id": "a", "name": "Cleanup", "prompt": ""}])
+
+ result = restore_cron_prompt_fields_if_degraded(snap_id, hermes_home=hermes_home)
+ assert result is not None
+ assert result["prompts"] == 1
+ assert json.loads(jobs_path.read_text())["jobs"][0]["prompt"] == "Clean the tmp dir."
+
+ def test_no_agent_jobs_are_untouched(self, tmp_path):
+ """Script jobs have no prompt — never restored, never stomped."""
+ from hermes_cli.backup import restore_cron_prompt_fields_if_degraded
+ hermes_home = tmp_path / ".hermes"
+ jobs_path = hermes_home / "cron" / "jobs.json"
+ self._seed_jobs(jobs_path, [
+ {"id": "agent", "name": "Brief", "prompt": "Write the brief."},
+ {"id": "script", "name": "Backup", "no_agent": True, "script": "echo hi", "prompt": "Backup"},
+ ])
+ snap_id = self._make_snapshot(hermes_home)
+ assert snap_id
+
+ self._seed_jobs(jobs_path, [
+ {"id": "agent", "name": "Brief", "prompt": "Brief"},
+ {"id": "script", "name": "Backup", "no_agent": True, "script": "echo hi", "prompt": "Backup"},
+ ])
+
+ result = restore_cron_prompt_fields_if_degraded(snap_id, hermes_home=hermes_home)
+ assert result is not None
+ assert result["prompts"] == 1
+ assert result["job_ids"] == ["agent"]
+ jobs = json.loads(jobs_path.read_text())["jobs"]
+ assert jobs[0]["prompt"] == "Write the brief."
+ assert jobs[1]["prompt"] == "Backup" # untouched
+
+ def test_a_legitimate_user_edit_is_not_stomped(self, tmp_path):
+ """Only prompt==name or blank restores — a genuinely different prompt
+ is the user's edit during the window, not degradation."""
+ from hermes_cli.backup import restore_cron_prompt_fields_if_degraded
+ hermes_home = tmp_path / ".hermes"
+ jobs_path = hermes_home / "cron" / "jobs.json"
+ self._seed_jobs(jobs_path, [{"id": "a", "name": "Old", "prompt": "Old prompt text."}])
+ snap_id = self._make_snapshot(hermes_home)
+ assert snap_id
+
+ self._seed_jobs(jobs_path, [{"id": "a", "name": "New name", "prompt": "Deliberately rewritten prompt."}])
+
+ result = restore_cron_prompt_fields_if_degraded(snap_id, hermes_home=hermes_home)
+ assert result is None
+ assert json.loads(jobs_path.read_text())["jobs"][0]["prompt"] == "Deliberately rewritten prompt."
+
+ def test_a_legit_prompt_equal_to_name_stays(self, tmp_path):
+ """A user may legitimately set prompt == name; a blank SNAPSHOT prompt
+ means the snapshot has nothing better — restore nothing."""
+ from hermes_cli.backup import restore_cron_prompt_fields_if_degraded
+ hermes_home = tmp_path / ".hermes"
+ jobs_path = hermes_home / "cron" / "jobs.json"
+ # Snapshot job had a blank prompt (hand-edited oddity).
+ self._seed_jobs(jobs_path, [{"id": "a", "name": "Ping", "prompt": ""}])
+ snap_id = self._make_snapshot(hermes_home)
+ assert snap_id
+
+ # Live prompt collapsed to the name — but the snapshot has nothing to give back.
+ self._seed_jobs(jobs_path, [{"id": "a", "name": "Ping", "prompt": "Ping"}])
+
+ result = restore_cron_prompt_fields_if_degraded(snap_id, hermes_home=hermes_home)
+ assert result is None
+
+ def test_unknown_job_ids_are_left_alone(self, tmp_path):
+ """Jobs the snapshot does not know are new since the snapshot — theirs."""
+ from hermes_cli.backup import restore_cron_prompt_fields_if_degraded
+ hermes_home = tmp_path / ".hermes"
+ jobs_path = hermes_home / "cron" / "jobs.json"
+ self._seed_jobs(jobs_path, [{"id": "a", "name": "A", "prompt": "A prompt."}])
+ snap_id = self._make_snapshot(hermes_home)
+ assert snap_id
+
+ self._seed_jobs(jobs_path, [
+ {"id": "a", "name": "A", "prompt": "A prompt."},
+ {"id": "new", "name": "New", "prompt": "New"}, # created during the window
+ ])
+
+ result = restore_cron_prompt_fields_if_degraded(snap_id, hermes_home=hermes_home)
+ assert result is None
+
+ def test_healthy_file_is_untouched(self, tmp_path):
+ from hermes_cli.backup import restore_cron_prompt_fields_if_degraded
+ hermes_home = tmp_path / ".hermes"
+ jobs_path = hermes_home / "cron" / "jobs.json"
+ self._seed_jobs(jobs_path, [{"id": "a", "name": "A", "prompt": "A prompt."}])
+ snap_id = self._make_snapshot(hermes_home)
+ assert snap_id
+ before = jobs_path.read_text()
+
+ result = restore_cron_prompt_fields_if_degraded(snap_id, hermes_home=hermes_home)
+ assert result is None
+ assert jobs_path.read_text() == before
+
+
# ---------------------------------------------------------------------------
# config.yaml model/provider + MoA auto-restore after silent update rewrite
# (issue #64160)