The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): bound HERMES_HOME override wins over shared session-db home
Teknium518bc90e74e0
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex c3e194e1d3f..a9e11c7abb7 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -1483,7 +1483,12 @@ def drain_truncation_warnings() -> list:# Skills prompt cache# =========================================================================-_SKILLS_PROMPT_CACHE_MAX = 8+# Sized for multi-profile processes: since #86313 the cache key carries a+# per-profile skills_dir (one entry per profile × platform), so the old cap+# of 8 could thrash on a gateway multiplexing default + several bots (each+# miss = full os.walk manifest rebuild). ~32 costs low single-digit MB worst+# case.+_SKILLS_PROMPT_CACHE_MAX = 32_SKILLS_PROMPT_CACHE: OrderedDict[tuple, str] = OrderedDict()_SKILLS_PROMPT_CACHE_LOCK = threading.Lock()# v2: entries gained org provenance fields (org_id/org_author/rel_dir) for M2diff --git a/agent/system_prompt.py b/agent/system_prompt.pyindex fe4b83617a5..a61ff7668cc 100644--- a/agent/system_prompt.py+++ b/agent/system_prompt.py@@ -163,9 +163,16 @@ def _plugin_session_info(agent: Any) -> Dict[str, str]:except Exception:cwd = ""try:- from hermes_cli.profiles import get_active_profile_name+ # Prefer the agent's own home (override-aware, session_db fallback) —+ # ambient get_active_profile_name() misreports on threads that lost+ # the HERMES_HOME ContextVar (#86313 class; plugin half per @helix4u).+ _home = _agent_home(agent)+ if _home is not None:+ profile_name = _profile_name_for_home(_home)+ else:+ from hermes_cli.profiles import get_active_profile_name- profile_name = str(get_active_profile_name() or "default")+ profile_name = str(get_active_profile_name() or "default")except Exception:profile_name = "default"return {@@ -264,15 +271,33 @@ def _plugin_section_blocks(sections: tuple, position: str) -> List[str]:def _agent_home(agent: Any) -> Optional[Path]:- """The agent's OWN profile home, resolved from its dedicated session_db.-- The agent's ``_session_db.db_path`` is ``<home>/state.db`` — ground truth- for which profile this agent belongs to, independent of any HERMES_HOME- ContextVar (which a build thread can lose: ContextVars don't propagate- into ``threading.Thread``, so an unbound build falls back to the launch- home and leaks the default profile's skills/identity into a bot prompt).- Returns None when it can't be resolved so callers fall back to ambient.+ """The agent's OWN profile home.++ Resolution order:++ 1. A bound HERMES_HOME ContextVar override wins. Surfaces that multiplex+ several profiles over ONE shared session DB (the messaging gateway:+ ``gateway/run.py`` hands every agent the launch-home ``state.db`` and+ binds the profile home per turn via ``_profile_runtime_scope`` ++ ``copy_context``) would otherwise have the db-derived launch home+ STOMP the correctly-bound profile — inverting the leak this helper+ exists to fix (found by @kshitijk4poor's post-merge probe on #86313).+ 2. Fallback: the home containing the agent's ``_session_db.db_path``+ (``<home>/state.db``) — ground truth on threads that lost the+ ContextVar (ContextVars don't propagate into ``threading.Thread``),+ where the unbound build previously fell back to the launch home and+ leaked the default profile's skills/identity into a bot prompt.++ Returns None when neither resolves so callers fall back to ambient."""+ try:+ from hermes_constants import get_hermes_home_override++ override = get_hermes_home_override()+ if override:+ return Path(override)+ except Exception:+ passtry:db = getattr(agent, "_session_db", None)db_path = getattr(db, "db_path", None)diff --git a/tests/agent/test_profile_home_override_precedence.py b/tests/agent/test_profile_home_override_precedence.pynew file mode 100644index 00000000000..2fff959689d--- /dev/null+++ b/tests/agent/test_profile_home_override_precedence.py@@ -0,0 +1,176 @@+"""Regression: multiplex gateway profile scoping + full-prompt wiring.++Two scenarios for _agent_home's resolution order (#86313 post-merge findings):++1. MULTIPLEX INVERSION (@kshitijk4poor): the messaging gateway hands every+ agent the shared launch-home state.db but binds the profile home per turn+ via the HERMES_HOME ContextVar (copy_context into the worker). A bound+ override must WIN over the db-derived launch home, else the shared-db+ fallback stomps the correct profile deterministically.++2. BARE THREAD (the original #86313 fix): no override bound — the db-derived+ home must still win over ambient env resolution.++Plus the full-prompt wiring test (@helix4u): build_system_prompt_parts on a+bare thread with the bot's session DB must produce a prompt whose identity+(SOUL.md), skills block, and profile line ALL belong to the bot — reverting+any single call-site wire breaks this test.+"""++import re+import threading+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++from hermes_constants import reset_hermes_home_override, set_hermes_home_override+++class _DB:+ def __init__(self, home: Path):+ self.db_path = home / "state.db"+++def _agent_for(home: Path, **overrides):+ base = dict(+ load_soul_identity=True,+ skip_context_files=True,+ valid_tool_names=[],+ _task_completion_guidance=False,+ _tool_use_enforcement=False,+ _environment_probe=False,+ _kanban_worker_guidance="",+ _memory_store=None,+ _memory_manager=None,+ model="",+ provider="",+ platform="",+ pass_session_id=False,+ session_id="",+ _session_db=_DB(home),+ )+ base.update(overrides)+ return SimpleNamespace(**base)+++def test_bound_override_wins_over_shared_db_home(tmp_path, monkeypatch):+ """Multiplex lane: shared launch-home DB + per-turn ContextVar binding.+ The override must win, not the db-derived launch home."""+ from agent import system_prompt++ root = tmp_path / "root"+ root.mkdir()+ bot_home = root / "profiles" / "mybot"+ bot_home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(root))++ agent = _agent_for(root) # shared db lives at <root>/state.db+ token = set_hermes_home_override(str(bot_home))+ try:+ assert system_prompt._agent_home(agent) == bot_home+ assert (+ system_prompt._profile_name_for_home(system_prompt._agent_home(agent))+ == "mybot"+ )+ finally:+ reset_hermes_home_override(token)+++def test_db_home_wins_on_bare_thread_without_override(tmp_path, monkeypatch):+ """Original #86313 scenario: unbound thread, dedicated per-profile DB."""+ from agent import system_prompt++ root = tmp_path / "root"+ bot_home = root / "profiles" / "mybot"+ bot_home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(root))++ agent = _agent_for(bot_home)+ result = {}++ def resolve():+ result["home"] = system_prompt._agent_home(agent)++ t = threading.Thread(target=resolve)+ t.start()+ t.join()++ assert result["home"] == bot_home+++def test_full_prompt_scoped_to_bot_on_bare_thread(tmp_path, monkeypatch):+ """Wiring test: SOUL.md identity, skills block, and profile line must ALL+ come from the bot's home when building on an unbound thread with the+ bot's session DB — no mixed-profile prompt."""+ from agent import prompt_builder+ from agent.system_prompt import build_system_prompt++ default_home = tmp_path / "root"+ default_skills = default_home / "skills" / "general" / "leaky-skill"+ default_skills.mkdir(parents=True)+ (default_skills / "SKILL.md").write_text(+ "---\nname: leaky-skill\ndescription: default-only skill\n---\nbody\n",+ encoding="utf-8",+ )+ (default_home / "SOUL.md").write_text("DEFAULT SOUL", encoding="utf-8")++ bot_home = default_home / "profiles" / "mybot"+ bot_skills = bot_home / "skills" / "general" / "bot-skill"+ bot_skills.mkdir(parents=True)+ (bot_skills / "SKILL.md").write_text(+ "---\nname: bot-skill\ndescription: bot-only skill\n---\nbody\n",+ encoding="utf-8",+ )+ (bot_home / "SOUL.md").write_text("BOT SOUL", encoding="utf-8")++ # Ambient env resolves to the launch/default home; nothing binds the+ # ContextVar on the build thread.+ monkeypatch.setenv("HERMES_HOME", str(default_home))+ prompt_builder.clear_skills_system_prompt_cache(clear_snapshot=False)++ agent = _agent_for(bot_home, valid_tool_names=["skill_view"])+ result = {}++ def build():+ with (+ patch("run_agent.build_nous_subscription_prompt", return_value=""),+ patch("run_agent.build_environment_hints", return_value=""),+ ):+ result["prompt"] = build_system_prompt(agent)++ t = threading.Thread(target=build)+ t.start()+ t.join()+ prompt = result["prompt"]++ assert "BOT SOUL" in prompt+ assert "DEFAULT SOUL" not in prompt+ m = re.search(r"<available_skills>(.*?)</available_skills>", prompt, re.DOTALL)+ skills_block = m.group(1) if m else ""+ assert "bot-skill" in skills_block+ assert "leaky-skill" not in skills_block+ assert "Active Hermes profile: mybot" in prompt+ assert "Active Hermes profile: default" not in prompt+++def test_plugin_session_info_profile_from_agent_home(tmp_path, monkeypatch):+ """Plugin prompt metadata must carry the agent's own profile name, not the+ ambient one (@helix4u's plugin half)."""+ from agent import system_prompt++ root = tmp_path / "root"+ bot_home = root / "profiles" / "mybot"+ bot_home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(root))++ agent = _agent_for(bot_home)+ result = {}++ def resolve():+ result["info"] = system_prompt._plugin_session_info(agent)++ t = threading.Thread(target=resolve)+ t.start()+ t.join()++ assert result["info"]["profile_name"] == "mybot"