The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): scope the skills index + active-profile line to the agent's OWN home
Teknium2f25dec3494d
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 96f3eb47868..bfdd6618abf 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -13,7 +13,13 @@ import contextvarsfrom collections import OrderedDictfrom pathlib import Path-from hermes_constants import get_hermes_home, get_skills_dir, is_wsl+from hermes_constants import (+ get_hermes_home,+ get_skills_dir,+ is_wsl,+ reset_hermes_home_override,+ set_hermes_home_override,+)from typing import List, Optionalfrom agent.runtime_cwd import resolve_agent_cwd@@ -1718,6 +1724,7 @@ def build_skills_system_prompt(available_tools: "set[str] | None" = None,available_toolsets: "set[str] | None" = None,compact_categories: "frozenset[str] | None" = None,+ skills_dir_override: "Path | None" = None,) -> str:"""Build a compact skill index for the system prompt.@@ -1739,13 +1746,44 @@ def build_skills_system_prompt(visible and loadable via ``skill_view`` / ``skills_list``; only thedescriptions are dropped, and a footer note explains the demotion."""- skills_dir = get_skills_dir()- external_dirs = get_all_skills_dirs()[1:] # skip local (index 0)+ # Home resolution is EXPLICIT when a caller passes skills_dir_override+ # (the agent knows its own profile home from its session_db path). This+ # avoids the ContextVar-on-a-thread trap: build threads that didn't bind+ # HERMES_HOME would otherwise fall back to the launch (default) home and+ # leak the default profile's skills into a bot's prompt (confirmed: a+ # no-override thread builds default's full index). Snapshot + external+ # dirs are scoped to the same home so nothing reads ambient state.+ if skills_dir_override is not None:+ skills_dir = Path(skills_dir_override)+ _home_token = set_hermes_home_override(str(skills_dir.parent))+ else:+ skills_dir = get_skills_dir()+ _home_token = None+ try:+ external_dirs = get_all_skills_dirs()[1:] # skip local (index 0)++ if not skills_dir.exists() and not external_dirs:+ return ""++ return _build_skills_system_prompt_inner(+ skills_dir,+ external_dirs,+ available_tools,+ available_toolsets,+ compact_categories,+ )+ finally:+ if _home_token is not None:+ reset_hermes_home_override(_home_token)- if not skills_dir.exists() and not external_dirs:- return ""- # ── Layer 1: in-process LRU cache ─────────────────────────────────+def _build_skills_system_prompt_inner(+ skills_dir: "Path",+ external_dirs: "list[Path]",+ available_tools: "set[str] | None",+ available_toolsets: "set[str] | None",+ compact_categories: "frozenset[str] | None",+) -> str:# Include the resolved platform so per-platform disabled-skill lists# produce distinct cache entries (gateway serves multiple platforms)._platform_hint = _current_session_platform_hint()diff --git a/agent/system_prompt.py b/agent/system_prompt.pyindex c15989e16e7..e3263903f1f 100644--- a/agent/system_prompt.py+++ b/agent/system_prompt.py@@ -51,6 +51,7 @@ from agent.prompt_builder import ()from agent.runtime_cwd import resolve_context_cwdfrom hermes_constants import get_hermes_home+from pathlib import Pathfrom utils import is_truthy_valuelogger = logging.getLogger(__name__)@@ -262,6 +263,32 @@ def _plugin_section_blocks(sections: tuple, position: str) -> List[str]:return [block] if block else []+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.+ """+ try:+ db = getattr(agent, "_session_db", None)+ db_path = getattr(db, "db_path", None)+ if db_path:+ return Path(db_path).parent+ except Exception:+ pass+ return None+++def _agent_skills_dir(agent: Any) -> Optional[Path]:+ """The agent's own ``<home>/skills`` dir, or None to use ambient home."""+ home = _agent_home(agent)+ return (home / "skills") if home is not None else None++def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) -> Dict[str, str]:"""Assemble the system prompt as three ordered cache tiers.@@ -435,6 +462,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)available_tools=agent.valid_tool_names,available_toolsets=avail_toolsets,compact_categories=_compact_cats or None,+ skills_dir_override=_agent_skills_dir(agent),)else:skills_prompt = ""@@ -514,15 +542,35 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)# mid-session, so this doesn't break the prompt cache.# See file_safety._resolve_active_profile_name + classify_cross_profile_target# for the matching tool-side guard.+ #+ # Resolve from the agent's OWN home first (its session_db path), not the+ # ambient HERMES_HOME: on a build thread that lost the ContextVar this+ # line would otherwise print "default" for a bot profile — the same+ # thread-fallback bug that leaked default's skills index.+ _agent_home_path = _agent_home(agent)+ active_profile = "default"try:- from agent.file_safety import _resolve_active_profile_name- active_profile = _resolve_active_profile_name()+ if _agent_home_path is not None:+ root = get_hermes_home()+ try:+ rel = _agent_home_path.resolve().relative_to((root / "profiles").resolve())+ active_profile = rel.parts[0] if rel.parts else "default"+ except (ValueError, OSError):+ # Home IS the launch root (default) or unrelatable → default.+ active_profile = "default"+ else:+ from agent.file_safety import _resolve_active_profile_name+ active_profile = _resolve_active_profile_name()except Exception:active_profile = "default"+ # Home string for the message text: prefer the agent's own home so the+ # paths named match the profile just resolved.+ _home_str = str(_agent_home_path if _agent_home_path is not None else get_hermes_home())+ _root_str = str(get_hermes_home())if active_profile == "default":post_workspace_parts.append("Active Hermes profile: default. Other profiles (if any) live "- "under " + str(get_hermes_home()) + "/profiles/<name>/. Each profile has its own "+ "under " + _root_str + "/profiles/<name>/. Each profile has its own ""skills/, plugins/, cron/, and memories/ that affect a different ""session than this one. Do not modify another profile's ""skills/plugins/cron/memories unless the user explicitly directs "@@ -531,9 +579,9 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)else:post_workspace_parts.append(f"Active Hermes profile: {active_profile}. This session reads "- f"and writes {get_hermes_home()}/profiles/{active_profile}/. The default "- f"profile's data lives at {get_hermes_home()}/skills/, {get_hermes_home()}/plugins/, "- f"{get_hermes_home()}/cron/, {get_hermes_home()}/memories/ — those belong to a "+ f"and writes {_home_str}/. The default "+ f"profile's data lives at {_root_str}/skills/, {_root_str}/plugins/, "+ f"{_root_str}/cron/, {_root_str}/memories/ — those belong to a "f"different session run from a different shell. Do NOT modify "f"another profile's skills/plugins/cron/memories unless the user "f"explicitly directs you to. The cross-profile write guard will "diff --git a/tests/agent/test_bot_profile_prompt_isolation.py b/tests/agent/test_bot_profile_prompt_isolation.pynew file mode 100644index 00000000000..bba70e2625b--- /dev/null+++ b/tests/agent/test_bot_profile_prompt_isolation.py@@ -0,0 +1,92 @@+"""Regression: a bot profile's system prompt must reflect ITS OWN skills/home,+never the launch (default) profile's — even when the agent build runs on a+thread that did not bind the HERMES_HOME ContextVar.++Root cause this guards (confirmed empirically): ContextVars do not propagate+into ``threading.Thread``. ``build_skills_system_prompt`` and the+active-profile line resolved the home via the ambient ``get_hermes_home()``,+so an unbound build thread fell back to ``~/.hermes`` (default) and leaked+default's full skills index + "Active Hermes profile: default" into a bot's+prompt, while the live ``skills_list()`` (re-bound per turn) correctly+showed the bot's real, empty set. The agent now resolves its own home from+its ``_session_db.db_path`` and passes it explicitly.+"""++import re+import threading++import pytest+++def _skills_body(prompt: str) -> str:+ m = re.search(r"<available_skills>(.*?)</available_skills>", prompt, re.DOTALL)+ return (m.group(1).strip() if m else "")+++def test_skills_prompt_scoped_to_override_not_ambient_home(tmp_path, monkeypatch):+ """An explicit skills_dir_override wins over ambient HERMES_HOME, on a+ bare thread with no override bound."""+ from agent import prompt_builder++ # A "default" home WITH skills (the thing that must NOT leak).+ default_home = tmp_path / "default"+ default_skills = default_home / "skills" / "general" / "leaky-skill"+ default_skills.mkdir(parents=True)+ (default_skills / "SKILL.md").write_text(+ "---\nname: leaky-skill\ndescription: should never appear in a bot prompt\n---\nbody\n",+ encoding="utf-8",+ )++ # An empty bot profile (no skills dir at all).+ bot_skills = tmp_path / "profiles" / "emptybot" / "skills"++ # Bind ambient home to default (mimics a build thread that lost the+ # bot's override and fell back to launch).+ monkeypatch.setenv("HERMES_HOME", str(default_home))+ prompt_builder.clear_skills_system_prompt_cache(clear_snapshot=False)++ result = {}++ def build():+ # No set_hermes_home_override on THIS thread — ambient resolves to+ # default. The override arg must still scope to the empty bot.+ result["bot"] = _skills_body(+ prompt_builder.build_skills_system_prompt(skills_dir_override=bot_skills)+ )++ t = threading.Thread(target=build)+ t.start()+ t.join()++ assert result["bot"] == "", (+ "empty bot profile leaked skills from the ambient (default) home: "+ + result["bot"][:200]+ )+++def test_agent_home_resolves_from_session_db_path(tmp_path):+ """The agent's own home is read from its session_db, independent of any+ ContextVar."""+ from agent import system_prompt++ bot_home = tmp_path / "profiles" / "mybot"+ bot_home.mkdir(parents=True)++ class _DB:+ db_path = bot_home / "state.db"++ class _Agent:+ _session_db = _DB()++ assert system_prompt._agent_home(_Agent()) == bot_home+ assert system_prompt._agent_skills_dir(_Agent()) == bot_home / "skills"+++def test_agent_home_none_without_session_db():+ from agent import system_prompt++ class _Agent:+ _session_db = None++ assert system_prompt._agent_home(_Agent()) is None+ assert system_prompt._agent_skills_dir(_Agent()) is None