The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(health): offset FILE_LINES growth by moving cohesive groups into topical siblings
Tekniuma070a5be3338
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 8adb01a6e62..9545e7c2fbf 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -1138,14 +1138,6 @@ def _newest_first(root: Path, keep_entry) -> List[Path]:_CRON_JOBS_REL = "cron/jobs.json"-# Config paths the update flow must never change (#64160): model routing and the MoA section are-# consumed machine-wide, so an update/repair cycle that rewrites them silently redirects paid-# inference. Dotted paths into raw config.yaml; a single-element tuple protects a whole section.-_PROTECTED_CONFIG_PATHS: Tuple[Tuple[str, ...], ...] = (- ("model", "provider"), ("model", "default"), ("model", "base_url"), ("model", "api_key"),- ("moa",))--def _prune_oldest(newest_first: List[Path], keep: int, remove, what: str) -> int:"""``remove(path)`` every entry past the first *keep*; return how many succeeded."""deleted = 0@@ -1789,189 +1781,6 @@ 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/backup_cron_prompts.py b/hermes_cli/backup_cron_prompts.pynew file mode 100644index 00000000000..c354fa73d42--- /dev/null+++ b/hermes_cli/backup_cron_prompts.py@@ -0,0 +1,204 @@+"""Post-update cron safety net for field-level loss: restore agent-job prompts an update+collapsed to the job name while the job count stayed the same (issue #82990).++Split out of ``hermes_cli.backup`` (which owns the quick snapshots this compares against and+the count-based net); ``backup`` names are late-imported so its patch seams+(``_sibling_profile_homes``) hold.+"""++import json+import logging+from pathlib import Path+from typing import Any, Dict, Optional++from hermes_constants import get_hermes_home++# Log-record parity with the origin module.+logger = logging.getLogger("hermes_cli.backup")+++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++ from hermes_cli.backup import _CRON_JOBS_REL, _atomic_output_path, _quick_snapshot_root++ 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+ from hermes_cli.backup import _sibling_profile_homes++ 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 restoreddiff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 2e803c4b984..78ada640826 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -2995,206 +2995,6 @@ def redact_config_value(value: Any, _depth: int = 0) -> Any:return value-def _section(title: str) -> None:- print()- print(color(f"◆ {title}", Colors.CYAN, Colors.BOLD))---def _show_managed_banner() -> None:- """Surface administrator-pinned settings so the user knows why a config.yaml value may not- be the effective one."""- managed_keys = managed_scope.managed_config_keys()- managed_env = managed_scope.load_managed_env()- if not managed_keys and not managed_env:- return- print()- print(color(- f" ⚷ Some settings are managed by your administrator ({managed_scope.get_managed_dir()}) "- f"and cannot be changed", Colors.YELLOW, Colors.BOLD))- for label, keys in (("config", managed_keys), ("env", managed_env)):- if keys:- print(color(f" Managed {label} keys: {', '.join(sorted(keys))}", Colors.YELLOW))---_SHOW_CONFIG_API_KEYS = (- ("OPENROUTER_API_KEY", "OpenRouter"),- ("VOICE_TOOLS_OPENAI_KEY", "OpenAI (STT/TTS)"),- ("EXA_API_KEY", "Exa"),- ("PARALLEL_API_KEY", "Parallel"),- ("FIRECRAWL_API_KEY", "Firecrawl"),- ("TAVILY_API_KEY", "Tavily"),- ("PERPLEXITY_API_KEY", "Perplexity"),- ("BROWSERBASE_API_KEY", "Browserbase"),- ("BROWSER_USE_API_KEY", "Browser Use"),- ("FAL_KEY", "FAL"))---def _show_model_section(config: Dict[str, Any]) -> None:- _section("Model")- print(f" Model: {redact_config_value(config.get('model', 'not set'))}")- cfg_max_turns = config.get('agent', {}).get('max_turns', DEFAULT_CONFIG['agent']['max_turns'])- print(f" Max turns: {cfg_max_turns}")- # Read the .env FILE directly so a stale HERMES_MAX_ITERATIONS ghost is caught even when the- # gateway bridge already overrode os.environ.- try:- env_ghost = load_env().get("HERMES_MAX_ITERATIONS")- except Exception:- env_ghost = None- if env_ghost is not None and str(env_ghost).strip() != str(cfg_max_turns).strip():- print(color(f" ⚠ .env has stale HERMES_MAX_ITERATIONS={env_ghost} "- f"(run 'hermes doctor --fix' to remove)", Colors.YELLOW))---def _show_display_section(config: Dict[str, Any]) -> None:- _section("Display")- display = config.get('display', {})- try:- from hermes_cli.personality import active_personality_name- active_personality = active_personality_name(config) or 'none'- except Exception:- active_personality = display.get('personality') or 'none'- on_off = lambda flag: 'on' if flag else 'off' # noqa: E731- print(f" Personality: {active_personality}")- print(f" Reasoning: {on_off(display.get('show_reasoning', True))}")- print(- f" Bell: complete={on_off(display.get('bell_on_complete', False))}, "- f"prompt={on_off(display.get('bell_on_prompt', False))}")- ump = display.get('user_message_preview', {})- ump = ump if isinstance(ump, dict) else {}- print(f" User preview: first {ump.get('first_lines', 2)} line(s), last {ump.get('last_lines', 2)} line(s)")---def _show_terminal_section(config: Dict[str, Any]) -> None:- _section("Terminal")- terminal = config.get('terminal', {})- print(f" Backend: {terminal.get('backend', 'local')}")- print(f" Working dir: {terminal.get('cwd', '.')}")- print(f" Timeout: {terminal.get('timeout', 60)}s")-- configured = lambda *names: 'configured' if all(get_env_value(n) for n in names) else '(not set)' # noqa: E731- from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE as default_img, DEFAULT_VERCEL_IMAGE as _DEFAULT_VERCEL_IMAGE- backend_lines = {- 'docker': lambda: [f" Docker image: {terminal.get('docker_image', default_img)}"],- 'singularity': lambda: [f" Image: {terminal.get('singularity_image', 'docker://' + default_img)}"],- 'modal': lambda: [- f" Modal image: {terminal.get('modal_image', default_img)}",- f" Modal token: {configured('MODAL_TOKEN_ID')}"],- 'daytona': lambda: [- f" Daytona image: {terminal.get('daytona_image', default_img)}",- f" API key: {configured('DAYTONA_API_KEY')}"],- 'vercel_sandbox': lambda: [- f" Vercel image: {terminal.get('vercel_runtime') or terminal.get('vercel_image') or _DEFAULT_VERCEL_IMAGE}",- f" Vercel auth: {'configured' if get_env_value('VERCEL_OIDC_TOKEN') or (get_env_value('VERCEL_TOKEN') and get_env_value('VERCEL_PROJECT_ID') and get_env_value('VERCEL_TEAM_ID')) else '(not set)'}",- ],- 'ssh': lambda: [- f" SSH host: {get_env_value('TERMINAL_SSH_HOST') or '(not set)'}",- f" SSH user: {get_env_value('TERMINAL_SSH_USER') or '(not set)'}"]}- for line in backend_lines.get(terminal.get('backend'), list)():- print(line)---def _show_compression_section(config: Dict[str, Any]) -> None:- _section("Context Compression")- compression = config.get('compression', {})- enabled = compression.get('enabled', True)- print(f" Enabled: {'yes' if enabled else 'no'}")- if not enabled:- return- print(f" Threshold: {compression.get('threshold', 0.50) * 100:.0f}%")- tt = compression.get('threshold_tokens')- try:- if tt is not None and int(tt) > 0:- print(f" Token cap: {int(tt):,} tokens (takes lower of ratio vs absolute)")- except (TypeError, ValueError):- pass- print(f" Target ratio: {compression.get('target_ratio', 0.20) * 100:.0f}% of threshold preserved")- print(f" Protect last: {compression.get('protect_last_n', 20)} messages")- print(f" Protect first: {compression.get('protect_first_n', 3)} non-system head messages")- aux_comp = config.get('auxiliary', {}).get('compression', {})- print(f" Model: {aux_comp.get('model', '') or '(auto)'}")- comp_provider = aux_comp.get('provider', 'auto')- if comp_provider and comp_provider != 'auto':- print(f" Provider: {comp_provider}")---def _show_aux_overrides(config: Dict[str, Any]) -> None:- aux_tasks = {"Vision": config.get('auxiliary', {}).get('vision', {})}- overrides = {- label: (t.get('provider', 'auto'), t.get('model', ''))- for label, t in aux_tasks.items()- if t.get('provider', 'auto') != 'auto' or t.get('model', '')}- if not overrides:- return- _section("Auxiliary Models (overrides)")- for label, (prov, mdl) in overrides.items():- parts = [f"provider={prov}"] + ([f"model={mdl}"] if mdl else [])- print(f" {label:12s} {', '.join(parts)}")---def _show_skill_settings() -> None:- try:- from agent.skill_utils import discover_all_skill_config_vars, resolve_skill_config_values- skill_vars = discover_all_skill_config_vars()- if not skill_vars:- return- resolved = resolve_skill_config_values(skill_vars)- _section("Skill Settings")- for var in skill_vars:- value = resolved.get(var["key"], "")- display_val = str(value) if value else color("(not set)", Colors.DIM)- skill_tag = color(f"[{var.get('skill', '')}]", Colors.DIM)- print(f" {var['key']:<20s} {display_val} {skill_tag}")- except Exception:- pass---def show_config():- """Display current configuration."""- config = load_config()-- print()- print(color("┌─────────────────────────────────────────────────────────┐", Colors.CYAN))- print(color("│ ☤ Hermes Configuration │", Colors.CYAN))- print(color("└─────────────────────────────────────────────────────────┘", Colors.CYAN))- _show_managed_banner()-- _section("Paths")- print(f" Config: {get_config_path()}")- print(f" Secrets: {get_env_path()}")- print(f" Install: {get_project_root()}")-- _section("API Keys")- for env_key, name in _SHOW_CONFIG_API_KEYS:- print(f" {name:<14} {redact_key(get_env_value(env_key))}")- from hermes_cli.auth import get_anthropic_key- print(f" {'Anthropic':<14} {redact_key(get_anthropic_key())}")-- _show_model_section(config)- _show_display_section(config)- _show_terminal_section(config)-- _section("Timezone")- tz = config.get('timezone', '')- print(f" Timezone: {tz or color('(server-local)', Colors.DIM)}")-- _show_compression_section(config)- _show_aux_overrides(config)-- _section("Messaging Platforms")- for label, env_key in (("Telegram", "TELEGRAM_BOT_TOKEN"), ("Discord", "DISCORD_BOT_TOKEN")):- state = 'configured' if get_env_value(env_key) else color('not configured', Colors.DIM)- print(f" {label + ':':<13} {state}")-- _show_skill_settings()-- print()- print(color("─" * 60, Colors.DIM))- print(color(" hermes config edit # Edit config file", Colors.DIM))- print(color(" hermes config set <key> <value>", Colors.DIM))- print(color(" hermes setup # Run setup wizard", Colors.DIM))- print()--def edit_config():"""Open config file in user's editor."""if is_managed():@@ -4001,9 +3801,14 @@ def _cmd_config_check(args):print()+def _cmd_config_show() -> None:+ from hermes_cli.config_show import show_config+ show_config()++_CONFIG_SUBCOMMANDS = {- None: lambda args: show_config(),- "show": lambda args: show_config(),+ None: lambda args: _cmd_config_show(),+ "show": lambda args: _cmd_config_show(),"edit": lambda args: edit_config(),"get": _cmd_config_get,"set": _cmd_config_set,diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 2f38976df3e..d21c34c1263 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2098,7 +2098,6 @@ DEFAULT_CONFIG = {"export": {"otlp": {"enabled": False, "endpoint": "", "headers_env": {}}},},"gateway": { # Gateway settings (messaging platforms: Telegram, Discord, Slack, ...).-# Seconds to let a SIGTERM-interrupted gateway agent unwind before adapter/database# teardown. Keep short so service-manager shutdowns don't exhaust their stop budget."signal_interrupt_grace_timeout": 1,diff --git a/hermes_cli/config_show.py b/hermes_cli/config_show.pynew file mode 100644index 00000000000..f9e709495cf--- /dev/null+++ b/hermes_cli/config_show.py@@ -0,0 +1,211 @@+"""``hermes config`` / ``hermes config show``: the read-only configuration summary.++Split out of ``hermes_cli.config``; config names are read through the module at call time+(``_cfg.<name>``) so ``hermes_cli.config.<name>`` patch seams hold.+"""++from typing import Any, Dict++from hermes_cli import config as _cfg+from hermes_cli import managed_scope+from hermes_cli.colors import Colors, color+++def _section(title: str) -> None:+ print()+ print(color(f"◆ {title}", Colors.CYAN, Colors.BOLD))+++def _show_managed_banner() -> None:+ """Surface administrator-pinned settings so the user knows why a config.yaml value may not+ be the effective one."""+ managed_keys = managed_scope.managed_config_keys()+ managed_env = managed_scope.load_managed_env()+ if not managed_keys and not managed_env:+ return+ print()+ print(color(+ f" ⚷ Some settings are managed by your administrator ({managed_scope.get_managed_dir()}) "+ f"and cannot be changed", Colors.YELLOW, Colors.BOLD))+ for label, keys in (("config", managed_keys), ("env", managed_env)):+ if keys:+ print(color(f" Managed {label} keys: {', '.join(sorted(keys))}", Colors.YELLOW))+++_SHOW_CONFIG_API_KEYS = (+ ("OPENROUTER_API_KEY", "OpenRouter"),+ ("VOICE_TOOLS_OPENAI_KEY", "OpenAI (STT/TTS)"),+ ("EXA_API_KEY", "Exa"),+ ("PARALLEL_API_KEY", "Parallel"),+ ("FIRECRAWL_API_KEY", "Firecrawl"),+ ("TAVILY_API_KEY", "Tavily"),+ ("PERPLEXITY_API_KEY", "Perplexity"),+ ("BROWSERBASE_API_KEY", "Browserbase"),+ ("BROWSER_USE_API_KEY", "Browser Use"),+ ("FAL_KEY", "FAL"))+++def _show_model_section(config: Dict[str, Any]) -> None:+ _section("Model")+ print(f" Model: {_cfg.redact_config_value(config.get('model', 'not set'))}")+ cfg_max_turns = config.get('agent', {}).get('max_turns', _cfg.DEFAULT_CONFIG['agent']['max_turns'])+ print(f" Max turns: {cfg_max_turns}")+ # Read the .env FILE directly so a stale HERMES_MAX_ITERATIONS ghost is caught even when the+ # gateway bridge already overrode os.environ.+ try:+ env_ghost = _cfg.load_env().get("HERMES_MAX_ITERATIONS")+ except Exception:+ env_ghost = None+ if env_ghost is not None and str(env_ghost).strip() != str(cfg_max_turns).strip():+ print(color(f" ⚠ .env has stale HERMES_MAX_ITERATIONS={env_ghost} "+ f"(run 'hermes doctor --fix' to remove)", Colors.YELLOW))+++def _show_display_section(config: Dict[str, Any]) -> None:+ _section("Display")+ display = config.get('display', {})+ try:+ from hermes_cli.personality import active_personality_name+ active_personality = active_personality_name(config) or 'none'+ except Exception:+ active_personality = display.get('personality') or 'none'+ on_off = lambda flag: 'on' if flag else 'off' # noqa: E731+ print(f" Personality: {active_personality}")+ print(f" Reasoning: {on_off(display.get('show_reasoning', True))}")+ print(+ f" Bell: complete={on_off(display.get('bell_on_complete', False))}, "+ f"prompt={on_off(display.get('bell_on_prompt', False))}")+ ump = display.get('user_message_preview', {})+ ump = ump if isinstance(ump, dict) else {}+ print(f" User preview: first {ump.get('first_lines', 2)} line(s), last {ump.get('last_lines', 2)} line(s)")+++def _show_terminal_section(config: Dict[str, Any]) -> None:+ _section("Terminal")+ terminal = config.get('terminal', {})+ print(f" Backend: {terminal.get('backend', 'local')}")+ print(f" Working dir: {terminal.get('cwd', '.')}")+ print(f" Timeout: {terminal.get('timeout', 60)}s")++ configured = lambda *names: 'configured' if all(_cfg.get_env_value(n) for n in names) else '(not set)' # noqa: E731+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE as default_img, DEFAULT_VERCEL_IMAGE as _DEFAULT_VERCEL_IMAGE+ backend_lines = {+ 'docker': lambda: [f" Docker image: {terminal.get('docker_image', default_img)}"],+ 'singularity': lambda: [f" Image: {terminal.get('singularity_image', 'docker://' + default_img)}"],+ 'modal': lambda: [+ f" Modal image: {terminal.get('modal_image', default_img)}",+ f" Modal token: {configured('MODAL_TOKEN_ID')}"],+ 'daytona': lambda: [+ f" Daytona image: {terminal.get('daytona_image', default_img)}",+ f" API key: {configured('DAYTONA_API_KEY')}"],+ 'vercel_sandbox': lambda: [+ f" Vercel image: {terminal.get('vercel_runtime') or terminal.get('vercel_image') or _DEFAULT_VERCEL_IMAGE}",+ f" Vercel auth: {'configured' if _cfg.get_env_value('VERCEL_OIDC_TOKEN') or (_cfg.get_env_value('VERCEL_TOKEN') and _cfg.get_env_value('VERCEL_PROJECT_ID') and _cfg.get_env_value('VERCEL_TEAM_ID')) else '(not set)'}",+ ],+ 'ssh': lambda: [+ f" SSH host: {_cfg.get_env_value('TERMINAL_SSH_HOST') or '(not set)'}",+ f" SSH user: {_cfg.get_env_value('TERMINAL_SSH_USER') or '(not set)'}"]}+ for line in backend_lines.get(terminal.get('backend'), list)():+ print(line)+++def _show_compression_section(config: Dict[str, Any]) -> None:+ _section("Context Compression")+ compression = config.get('compression', {})+ enabled = compression.get('enabled', True)+ print(f" Enabled: {'yes' if enabled else 'no'}")+ if not enabled:+ return+ print(f" Threshold: {compression.get('threshold', 0.50) * 100:.0f}%")+ tt = compression.get('threshold_tokens')+ try:+ if tt is not None and int(tt) > 0:+ print(f" Token cap: {int(tt):,} tokens (takes lower of ratio vs absolute)")+ except (TypeError, ValueError):+ pass+ print(f" Target ratio: {compression.get('target_ratio', 0.20) * 100:.0f}% of threshold preserved")+ print(f" Protect last: {compression.get('protect_last_n', 20)} messages")+ print(f" Protect first: {compression.get('protect_first_n', 3)} non-system head messages")+ aux_comp = config.get('auxiliary', {}).get('compression', {})+ print(f" Model: {aux_comp.get('model', '') or '(auto)'}")+ comp_provider = aux_comp.get('provider', 'auto')+ if comp_provider and comp_provider != 'auto':+ print(f" Provider: {comp_provider}")+++def _show_aux_overrides(config: Dict[str, Any]) -> None:+ aux_tasks = {"Vision": config.get('auxiliary', {}).get('vision', {})}+ overrides = {+ label: (t.get('provider', 'auto'), t.get('model', ''))+ for label, t in aux_tasks.items()+ if t.get('provider', 'auto') != 'auto' or t.get('model', '')}+ if not overrides:+ return+ _section("Auxiliary Models (overrides)")+ for label, (prov, mdl) in overrides.items():+ parts = [f"provider={prov}"] + ([f"model={mdl}"] if mdl else [])+ print(f" {label:12s} {', '.join(parts)}")+++def _show_skill_settings() -> None:+ try:+ from agent.skill_utils import discover_all_skill_config_vars, resolve_skill_config_values+ skill_vars = discover_all_skill_config_vars()+ if not skill_vars:+ return+ resolved = resolve_skill_config_values(skill_vars)+ _section("Skill Settings")+ for var in skill_vars:+ value = resolved.get(var["key"], "")+ display_val = str(value) if value else color("(not set)", Colors.DIM)+ skill_tag = color(f"[{var.get('skill', '')}]", Colors.DIM)+ print(f" {var['key']:<20s} {display_val} {skill_tag}")+ except Exception:+ pass+++def show_config():+ """Display current configuration."""+ config = _cfg.load_config()++ print()+ print(color("┌─────────────────────────────────────────────────────────┐", Colors.CYAN))+ print(color("│ ☤ Hermes Configuration │", Colors.CYAN))+ print(color("└─────────────────────────────────────────────────────────┘", Colors.CYAN))+ _show_managed_banner()++ _section("Paths")+ print(f" Config: {_cfg.get_config_path()}")+ print(f" Secrets: {_cfg.get_env_path()}")+ print(f" Install: {_cfg.get_project_root()}")++ _section("API Keys")+ for env_key, name in _SHOW_CONFIG_API_KEYS:+ print(f" {name:<14} {_cfg.redact_key(_cfg.get_env_value(env_key))}")+ from hermes_cli.auth import get_anthropic_key+ print(f" {'Anthropic':<14} {_cfg.redact_key(get_anthropic_key())}")++ _show_model_section(config)+ _show_display_section(config)+ _show_terminal_section(config)++ _section("Timezone")+ tz = config.get('timezone', '')+ print(f" Timezone: {tz or color('(server-local)', Colors.DIM)}")++ _show_compression_section(config)+ _show_aux_overrides(config)++ _section("Messaging Platforms")+ for label, env_key in (("Telegram", "TELEGRAM_BOT_TOKEN"), ("Discord", "DISCORD_BOT_TOKEN")):+ state = 'configured' if _cfg.get_env_value(env_key) else color('not configured', Colors.DIM)+ print(f" {label + ':':<13} {state}")++ _show_skill_settings()++ print()+ print(color("─" * 60, Colors.DIM))+ print(color(" hermes config edit # Edit config file", Colors.DIM))+ print(color(" hermes config set <key> <value>", Colors.DIM))+ print(color(" hermes setup # Run setup wizard", Colors.DIM))+ print()diff --git a/hermes_cli/console_engine.py b/hermes_cli/console_engine.pyindex 44167431135..fc552484186 100644--- a/hermes_cli/console_engine.py+++ b/hermes_cli/console_engine.py@@ -562,7 +562,7 @@ def _status(_engine: HermesConsoleEngine, args: list[str]) -> str:_doctor = _simple_command("doctor", "hermes_cli.doctor", "run_doctor", lambda: (SimpleNamespace(fix=False, ack=None),))-_config_show = _simple_command("config show", "hermes_cli.config", "show_config")+_config_show = _simple_command("config show", "hermes_cli.config_show", "show_config")_cron_status = _simple_command("cron status", "hermes_cli.cron", "cron_status")diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex be05575378b..3805621a7ad 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -324,14 +324,6 @@ def _resolve_rate_limit_cooldown_seconds() -> int:return _env_int("HERMES_KANBAN_RATE_LIMIT_COOLDOWN_SECONDS", DEFAULT_RATE_LIMIT_COOLDOWN_SECONDS)-# build_worker_context() caps, sized for a ~100k-char prompt with headroom.-_CTX_MAX_PRIOR_ATTEMPTS = 10 # most recent N prior runs shown in full-_CTX_MAX_COMMENTS = 30 # most recent N comments shown in full-_CTX_MAX_FIELD_BYTES = 4 * 1024 # per summary/error/metadata/result-_CTX_MAX_BODY_BYTES = 8 * 1024 # per task.body (opening post)-_CTX_MAX_COMMENT_BYTES = 2 * 1024 # per comment--def _relative_age(ts: Optional[int], now: Optional[int] = None) -> str:"""``just now`` / ``18h ago`` / ``3d ago``; "" for a missing/invalid ts. An LLMreads a bare absolute timestamp as current fact — the relative age is what@@ -4071,6 +4063,10 @@ def build_worker_context(conn: sqlite3.Connection, task_id: str) -> str:task = get_task(conn, task_id)if not task:raise ValueError(f"unknown task {task_id}")+ from hermes_cli.kanban_db_context import (+ _ctx_attachments, _ctx_comments, _ctx_header, _ctx_parent_results, _ctx_prior_attempts,+ _ctx_role_history,+ )# One clock reading so every relative age in this rendering agrees.now = int(time.time())lines: list[str] = []@@ -4083,198 +4079,6 @@ def build_worker_context(conn: sqlite3.Connection, task_id: str) -> str:return "\n".join(lines).rstrip() + "\n"-def _ctx_cap(s: Optional[str], limit: int = _CTX_MAX_FIELD_BYTES) -> str:- """Truncate to ``limit`` chars with a visible ellipsis."""- if not s:- return ""- s = s.strip()- if len(s) <= limit:- return s- return s[:limit] + f"… [truncated, {len(s) - limit} chars omitted]"---def _ctx_stamp(ts: int, now: int) -> str:- """``YYYY-MM-DD HH:MM`` plus a relative age when one is available."""- disp = time.strftime("%Y-%m-%d %H:%M", time.localtime(ts))- age = _relative_age(ts, now)- return f"{disp}, {age}" if age else disp---def _ctx_metadata_line(metadata: Any) -> Optional[str]:- if not metadata:- return None- try:- return f"_metadata_: `{_ctx_cap(json.dumps(metadata, ensure_ascii=False, sort_keys=True))}`"- except Exception:- return None---def _ctx_tail(items: list, cap: int, noun: str) -> tuple[list, Optional[str]]:- """Keep the newest ``cap`` items; describe the omitted head, if any."""- omitted = max(0, len(items) - cap)- if not omitted:- return items, None- return items[-cap:], (- f"_({omitted} earlier {noun}{'s' if omitted != 1 else ''} "- f"omitted; showing most recent {cap})_"- )---def _ctx_header(lines: list[str], task: Task) -> None:- lines.append(f"# Kanban task {task.id}: {task.title}")- lines.append("")- lines.append(f"Assignee: {task.assignee or '(unassigned)'}")- lines.append(f"Status: {task.status}")- if task.tenant:- lines.append(f"Tenant: {task.tenant}")- lines.append(f"Workspace: {task.workspace_kind} @ {task.workspace_path or '(unresolved)'}")- if task.max_runtime_seconds is not None:- terminal_timeout = _worker_terminal_timeout_env(- task.max_runtime_seconds, os.environ.get("TERMINAL_TIMEOUT"),- )- effective_terminal_timeout = terminal_timeout or os.environ.get("TERMINAL_TIMEOUT")- lines.append(f"Max runtime: {task.max_runtime_seconds}s")- if effective_terminal_timeout:- lines.append(f"Terminal timeout: {effective_terminal_timeout}s")- if task.branch_name:- lines.append(f"Branch: {task.branch_name}")- lines.append("")- if task.body and task.body.strip():- lines.append("## Body")- lines.append(_ctx_cap(task.body, _CTX_MAX_BODY_BYTES))- lines.append("")---def _ctx_attachments(lines: list[str], attachments: list[Attachment]) -> None:- """Absolute on-disk paths so the worker's file tools read them directly- (remote terminal backends need the attachments dir mounted)."""- if not attachments:- return- lines.append("## Attachments")- lines.append(- "Files attached to this task. Read them with the file/terminal "- "tools at the absolute paths below:"- )- for att in attachments:- size_kb = max(1, (att.size + 1023) // 1024) if att.size else 0- size_str = f", {size_kb} KB" if size_kb else ""- ctype = f", {att.content_type}" if att.content_type else ""- lines.append(f"- `{att.filename}`{ctype}{size_str} → `{att.stored_path}`")- lines.append("")---def _ctx_prior_attempts(lines: list[str], conn: sqlite3.Connection, task_id: str, now: int) -> None:- """Closed runs on this task (the active run is this worker), newest- ``_CTX_MAX_PRIOR_ATTEMPTS`` in full, older ones as a one-line marker."""- all_prior = [r for r in list_runs(conn, task_id) if r.ended_at is not None]- shown, omitted_note = _ctx_tail(all_prior, _CTX_MAX_PRIOR_ATTEMPTS, "attempt")- if not shown:- return- first_shown_idx = len(all_prior) - len(shown) + 1- lines.append("## Prior attempts on this task")- if omitted_note:- lines.append(omitted_note)- for offset, run in enumerate(shown):- profile = run.profile or "(unknown)"- outcome = run.outcome or run.status- lines.append(- f"### Attempt {first_shown_idx + offset} — {outcome} ({profile}, {_ctx_stamp(run.started_at, now)})"- )- if run.summary and run.summary.strip():- lines.append(_ctx_cap(run.summary))- if run.error and run.error.strip():- lines.append(f"_error_: {_ctx_cap(run.error)}")- meta_line = _ctx_metadata_line(run.metadata)- if meta_line:- lines.append(meta_line)- lines.append("")---def _ctx_parent_results(lines: list[str], conn: sqlite3.Connection, task_id: str, now: int) -> None:- """Done-parent handoffs: newest ``completed`` run's summary+metadata,- falling back to ``task.result`` for pre-runs-table data. Stamped with a- relative age so the worker re-verifies stale upstream results."""- parent_rows = conn.execute(- "SELECT parent_id FROM task_links WHERE child_id = ? ORDER BY parent_id", (task_id,),- ).fetchall()- wrote_header = False- for pid in (r["parent_id"] for r in parent_rows):- pt = get_task(conn, pid)- if not pt or pt.status != "done":- continue- runs = [r for r in list_runs(conn, pid) if r.outcome == "completed"]- runs.sort(key=lambda r: r.started_at, reverse=True)- run = runs[0] if runs else None- if not wrote_header:- lines.append("## Parent task results")- lines.append(- "_Handoffs from upstream tasks, captured when each parent "- "completed (see age below). These are point-in-time "- "snapshots, not live state — if a result drives your "- "current work and it's not recent, re-verify against the "- "source before acting on it as current._"- )- wrote_header = True- done_ts = run.ended_at if run is not None and run.ended_at else (pt.completed_at or None)- age = _relative_age(done_ts, now)- lines.append(f"### {pid}" + (f" (completed {age})" if age else ""))- if run is not None and run.summary and run.summary.strip():- lines.append(_ctx_cap(run.summary))- elif pt.result:- lines.append(_ctx_cap(pt.result))- else:- lines.append("(no result recorded)")- meta_line = _ctx_metadata_line(run.metadata) if run is not None else None- if meta_line:- lines.append(meta_line)- lines.append("")---def _ctx_role_history(lines: list[str], conn: sqlite3.Connection, task: Task, now: int) -> None:- """The assignee's 5 most recent completed runs on OTHER tasks — implicit- role continuity without wiring anything into SOUL.md / MEMORY.md."""- if not task.assignee:- return- role_rows = conn.execute(- "SELECT t.id, t.title, r.summary, r.ended_at "- "FROM task_runs r JOIN tasks t ON r.task_id = t.id "- "WHERE r.profile = ? AND r.task_id != ? "- " AND r.outcome = 'completed' "- "ORDER BY r.ended_at DESC LIMIT 5", (task.assignee, task.id),- ).fetchall()- if not role_rows:- return- lines.append(f"## Recent work by @{task.assignee}")- for row in role_rows:- first = _first_line(row["summary"], 200) or "(no summary)"- lines.append(- f"- {row['id']} — {row['title']} ({_ctx_stamp(int(row['ended_at']), now)}): {first}"- )- lines.append("")---def _ctx_comments(lines: list[str], comments: list[Comment], now: int) -> None:- """Newest ``_CTX_MAX_COMMENTS`` comments. The explicit "comment from- worker" framing stops an operator-controlled HERMES_PROFILE like- "hermes-system" being read as a system directive above an- attacker-influenceable body (defense-in-depth)."""- shown, omitted_note = _ctx_tail(comments, _CTX_MAX_COMMENTS, "comment")- if not shown:- return- lines.append("## Comment thread")- if omitted_note:- lines.append(omitted_note)- for c in shown:- # Render author with explicit "comment from worker" framing so operator-controlled HERMES_PROFILE- # values like "hermes-system" or "operator" can't be misread by the next worker as a system- # directive above the (attacker-influenceable) comment body. Defense-in-depth — the LLM-controlled- # author-forgery surface was already closed in #22435. See #22452.- safe_author = (c.author or "").replace("`", "")- lines.append(f"comment from worker `{safe_author}` at {_ctx_stamp(c.created_at, now)}:")- lines.append(_ctx_cap(c.body, _CTX_MAX_COMMENT_BYTES))- lines.append("")--# --- Stats + SLA helpers ---def board_stats(conn: sqlite3.Connection) -> dict:diff --git a/hermes_cli/kanban_db_context.py b/hermes_cli/kanban_db_context.pynew file mode 100644index 00000000000..0c5fc99df7d--- /dev/null+++ b/hermes_cli/kanban_db_context.py@@ -0,0 +1,219 @@+"""Worker-context rendering for ``build_worker_context``: the capped markdown sections a spawned+worker reads about its task (header, attachments, prior attempts, parent handoffs, role+history, comments).++Split out of ``hermes_cli.kanban_db``; origin-resident helpers are reached late-bound via+``_kb`` so monkeypatching ``kanban_db.<name>`` keeps working.+"""++from __future__ import annotations++import json+import os+import sqlite3+import time+from typing import TYPE_CHECKING, Any, Optional++import hermes_cli.kanban_db as _kb++if TYPE_CHECKING:+ from hermes_cli.kanban_db import Attachment, Comment, Task++# build_worker_context() caps, sized for a ~100k-char prompt with headroom.+_CTX_MAX_PRIOR_ATTEMPTS = 10 # most recent N prior runs shown in full+_CTX_MAX_COMMENTS = 30 # most recent N comments shown in full+_CTX_MAX_FIELD_BYTES = 4 * 1024 # per summary/error/metadata/result+_CTX_MAX_BODY_BYTES = 8 * 1024 # per task.body (opening post)+_CTX_MAX_COMMENT_BYTES = 2 * 1024 # per comment+++def _ctx_cap(s: Optional[str], limit: int = _CTX_MAX_FIELD_BYTES) -> str:+ """Truncate to ``limit`` chars with a visible ellipsis."""+ if not s:+ return ""+ s = s.strip()+ if len(s) <= limit:+ return s+ return s[:limit] + f"… [truncated, {len(s) - limit} chars omitted]"+++def _ctx_stamp(ts: int, now: int) -> str:+ """``YYYY-MM-DD HH:MM`` plus a relative age when one is available."""+ disp = time.strftime("%Y-%m-%d %H:%M", time.localtime(ts))+ age = _kb._relative_age(ts, now)+ return f"{disp}, {age}" if age else disp+++def _ctx_metadata_line(metadata: Any) -> Optional[str]:+ if not metadata:+ return None+ try:+ return f"_metadata_: `{_ctx_cap(json.dumps(metadata, ensure_ascii=False, sort_keys=True))}`"+ except Exception:+ return None+++def _ctx_tail(items: list, cap: int, noun: str) -> tuple[list, Optional[str]]:+ """Keep the newest ``cap`` items; describe the omitted head, if any."""+ omitted = max(0, len(items) - cap)+ if not omitted:+ return items, None+ return items[-cap:], (+ f"_({omitted} earlier {noun}{'s' if omitted != 1 else ''} "+ f"omitted; showing most recent {cap})_"+ )+++def _ctx_header(lines: list[str], task: Task) -> None:+ lines.append(f"# Kanban task {task.id}: {task.title}")+ lines.append("")+ lines.append(f"Assignee: {task.assignee or '(unassigned)'}")+ lines.append(f"Status: {task.status}")+ if task.tenant:+ lines.append(f"Tenant: {task.tenant}")+ lines.append(f"Workspace: {task.workspace_kind} @ {task.workspace_path or '(unresolved)'}")+ if task.max_runtime_seconds is not None:+ terminal_timeout = _kb._worker_terminal_timeout_env(+ task.max_runtime_seconds, os.environ.get("TERMINAL_TIMEOUT"),+ )+ effective_terminal_timeout = terminal_timeout or os.environ.get("TERMINAL_TIMEOUT")+ lines.append(f"Max runtime: {task.max_runtime_seconds}s")+ if effective_terminal_timeout:+ lines.append(f"Terminal timeout: {effective_terminal_timeout}s")+ if task.branch_name:+ lines.append(f"Branch: {task.branch_name}")+ lines.append("")+ if task.body and task.body.strip():+ lines.append("## Body")+ lines.append(_ctx_cap(task.body, _CTX_MAX_BODY_BYTES))+ lines.append("")+++def _ctx_attachments(lines: list[str], attachments: list[Attachment]) -> None:+ """Absolute on-disk paths so the worker's file tools read them directly+ (remote terminal backends need the attachments dir mounted)."""+ if not attachments:+ return+ lines.append("## Attachments")+ lines.append(+ "Files attached to this task. Read them with the file/terminal "+ "tools at the absolute paths below:"+ )+ for att in attachments:+ size_kb = max(1, (att.size + 1023) // 1024) if att.size else 0+ size_str = f", {size_kb} KB" if size_kb else ""+ ctype = f", {att.content_type}" if att.content_type else ""+ lines.append(f"- `{att.filename}`{ctype}{size_str} → `{att.stored_path}`")+ lines.append("")+++def _ctx_prior_attempts(lines: list[str], conn: sqlite3.Connection, task_id: str, now: int) -> None:+ """Closed runs on this task (the active run is this worker), newest+ ``_CTX_MAX_PRIOR_ATTEMPTS`` in full, older ones as a one-line marker."""+ all_prior = [r for r in _kb.list_runs(conn, task_id) if r.ended_at is not None]+ shown, omitted_note = _ctx_tail(all_prior, _CTX_MAX_PRIOR_ATTEMPTS, "attempt")+ if not shown:+ return+ first_shown_idx = len(all_prior) - len(shown) + 1+ lines.append("## Prior attempts on this task")+ if omitted_note:+ lines.append(omitted_note)+ for offset, run in enumerate(shown):+ profile = run.profile or "(unknown)"+ outcome = run.outcome or run.status+ lines.append(+ f"### Attempt {first_shown_idx + offset} — {outcome} ({profile}, {_ctx_stamp(run.started_at, now)})"+ )+ if run.summary and run.summary.strip():+ lines.append(_ctx_cap(run.summary))+ if run.error and run.error.strip():+ lines.append(f"_error_: {_ctx_cap(run.error)}")+ meta_line = _ctx_metadata_line(run.metadata)+ if meta_line:+ lines.append(meta_line)+ lines.append("")+++def _ctx_parent_results(lines: list[str], conn: sqlite3.Connection, task_id: str, now: int) -> None:+ """Done-parent handoffs: newest ``completed`` run's summary+metadata,+ falling back to ``task.result`` for pre-runs-table data. Stamped with a+ relative age so the worker re-verifies stale upstream results."""+ parent_rows = conn.execute(+ "SELECT parent_id FROM task_links WHERE child_id = ? ORDER BY parent_id", (task_id,),+ ).fetchall()+ wrote_header = False+ for pid in (r["parent_id"] for r in parent_rows):+ pt = _kb.get_task(conn, pid)+ if not pt or pt.status != "done":+ continue+ runs = [r for r in _kb.list_runs(conn, pid) if r.outcome == "completed"]+ runs.sort(key=lambda r: r.started_at, reverse=True)+ run = runs[0] if runs else None+ if not wrote_header:+ lines.append("## Parent task results")+ lines.append(+ "_Handoffs from upstream tasks, captured when each parent "+ "completed (see age below). These are point-in-time "+ "snapshots, not live state — if a result drives your "+ "current work and it's not recent, re-verify against the "+ "source before acting on it as current._"+ )+ wrote_header = True+ done_ts = run.ended_at if run is not None and run.ended_at else (pt.completed_at or None)+ age = _kb._relative_age(done_ts, now)+ lines.append(f"### {pid}" + (f" (completed {age})" if age else ""))+ if run is not None and run.summary and run.summary.strip():+ lines.append(_ctx_cap(run.summary))+ elif pt.result:+ lines.append(_ctx_cap(pt.result))+ else:+ lines.append("(no result recorded)")+ meta_line = _ctx_metadata_line(run.metadata) if run is not None else None+ if meta_line:+ lines.append(meta_line)+ lines.append("")+++def _ctx_role_history(lines: list[str], conn: sqlite3.Connection, task: Task, now: int) -> None:+ """The assignee's 5 most recent completed runs on OTHER tasks — implicit+ role continuity without wiring anything into SOUL.md / MEMORY.md."""+ if not task.assignee:+ return+ role_rows = conn.execute(+ "SELECT t.id, t.title, r.summary, r.ended_at "+ "FROM task_runs r JOIN tasks t ON r.task_id = t.id "+ "WHERE r.profile = ? AND r.task_id != ? "+ " AND r.outcome = 'completed' "+ "ORDER BY r.ended_at DESC LIMIT 5", (task.assignee, task.id),+ ).fetchall()+ if not role_rows:+ return+ lines.append(f"## Recent work by @{task.assignee}")+ for row in role_rows:+ first = _kb._first_line(row["summary"], 200) or "(no summary)"+ lines.append(+ f"- {row['id']} — {row['title']} ({_ctx_stamp(int(row['ended_at']), now)}): {first}"+ )+ lines.append("")+++def _ctx_comments(lines: list[str], comments: list[Comment], now: int) -> None:+ """Newest ``_CTX_MAX_COMMENTS`` comments. The explicit "comment from+ worker" framing stops an operator-controlled HERMES_PROFILE like+ "hermes-system" being read as a system directive above an+ attacker-influenceable body (defense-in-depth)."""+ shown, omitted_note = _ctx_tail(comments, _CTX_MAX_COMMENTS, "comment")+ if not shown:+ return+ lines.append("## Comment thread")+ if omitted_note:+ lines.append(omitted_note)+ for c in shown:+ # Render author with explicit "comment from worker" framing so operator-controlled HERMES_PROFILE+ # values like "hermes-system" or "operator" can't be misread by the next worker as a system+ # directive above the (attacker-influenceable) comment body. Defense-in-depth — the LLM-controlled+ # author-forgery surface was already closed in #22435. See #22452.+ safe_author = (c.author or "").replace("`", "")+ lines.append(f"comment from worker `{safe_author}` at {_ctx_stamp(c.created_at, now)}:")+ lines.append(_ctx_cap(c.body, _CTX_MAX_COMMENT_BYTES))+ lines.append("")diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex d0ce2470db9..50b59f51789 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -1693,36 +1693,6 @@ def _first_run_setup_guard(args) -> None:sys.exit(1)-def _read_query_file(args) -> None:- """--query-file: read the single query from a file (or stdin via '-').-- Callers never have to shell-quote message bodies — this is the transport- the Bot Mode DM protocol uses; interpolating arbitrary text into a- double-quoted shell argument truncates on quotes and executes $(...)- (see tools/bot_mode_probe.py).- """- _qfile = getattr(args, "query_file", None)- if not _qfile:- return- if args.query:- # argparse's mutually-exclusive group catches the normal CLI path;- # this guards programmatic callers that fill the namespace directly.- print("Error: -q/--query and --query-file are mutually exclusive", file=sys.stderr)- sys.exit(2)- try:- if _qfile == "-":- args.query = sys.stdin.read()- else:- with open(_qfile, "r", encoding="utf-8-sig", errors="replace") as _fh:- args.query = _fh.read()- except OSError as _e:- print(f"Error: cannot read --query-file {_qfile}: {_e}", file=sys.stderr)- sys.exit(2)- if not (args.query or "").strip():- print(f"Error: --query-file {_qfile} is empty", file=sys.stderr)- sys.exit(2)--# args attr -> (kwarg, default) passed through to _launch_tui / cli.main._CHAT_PASSTHROUGH = (("provider", None), ("toolsets", None), ("skills", None), ("verbose", None),@@ -1794,6 +1764,7 @@ def cmd_chat(args):**passthrough,)+ from hermes_cli.main_query_file import _read_query_file_read_query_file(args)safe_mode = getattr(args, "safe_mode", False)diff --git a/hermes_cli/main_query_file.py b/hermes_cli/main_query_file.pynew file mode 100644index 00000000000..a85b25afe59--- /dev/null+++ b/hermes_cli/main_query_file.py@@ -0,0 +1,36 @@+"""``--query-file``: the single-query transport that never passes through a shell.++Split out of ``hermes_cli/main.py``.+"""++import sys+++def _read_query_file(args) -> None:+ """--query-file: read the single query from a file (or stdin via '-').++ Callers never have to shell-quote message bodies — this is the transport+ the Bot Mode DM protocol uses; interpolating arbitrary text into a+ double-quoted shell argument truncates on quotes and executes $(...)+ (see tools/bot_mode_probe.py).+ """+ _qfile = getattr(args, "query_file", None)+ if not _qfile:+ return+ if args.query:+ # argparse's mutually-exclusive group catches the normal CLI path;+ # this guards programmatic callers that fill the namespace directly.+ print("Error: -q/--query and --query-file are mutually exclusive", file=sys.stderr)+ sys.exit(2)+ try:+ if _qfile == "-":+ args.query = sys.stdin.read()+ else:+ with open(_qfile, "r", encoding="utf-8-sig", errors="replace") as _fh:+ args.query = _fh.read()+ except OSError as _e:+ print(f"Error: cannot read --query-file {_qfile}: {_e}", file=sys.stderr)+ sys.exit(2)+ if not (args.query or "").strip():+ print(f"Error: --query-file {_qfile} is empty", file=sys.stderr)+ sys.exit(2)diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 84c220ea10f..13171e7cf7f 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -11,9 +11,7 @@ and an ``__init__.py`` exposing ``register(ctx)``. Plugins register callbacks fofrom __future__ import annotationsimport asyncio-import contextvarsimport importlib.metadata-import inspectimport jsonimport loggingimport os@@ -57,7 +55,7 @@ from hermes_cli.plugins_dispatch import ( # noqa: F401 — re-exported_HOOK_CALLBACK_TIMEOUT_SECS, _HOOK_TIMEOUT_SUPPRESSION_SECONDS, _MAX_HOOK_CALLBACK_TIMEOUT_SECS,_PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE, PluginDispatchMixin, PluginSystemPromptSection,RenderedPluginSystemPromptSection, _EventSubscription, format_system_prompt_sections,- is_valid_system_prompt_section_id,+ is_valid_system_prompt_section_id, resolve_plugin_command_result,)from hermes_cli.plugins_ledger import PluginLedgerMixin, PluginRegistrationfrom hermes_cli.plugins_state import (@@ -2198,43 +2196,6 @@ def get_plugin_command_handler(name: str) -> Optional[Callable]:return entry["handler"] if entry else None-_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS = 30.0---def resolve_plugin_command_result(result: Any) -> Any:- """Resolve a plugin command result, awaiting async handlers: ``asyncio.run`` when no loop is- running, else a helper thread with its own loop (30s bound so a hung handler cannot wedge the- terminal)."""- if not inspect.isawaitable(result):- return result- try:- asyncio.get_running_loop()- except RuntimeError:- return asyncio.run(result)- outcome: Dict[str, Any] = {}- failure: Dict[str, BaseException] = {}- done = threading.Event()-- def _runner() -> None:- try:- outcome["value"] = asyncio.run(result)- except BaseException as exc: # pragma: no cover - re-raised below- failure["exc"] = exc- finally:- done.set()-- # copy_context: the helper thread must see the caller's profile/secret scope, else an- # async hook under a running loop reads the default HERMES_HOME and get_secret raises.- threading.Thread(target=contextvars.copy_context().run, args=(_runner,),- name="hermes-plugin-command-await", daemon=True).start()- if not done.wait(timeout=_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS):- raise TimeoutError("Plugin command async handler did not complete within "- f"{_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS:.0f}s")- if "exc" in failure:- raise failure["exc"]- return outcome.get("value")--def get_plugin_commands() -> Dict[str, dict]:"""Plugin commands dict (name -> {handler, description, plugin}) after idempotent discovery."""return _ensure_plugins_discovered()._plugin_commandsdiff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.pyindex c98219890d7..41d4dbd00ce 100644--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@ -180,6 +180,43 @@ def _hook_uses_callback_timeout(hook_name: str, timeout: float) -> bool:return hook_name in _HOOK_TIMEOUT_BOUNDED_HOOKS or hook_name in _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS+_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS = 30.0+++def resolve_plugin_command_result(result: Any) -> Any:+ """Resolve a plugin command result, awaiting async handlers: ``asyncio.run`` when no loop is+ running, else a helper thread with its own loop (30s bound so a hung handler cannot wedge the+ terminal)."""+ if not inspect.isawaitable(result):+ return result+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return asyncio.run(result)+ outcome: Dict[str, Any] = {}+ failure: Dict[str, BaseException] = {}+ done = threading.Event()++ def _runner() -> None:+ try:+ outcome["value"] = asyncio.run(result)+ except BaseException as exc: # pragma: no cover - re-raised below+ failure["exc"] = exc+ finally:+ done.set()++ # copy_context: the helper thread must see the caller's profile/secret scope, else an+ # async hook under a running loop reads the default HERMES_HOME and get_secret raises.+ threading.Thread(target=contextvars.copy_context().run, args=(_runner,),+ name="hermes-plugin-command-await", daemon=True).start()+ if not done.wait(timeout=_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS):+ raise TimeoutError("Plugin command async handler did not complete within "+ f"{_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS:.0f}s")+ if "exc" in failure:+ raise failure["exc"]+ return outcome.get("value")++class PluginDispatchMixin:@staticmethoddef _hook_callback_kwargs(callback: Callable, payload: Dict[str, Any]) -> Dict[str, Any]:@@ -205,7 +242,6 @@ class PluginDispatchMixin:are (loop-safe), otherwise the bare coroutine object is appended to the results and theplugin's body never runs (#12449)."""- from hermes_cli.plugins import resolve_plugin_command_resultreturn resolve_plugin_command_result(callback(**cls._hook_callback_kwargs(callback, payload)))def invoke_hook(self, hook_name: str, **kwargs: Any) -> List[Any]:@@ -419,7 +455,6 @@ class PluginDispatchMixin:def _deliver_event(self, item: _QueuedPluginEvent) -> None:"""Deliver one queued event on the host-owned worker thread."""- from hermes_cli.plugins import resolve_plugin_command_resultwith self._event_lock:if item.generation != self._event_generation:returndiff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex 37f7c961710..d0448178043 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -2411,54 +2411,6 @@ def import_profile(archive_path: str, name: Optional[str] = None) -> Path:# Rename-def _atomic_write_json(path: Path, data: dict) -> bool:- """Atomic rewrite of a third-party JSON config; False on OSError (nothing partially written)."""- from utils import atomic_json_write- try:- atomic_json_write(path, data)- return True- except OSError:- return False---def _migrate_honcho_profile_host(old_name: str, new_name: str, new_dir: Path) -> None:- """Rename Honcho host blocks for a renamed profile without changing peers."""- old_host = f"hermes_{old_name}"- legacy_old_host = f"hermes.{old_name}"- new_host = f"hermes_{new_name}"- candidates = [- new_dir / "honcho.json", _get_default_hermes_home() / "honcho.json", Path.home() / ".honcho" / "config.json"- ]- seen: set[Path] = set()- for path in candidates:- try:- resolved = path.resolve()- except OSError:- resolved = path- if resolved in seen or not path.is_file():- continue- seen.add(resolved)- try:- raw = json.loads(path.read_text(encoding="utf-8-sig"))- except (OSError, json.JSONDecodeError):- continue- hosts = raw.get("hosts")- if not isinstance(hosts, dict):- continue- source_host = old_host if old_host in hosts else legacy_old_host- if source_host not in hosts:- continue- if new_host in hosts:- print(f"⚠ Honcho host block not migrated: {new_host} already exists in {path}")- continue- block = hosts[source_host]- if isinstance(block, dict) and "aiPeer" not in block:- block["aiPeer"] = old_name # source_host is ``hermes_<old>`` or legacy ``hermes.<old>``- hosts[new_host] = hosts.pop(source_host)- if _atomic_write_json(path, raw):- print(f"✓ Honcho host updated: {source_host} → {new_host}")--def _record_profile_rename(new_dir: Path, old_canon: str) -> None:"""Append ``old_canon`` to the renamed profile's ``previous_names`` history.Best-effort: never raises, so a metadata write failure cannot fail the rename.@@ -2548,7 +2500,8 @@ def rename_profile(old_name: str, new_name: str) -> Path:_record_profile_rename(new_dir, old_canon)# 3. Update profile-scoped Honcho host blocks, preserving aiPeer identity- _migrate_honcho_profile_host(old_canon, new_canon, new_dir)+ from hermes_cli.profiles_honcho import migrate_honcho_profile_host+ migrate_honcho_profile_host(old_canon, new_canon, new_dir)# 4. Update wrapper scriptremove_wrapper_script(old_canon)diff --git a/hermes_cli/profiles_honcho.py b/hermes_cli/profiles_honcho.pynew file mode 100644index 00000000000..788e270fbf3--- /dev/null+++ b/hermes_cli/profiles_honcho.py@@ -0,0 +1,58 @@+"""Honcho host-block migration for ``hermes profile rename``.++Split out of ``hermes_cli.profiles``; the profiles root is late-imported from there so its+``_get_default_hermes_home`` seam holds.+"""++import json+from pathlib import Path+++def _atomic_write_json(path: Path, data: dict) -> bool:+ """Atomic rewrite of a third-party JSON config; False on OSError (nothing partially written)."""+ from utils import atomic_json_write+ try:+ atomic_json_write(path, data)+ return True+ except OSError:+ return False+++def migrate_honcho_profile_host(old_name: str, new_name: str, new_dir: Path) -> None:+ """Rename Honcho host blocks for a renamed profile without changing peers."""+ from hermes_cli.profiles import _get_default_hermes_home++ old_host = f"hermes_{old_name}"+ legacy_old_host = f"hermes.{old_name}"+ new_host = f"hermes_{new_name}"+ candidates = [+ new_dir / "honcho.json", _get_default_hermes_home() / "honcho.json", Path.home() / ".honcho" / "config.json"+ ]+ seen: set[Path] = set()+ for path in candidates:+ try:+ resolved = path.resolve()+ except OSError:+ resolved = path+ if resolved in seen or not path.is_file():+ continue+ seen.add(resolved)+ try:+ raw = json.loads(path.read_text(encoding="utf-8-sig"))+ except (OSError, json.JSONDecodeError):+ continue+ hosts = raw.get("hosts")+ if not isinstance(hosts, dict):+ continue+ source_host = old_host if old_host in hosts else legacy_old_host+ if source_host not in hosts:+ continue+ if new_host in hosts:+ print(f"⚠ Honcho host block not migrated: {new_host} already exists in {path}")+ continue+ block = hosts[source_host]+ if isinstance(block, dict) and "aiPeer" not in block:+ block["aiPeer"] = old_name # source_host is ``hermes_<old>`` or legacy ``hermes.<old>``+ hosts[new_host] = hosts.pop(source_host)+ if _atomic_write_json(path, raw):+ print(f"✓ Honcho host updated: {source_host} → {new_host}")diff --git a/hermes_cli/update_cmd_config.py b/hermes_cli/update_cmd_config.pyindex 554165d9f1f..27ced4041f4 100644--- a/hermes_cli/update_cmd_config.py+++ b/hermes_cli/update_cmd_config.py@@ -103,7 +103,7 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None:# 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+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_if_degradedprompt_restore = restore_cron_prompt_fields_if_degraded(pre_update_snapshot_id)if prompt_restore:print()@@ -120,7 +120,7 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None: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+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_all_profilesfor _prompt_restored in restore_cron_prompt_fields_all_profiles(_LAST_SIBLING_SNAPSHOTS):print()print(f" ⚠️ Profile '{_prompt_restored['profile']}': {_prompt_line(_prompt_restored)}")diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex 90d4368c29c..1ab38e776de 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -2172,7 +2172,7 @@ class TestRestoreCronPromptFieldsIfDegraded: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+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_if_degradedhermes_home = tmp_path / ".hermes"jobs_path = hermes_home / "cron" / "jobs.json"self._seed_jobs(jobs_path, [@@ -2204,7 +2204,7 @@ class TestRestoreCronPromptFieldsIfDegraded: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+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_if_degradedhermes_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."}])@@ -2220,7 +2220,7 @@ class TestRestoreCronPromptFieldsIfDegraded: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+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_if_degradedhermes_home = tmp_path / ".hermes"jobs_path = hermes_home / "cron" / "jobs.json"self._seed_jobs(jobs_path, [@@ -2246,7 +2246,7 @@ class TestRestoreCronPromptFieldsIfDegraded:def test_a_legitimate_user_edit_is_not_stomped(self, tmp_path):"""Only prompt==name or blank restores — a genuinely different promptis the user's edit during the window, not degradation."""- from hermes_cli.backup import restore_cron_prompt_fields_if_degraded+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_if_degradedhermes_home = tmp_path / ".hermes"jobs_path = hermes_home / "cron" / "jobs.json"self._seed_jobs(jobs_path, [{"id": "a", "name": "Old", "prompt": "Old prompt text."}])@@ -2262,7 +2262,7 @@ class TestRestoreCronPromptFieldsIfDegraded:def test_a_legit_prompt_equal_to_name_stays(self, tmp_path):"""A user may legitimately set prompt == name; a blank SNAPSHOT promptmeans the snapshot has nothing better — restore nothing."""- from hermes_cli.backup import restore_cron_prompt_fields_if_degraded+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_if_degradedhermes_home = tmp_path / ".hermes"jobs_path = hermes_home / "cron" / "jobs.json"# Snapshot job had a blank prompt (hand-edited oddity).@@ -2278,7 +2278,7 @@ class TestRestoreCronPromptFieldsIfDegraded: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+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_if_degradedhermes_home = tmp_path / ".hermes"jobs_path = hermes_home / "cron" / "jobs.json"self._seed_jobs(jobs_path, [{"id": "a", "name": "A", "prompt": "A prompt."}])@@ -2294,7 +2294,7 @@ class TestRestoreCronPromptFieldsIfDegraded:assert result is Nonedef test_healthy_file_is_untouched(self, tmp_path):- from hermes_cli.backup import restore_cron_prompt_fields_if_degraded+ from hermes_cli.backup_cron_prompts import restore_cron_prompt_fields_if_degradedhermes_home = tmp_path / ".hermes"jobs_path = hermes_home / "cron" / "jobs.json"self._seed_jobs(jobs_path, [{"id": "a", "name": "A", "prompt": "A prompt."}])diff --git a/tests/hermes_cli/test_managed_scope_surfacing.py b/tests/hermes_cli/test_managed_scope_surfacing.pyindex 30f0729e771..5a74569d444 100644--- a/tests/hermes_cli/test_managed_scope_surfacing.py+++ b/tests/hermes_cli/test_managed_scope_surfacing.py@@ -39,7 +39,7 @@ def test_config_show_no_managed_scope_silent(tmp_path, monkeypatch, capsys):cfg._LOAD_CONFIG_CACHE.clear()cfg._RAW_CONFIG_CACHE.clear()managed_scope.invalidate_managed_cache()- from hermes_cli.config import show_config+ from hermes_cli.config_show import show_configshow_config()out = capsys.readouterr().out.lower()diff --git a/tests/hermes_cli/test_plugins.py b/tests/hermes_cli/test_plugins.pyindex 3fe75a3b2af..3f1eb2e5f26 100644--- a/tests/hermes_cli/test_plugins.py+++ b/tests/hermes_cli/test_plugins.py@@ -2576,7 +2576,7 @@ class TestPluginCommandResultResolution:async def _handler():return "threaded-ok"- monkeypatch.setattr("hermes_cli.plugins.asyncio.get_running_loop", lambda: _Loop())+ monkeypatch.setattr("hermes_cli.plugins_dispatch.asyncio.get_running_loop", lambda: _Loop())assert resolve_plugin_command_result(_handler()) == "threaded-ok"def test_running_loop_timeout_does_not_hang_forever(self, monkeypatch):@@ -2590,8 +2590,8 @@ class TestPluginCommandResultResolution:await _asyncio.sleep(10)return "should-not-reach"- monkeypatch.setattr("hermes_cli.plugins.asyncio.get_running_loop", lambda: _Loop())- monkeypatch.setattr("hermes_cli.plugins._PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS", 0.1)+ monkeypatch.setattr("hermes_cli.plugins_dispatch.asyncio.get_running_loop", lambda: _Loop())+ monkeypatch.setattr("hermes_cli.plugins_dispatch._PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS", 0.1)with pytest.raises(TimeoutError):resolve_plugin_command_result(_slow_handler())