Skip to content

The agent that grows with you

refactor(config-remote): meet the code-health ratchet on main

Ben Barclay3b05d4501bd0
diff --git a/cron/jobs.py b/cron/jobs.py
index c07480451b7..3b26b6305a3 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1658,7 +1658,6 @@ def _main_model_pin() -> tuple[Optional[str], Optional[str]]:
no second precedence axis. ``(None, None)`` when nothing is configured (the job stays unpinned)."""
from hermes_cli.config_backend import config_exists
from hermes_cli.config_effective import load_user_config_effective
-
cfg_path = get_hermes_home() / "config.yaml"
cfg = load_user_config_effective(cfg_path) if config_exists(cfg_path) else {}
model_cfg = cfg.get("model") or {}
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 7df27bf29ed..838a4c62e7e 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -1506,16 +1506,6 @@ class _BoundedCronSessionDB:
return _bounded
-def _job_doc_header(job_name: str, job_id: str, now_iso: str, mode: str) -> str:
- """Common markdown header for the short-circuit run docs (no_agent / monitor)."""
- return (
- f"# Cron Job: {job_name}\n\n"
- f"**Job ID:** {job_id}\n"
- f"**Run Time:** {now_iso}\n"
- f"**Mode:** {mode}\n"
- )
-
-
def _resolve_job_workdir(job: dict, job_id: str) -> Optional[str]:
"""Configured job workdir, or None when unset / no longer a directory (logged)."""
workdir = (job.get("workdir") or "").strip() or None
@@ -1635,12 +1625,12 @@ def _load_cron_job_config(job: dict, job_id: str, job_name: str) -> _CronJobConf
the main agent model (config ``model:``, then HERMES_MODEL) > the claimed welcome trial's. Re-read
every tick (no cache) so ``hermes cron edit --model`` and ``hermes model`` both apply next tick."""
from hermes_cli.anon_auth import trial_model
- from hermes_cli.config_backend import config_exists
model = job.get("model") or cron_env_setting("HERMES_MODEL") or ""
_cron_default_provider = ""
_cfg: dict = {}
_model_cfg: Any = {}
try:
+ from hermes_cli.config_backend import config_exists
from hermes_cli.config_effective import load_user_config_effective
_cfg_path = str(_get_hermes_home() / "config.yaml")
if config_exists(_cfg_path):
@@ -4396,7 +4386,7 @@ from cron.scheduler_script import (
from cron.scheduler_prompt import (
_PROMPT_FRAME, _PROMPT_HEADING, _PROMPT_SEPARATOR, _RESPONSE_FRAME, _RESPONSE_HEADING,
_RESPONSE_TERMINATOR, _block_and_pause_job, _build_job_prompt, _guard_job_credential_exfil,
- _parse_wake_gate,
+ _job_doc_header, _parse_wake_gate,
)
from cron.scheduler_preflight import (
BLOCKED_CONFIG_MARKER, BLOCKED_CONFIG_SILENT_MARKER, _cron_preflight_enabled,
diff --git a/cron/scheduler_prompt.py b/cron/scheduler_prompt.py
index 1ef34b18f00..a5e862f5a0c 100644
--- a/cron/scheduler_prompt.py
+++ b/cron/scheduler_prompt.py
@@ -79,6 +79,16 @@ _RESPONSE_FRAME_RE = re.compile(
rf"(?m)^{re.escape(_RESPONSE_FRAME)}(\d+)\n{re.escape(_RESPONSE_HEADING)}")
+def _job_doc_header(job_name: str, job_id: str, now_iso: str, mode: str) -> str:
+ """Common markdown header for the short-circuit run docs (no_agent / monitor)."""
+ return (
+ f"# Cron Job: {job_name}\n\n"
+ f"**Job ID:** {job_id}\n"
+ f"**Run Time:** {now_iso}\n"
+ f"**Mode:** {mode}\n"
+ )
+
+
def _archive_answer(archive: str) -> str | None:
"""The reusable answer of a stored run, using its length frame when available.
diff --git a/gateway/run.py b/gateway/run.py
index 6efb375623c..aacf33b94f6 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -44,6 +44,7 @@ from agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, copy_iden
from agent.turn_context import compression_made_progress
from agent.session_activity import ActivityProvenance, AwakeIdleMeter
from hermes_cli.config import _is_ssh_remote_tilde_cwd, cfg_get, config_exists
+from hermes_cli.config_backend import require_file_tooling
from gateway.run_common import _csv_or_list_to_set
from hermes_cli.fallback_config import pre_agent_fallback_notice
from gateway.turn_executor import _UnboundedThreadExecutor
@@ -5154,7 +5155,6 @@ def main():
config = None
if args.config:
- from hermes_cli.config_backend import require_file_tooling
require_file_tooling("gateway --config <file>")
import hermes_yaml as yaml
with open(args.config, encoding="utf-8-sig") as f:
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index d65ef2bdb65..bcb2deea56d 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -27,6 +27,7 @@ from hermes_state_holders import read_only_db_uri
from agent.provider_media import GENERATED_SUBDIR
from hermes_cli.archive_safe import normalize_archive_parts
from hermes_cli.backup_sqlite import _close_quietly, _safe_copy_db
+from hermes_cli.config_backend import require_file_tooling
from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, profile_root_entry
from hermes_cli.sizefmt import format_bytes as _format_size
@@ -597,6 +598,7 @@ def run_backup(args) -> bool:
the caller turns False into exit status 1 so a cron/systemd timer never publishes a "successful"
archive that is missing state.db. Hard failures keep raising ``SystemExit``.
"""
+ require_file_tooling("`hermes backup`")
hermes_root = get_default_hermes_root()
if not hermes_root.is_dir():
@@ -733,6 +735,7 @@ def _import_member_rel(member: str, prefix: str) -> tuple[str, bool]:
def run_import(args) -> Optional[int]:
"""Restore a Hermes backup; return 1 on damaged archives or incomplete restores."""
+ require_file_tooling("`hermes import`")
zip_path = Path(args.zipfile).expanduser().resolve()
if not zip_path.is_file():
@@ -760,7 +763,6 @@ def run_import(args) -> Optional[int]:
print(f"Backup contains {file_count} files")
print(f"Target: {display_hermes_home()}")
-
if prefix:
print(f"Detected archive prefix: {prefix!r} (will be stripped)")
@@ -1540,6 +1542,7 @@ def restore_quick_snapshot(
was not refused or skipped.
"""
from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance
+ require_file_tooling("Snapshot restore")
home = hermes_home or get_hermes_home()
try:
with exclusive_maintenance([home]):
diff --git a/hermes_cli/config_migrations.py b/hermes_cli/config_migrations.py
index a6ac26ab909..acdf2f98878 100644
--- a/hermes_cli/config_migrations.py
+++ b/hermes_cli/config_migrations.py
@@ -911,25 +911,21 @@ def run_migrations(
"""
token = _CONFIG_ONLY.set(config_only)
try:
- _run_steps(current_ver, results, quiet, unversioned)
+ for target_ver, migration_fn in MIGRATIONS:
+ due = current_ver < target_ver or target_ver in STAMP_INDEPENDENT_STEPS
+ if due and (target_ver in LEGACY_KEY_STEPS or not unversioned):
+ try:
+ migration_fn(results, quiet)
+ except Exception as exc:
+ # A malformed nested value in one step must not abort the rest of the
+ # ladder (config loading itself fails otherwise). Loud, not silent.
+ warning = f"config migration to v{target_ver} failed and was skipped: {exc}"
+ results.setdefault("warnings", []).append(warning)
+ # Quiet callers (profile creation, unattended update) discard ``results`` and
+ # migrate_config still stamps the latest version, so without a log line the
+ # skipped step vanishes for good.
+ logger.warning("%s", warning)
+ if not quiet:
+ print(f" ⚠ {warning}")
finally:
_CONFIG_ONLY.reset(token)
-
-
-def _run_steps(current_ver: int, results: dict[str, Any], quiet: bool, unversioned: bool) -> None:
- for target_ver, migration_fn in MIGRATIONS:
- due = current_ver < target_ver or target_ver in STAMP_INDEPENDENT_STEPS
- if due and (target_ver in LEGACY_KEY_STEPS or not unversioned):
- try:
- migration_fn(results, quiet)
- except Exception as exc:
- # A malformed nested value in one step must not abort the rest of the
- # ladder (config loading itself fails otherwise). Loud, not silent.
- warning = f"config migration to v{target_ver} failed and was skipped: {exc}"
- results.setdefault("warnings", []).append(warning)
- # Quiet callers (profile creation, unattended update) discard ``results`` and
- # migrate_config still stamps the latest version, so without a log line the
- # skipped step vanishes for good.
- logger.warning("%s", warning)
- if not quiet:
- print(f" ⚠ {warning}")
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index 7501d8d8510..f7dc6047494 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -469,7 +469,7 @@ def _bootstrap_env(home: Path | None = None, project_env: Path | None = None) ->
from hermes_cli import managed_scope
managed_dir = managed_scope.get_managed_dir()
- except Exception: # noqa: BLE001 — same fail-open as _apply_managed_env
+ except Exception: # health: allow BLE001 -- managed scope never blocks startup, as in _apply_managed_env
managed_dir = None
if managed_dir is not None:
layers.append((managed_dir / ".env", True))
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index 8c51fa228b7..dd7716e53b3 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -18,6 +18,9 @@ from typing import Dict, List, Optional, Tuple
from agent.file_safety import HOME_CREDENTIAL_DIRS
from hermes_cli.archive_safe import archive_root_dirs, make_targz, normalize_archive_parts, safe_extract_targz
+from hermes_cli import config_backend as _config_backend
+from hermes_cli.config_backend import config_exists, config_version, require_file_tooling
+from hermes_cli.profiles_config import _migrate_profile_config_if_outdated
from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS
from hermes_cli.profiles_remove import _rmtree_make_writable, _rmtree_with_retry, wait_profile_unowned
from hermes_constants import (
@@ -584,28 +587,6 @@ def remove_wrapper_script(name: str) -> bool:
return False
-def _migrate_profile_config_if_outdated(profile_dir: Path) -> None:
- """Migrate a copied config.yaml to the current schema (non-interactive, scoped to the new
- profile); otherwise the first desktop/doctor view shows a scary ``v0 -> latest`` warning."""
- from hermes_cli.config_backend import config_exists, supports_file_tooling
- if not supports_file_tooling():
- return # no local config.yaml to migrate: a remote backend migrates in memory on read (D12)
- if not config_exists(profile_dir / "config.yaml"):
- return
- # Creation must not fail over an unmigratable old config; `hermes doctor --fix` surfaces
- # the detailed error in the target profile.
- with contextlib.suppress(Exception):
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
- from hermes_cli.config import check_config_version, migrate_config
- token = set_hermes_home_override(str(profile_dir))
- try:
- current_ver, latest_ver = check_config_version()
- if current_ver < latest_ver:
- migrate_config(interactive=False, quiet=True)
- finally:
- reset_hermes_home_override(token)
-
-
def find_alias_for_profile(profile_name: str) -> Optional[str]:
"""Alias name of the wrapper activating *profile_name*, or None. For listing ALL profiles
prefer :func:`build_alias_map`: per-profile calls re-read every wrapper N times (O(N*M)),
@@ -1131,6 +1112,7 @@ def profiles_to_serve(multiplex: bool, *, include_standalone: bool = False,
def _resolve_clone_source(clone_from: Optional[str]) -> Path:
"""Directory to clone from: the named profile, or the active profile when ``None``."""
+ require_file_tooling("Profile clone")
if clone_from is None:
from hermes_constants import get_hermes_home
source_dir = get_hermes_home()
@@ -2286,8 +2268,7 @@ def _refuse_rename_without_file_tooling(old_canon: str) -> None:
"""A remote config backend keys each profile's settings by its canonical name, and the plane
has no rename: renaming the local home would leave the settings under the old name and read
another (possibly populated) level under the new one. Refused before any side effect."""
- from hermes_cli.config_backend import get_config_backend
- backend = get_config_backend()
+ backend = _config_backend.get_config_backend()
if not backend.supports_file_tooling():
raise ValueError(
f"Cannot rename profile '{old_canon}': its config lives in the {backend.name!r} config "
diff --git a/hermes_cli/profiles_config.py b/hermes_cli/profiles_config.py
new file mode 100644
index 00000000000..0de7d711bb0
--- /dev/null
+++ b/hermes_cli/profiles_config.py
@@ -0,0 +1,29 @@
+"""Migrate a new profile's copied config document (``hermes_cli.profiles`` creation helper)."""
+
+from __future__ import annotations
+
+import contextlib
+from pathlib import Path
+from hermes_cli.config_backend import config_exists, supports_file_tooling
+
+
+def _migrate_profile_config_if_outdated(profile_dir: Path) -> None:
+ """Migrate a copied config.yaml to the current schema (non-interactive, scoped to the new
+ profile); otherwise the first desktop/doctor view shows a scary ``v0 -> latest`` warning."""
+ if not supports_file_tooling():
+ return # no local config.yaml to migrate: a remote backend migrates in memory on read (D12)
+ if not config_exists(profile_dir / "config.yaml"):
+ return
+ # Creation must not fail over an unmigratable old config; `hermes doctor --fix` surfaces
+ # the detailed error in the target profile.
+ with contextlib.suppress(Exception):
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from hermes_cli.config import check_config_version, migrate_config
+ token = set_hermes_home_override(str(profile_dir))
+ try:
+ current_ver, latest_ver = check_config_version()
+ if current_ver < latest_ver:
+ migrate_config(interactive=False, quiet=True)
+ finally:
+ reset_hermes_home_override(token)
+
diff --git a/tui_gateway/pet_sheet.py b/tui_gateway/pet_sheet.py
new file mode 100644
index 00000000000..776c2cb8ecd
--- /dev/null
+++ b/tui_gateway/pet_sheet.py
@@ -0,0 +1,54 @@
+"""Pure pet spritesheet helpers (revision id, per-row frame counts, row taxonomy, payload clone) for
+the ``pet.*`` RPCs in ``tui_gateway.server``."""
+
+from __future__ import annotations
+
+import contextlib
+
+
+def _pet_sheet_revision(spritesheet) -> str:
+ """Stable revision id for one spritesheet file."""
+ with contextlib.suppress(Exception):
+ stat = spritesheet.stat()
+ return f"{stat.st_mtime_ns}:{stat.st_size}"
+ return "0:0"
+
+
+def _clone_pet_payload(payload: dict) -> dict:
+ """Shallow-clone cached payloads so callers can't mutate shared state."""
+ out = dict(payload)
+ for key, kind in (("framesByState", dict), ("framesByRow", dict), ("stateRows", list)):
+ if isinstance(payload.get(key), kind):
+ out[key] = kind(payload[key])
+ return out
+
+
+def _pet_row_frame_counts(spritesheet) -> dict:
+ """Real frame count per concrete spritesheet row name."""
+ with contextlib.suppress(Exception):
+ from PIL import Image
+ from agent.pet import constants, render
+ with Image.open(spritesheet) as opened:
+ image = opened.convert("RGBA")
+ W, H = constants.FRAME_W, constants.FRAME_H
+ cols = max(1, image.width // W)
+ row_count = max(1, image.height // H)
+ rows = constants.state_rows_for_grid(row_count)
+ out: dict[str, int] = {}
+ for row_idx, name in enumerate(rows[:row_count]):
+ top = row_idx * H
+ blank = lambda col: render._frame_is_blank(image.crop((col * W, top, col * W + W, top + H)))
+ out[name] = next((col for col in range(cols) if blank(col)), cols) # frames before the first blank cell
+ return out
+ return {}
+
+
+def _pet_state_rows(spritesheet) -> list[str]:
+ """Row taxonomy for the concrete sheet (legacy 8-row or current 9-row atlas), in the renderer's `PetState` names."""
+ from agent.pet import constants
+ with contextlib.suppress(Exception):
+ from PIL import Image
+ with Image.open(spritesheet) as image:
+ row_count = max(1, image.height // constants.FRAME_H)
+ return list(constants.state_rows_for_grid(row_count))
+ return list(constants.STATE_ROWS)
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index a0f5934fba2..d32368d06ae 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -27,7 +27,10 @@ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, s
from hermes_constants import (
get_hermes_home, get_hermes_home_override, get_process_hermes_home, profile_name_for_home,
reset_hermes_home_override, set_hermes_home_override)
+from hermes_cli import config_backend as _config_backend
+from hermes_cli.config_backend import Changes, config_exists, supports_file_tooling
from hermes_cli.env_loader import load_hermes_dotenv
+from tui_gateway.pet_sheet import _clone_pet_payload, _pet_row_frame_counts, _pet_sheet_revision, _pet_state_rows
from utils import is_truthy_value
from hermes_state_ids import new_session_id
from tools.environments.local import hermes_subprocess_env
@@ -671,7 +674,6 @@ def _profile_configured_cwd(profile_home: Path | None) -> str | None:
env var (issue #40334). Returns an absolute, existing directory, or None for placeholders / missing /
invalid paths.
"""
- from hermes_cli.config_backend import config_exists
if profile_home is None:
return None
with contextlib.suppress(Exception):
@@ -1353,15 +1355,13 @@ def _write_config_changes(sets: dict, unsets: tuple = ()) -> None:
the bulk save's silent omission, so a setter never reports a refused value as saved. Nothing is
applied when it raises. The file backend keeps its raw round-trip (callers branch on
``supports_file_tooling()``)."""
- from hermes_cli.config_backend import Changes, get_config_backend
try:
- get_config_backend().write_changes(_active_config_path().parent, Changes(set=dict(sets), unset=tuple(unsets)))
+ _config_backend.get_config_backend().write_changes(_active_config_path().parent, Changes(set=dict(sets), unset=tuple(unsets)))
finally:
_drop_cfg_cache()
def _write_config_key(key_path: str, value):
- from hermes_cli.config_backend import supports_file_tooling
if not supports_file_tooling():
_write_config_changes({key_path: value})
return
@@ -1798,43 +1798,6 @@ _pet_payload_cache_lock = threading.Lock()
_pet_payload_cache: dict[tuple, dict] = {}
-def _pet_sheet_revision(spritesheet) -> str:
- """Stable revision id for one spritesheet file."""
- with contextlib.suppress(Exception):
- stat = spritesheet.stat()
- return f"{stat.st_mtime_ns}:{stat.st_size}"
- return "0:0"
-
-
-def _clone_pet_payload(payload: dict) -> dict:
- """Shallow-clone cached payloads so callers can't mutate shared state."""
- out = dict(payload)
- for key, kind in (("framesByState", dict), ("framesByRow", dict), ("stateRows", list)):
- if isinstance(payload.get(key), kind):
- out[key] = kind(payload[key])
- return out
-
-
-def _pet_row_frame_counts(spritesheet) -> dict:
- """Real frame count per concrete spritesheet row name."""
- with contextlib.suppress(Exception):
- from PIL import Image
- from agent.pet import constants, render
- with Image.open(spritesheet) as opened:
- image = opened.convert("RGBA")
- W, H = constants.FRAME_W, constants.FRAME_H
- cols = max(1, image.width // W)
- row_count = max(1, image.height // H)
- rows = constants.state_rows_for_grid(row_count)
- out: dict[str, int] = {}
- for row_idx, name in enumerate(rows[:row_count]):
- top = row_idx * H
- blank = lambda col: render._frame_is_blank(image.crop((col * W, top, col * W + W, top + H)))
- out[name] = next((col for col in range(cols) if blank(col)), cols) # frames before the first blank cell
- return out
- return {}
-
-
def _pet_cfg() -> dict:
"""``display.pet`` from the canonical config ({} on any failure)."""
with contextlib.suppress(Exception):
@@ -1901,17 +1864,6 @@ def _pet_active_selection():
return enabled, pet, float(pet_cfg.get("scale", constants.DEFAULT_SCALE) or constants.DEFAULT_SCALE)
-def _pet_state_rows(spritesheet) -> list[str]:
- """Row taxonomy for the concrete sheet (legacy 8-row or current 9-row atlas), in the renderer's `PetState` names."""
- from agent.pet import constants
- with contextlib.suppress(Exception):
- from PIL import Image
- with Image.open(spritesheet) as image:
- row_count = max(1, image.height // constants.FRAME_H)
- return list(constants.state_rows_for_grid(row_count))
- return list(constants.STATE_ROWS)
-
-
def _pet_gen_root():
"""Profile-scoped staging dir for in-progress generation drafts."""
root = get_hermes_home() / "cache" / "pet-gen"