The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: legacy Bot Mode section in SOUL.md no longer taxes every session or shadows the live roster
Tekniumb167e81750de
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex afc79fcc220..2f360824984 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -1454,6 +1454,11 @@ def load_soul_md(context_length: Optional[int] = None, home_override: "Path | Noreturn Nonetry:content = (_read_text_with_timeout(soul_path) or "").strip()+ if content:+ # Plugin-era desktop builds appended a frozen Bot Mode roster to SOUL.md; the server+ # now injects the live section in Bot Chat only, so the copy is dead weight everywhere.+ from tools.bot_mode_probe import strip_legacy_protocol+ content = strip_legacy_protocol(content).strip()if not content:return Nonereturn _truncate_content(_scan_context_content(content, "SOUL.md"), "SOUL.md", context_length=context_length,diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 1b01342cb06..099d6fc647c 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2327,7 +2327,7 @@ DEFAULT_CONFIG = {# Extra ports detection probes for an external llama-server (besides 8080)."detect_ports": [],},- "_config_version": 40, # Config schema version - bump this when adding new required fields+ "_config_version": 41, # Config schema version - bump this when adding new required fields}diff --git a/hermes_cli/config_migrations.py b/hermes_cli/config_migrations.pyindex 46c27177bb2..d91983f95c1 100644--- a/hermes_cli/config_migrations.py+++ b/hermes_cli/config_migrations.py@@ -518,6 +518,30 @@ def _migrate_to_39(results: Dict[str, Any], quiet: bool) -> None:"Video Generation (Nous Subscription or FAL).")+def _migrate_to_41(results: Dict[str, Any], quiet: bool) -> None:+ # 40 → 41: drop the plugin-era "## Messaging other agents" append from every SOUL.md. The+ # server injects the live Bot Mode section in Bot Chat sessions; the frozen SOUL copy taxed+ # every other session (~600 tok) and shadowed the live roster in Bot Chat itself.+ from hermes_constants import get_hermes_home+ from tools.bot_mode_probe import _PROTOCOL_HEADING, _hermes_root, _roster, strip_legacy_protocol++ cleaned: List[str] = []+ for name, profile_dir in _roster(_hermes_root(get_hermes_home())):+ soul = profile_dir / "SOUL.md"+ try:+ text = soul.read_text(encoding="utf-8") if soul.is_file() else ""+ if _PROTOCOL_HEADING in text:+ soul.write_text(strip_legacy_protocol(text), encoding="utf-8")+ cleaned.append(name)+ except OSError:+ continue+ if cleaned:+ results["config_added"].append(f"removed legacy Bot Mode section from SOUL.md ({', '.join(cleaned)})")+ if not quiet:+ print(f" ✓ Removed the plugin-era 'Messaging other agents' section from SOUL.md "+ f"({', '.join(cleaned)}) — Bot Chat sessions now get the live roster instead.")++#: Registry of (target_version, step), strictly ascending; simple default-flip steps are#: declared inline via _rewrite_stale_default / _rewrite_key partials. Later steps observe#: earlier steps' writes via read_raw_config() (filesystem state). v12 is the support floor:@@ -602,6 +626,7 @@ MIGRATIONS: Tuple[Tuple[int, Callable[[Dict[str, Any], bool], None]], ...] = (added="model_catalog.ttl_hours 1 → ttl_minutes 20 (default)",message=" ✓ Model catalog now refreshes every 20 minutes (model_catalog.ttl_minutes)",extra_guard=lambda raw: "ttl_minutes" not in raw)),+ (41, _migrate_to_41),)diff --git a/tests/agent/test_soul_legacy_bot_protocol.py b/tests/agent/test_soul_legacy_bot_protocol.pynew file mode 100644index 00000000000..7a96ff07a75--- /dev/null+++ b/tests/agent/test_soul_legacy_bot_protocol.py@@ -0,0 +1,45 @@+"""The plugin-era "## Messaging other agents" SOUL append is dead weight: the server injects+the live section in Bot Chat only, so every copy in SOUL.md must vanish — at load time for+sessions that start before the migration runs, and on disk once the migration runs."""++from tools import bot_mode_probe++LEGACY = "# Me\n\nBe terse.\n\n## Messaging other agents\n\nold plugin text\n- `bot-a`\n"+++def test_load_soul_md_drops_legacy_protocol_section(tmp_path, monkeypatch):+ from agent import prompt_builder++ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ (home / "SOUL.md").write_text(LEGACY + "\n## Symbols\n\nuse ◆\n", encoding="utf-8")++ soul = prompt_builder.load_soul_md(home_override=home)++ assert "Messaging other agents" not in soul and "old plugin text" not in soul+ assert "Be terse." in soul and "use ◆" in soul # neighbouring sections survive+ # Bot Chat itself keeps the live section: SOUL no longer suppresses the probe.+ bot_mode_probe._reset_cache_for_tests()+ (home / "profiles" / "bot").mkdir(parents=True)+ (home / "profiles" / "bot" / "profile.yaml").write_text("ui_meta:\n hermes-bots: {}\n", encoding="utf-8")+ assert "`@bot`" in bot_mode_probe.get_bot_mode_protocol_section(home)+++def test_migration_41_strips_every_profile_soul_once(tmp_path, monkeypatch):+ from hermes_cli.config_migrations import _migrate_to_41++ home = tmp_path / ".hermes"+ (home / "profiles" / "worker").mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ (home / "SOUL.md").write_text(LEGACY, encoding="utf-8")+ (home / "profiles" / "worker" / "SOUL.md").write_text("# Worker\n\n## Messaging other agents\nx\n", encoding="utf-8")++ results = {"config_added": []}+ _migrate_to_41(results, quiet=True)++ assert (home / "SOUL.md").read_text(encoding="utf-8") == "# Me\n\nBe terse.\n"+ assert (home / "profiles" / "worker" / "SOUL.md").read_text(encoding="utf-8") == "# Worker\n"+ assert results["config_added"] and "default" in results["config_added"][0] and "worker" in results["config_added"][0]+ _migrate_to_41(results := {"config_added": []}, quiet=True)+ assert results["config_added"] == [] # idempotent: nothing left to stripdiff --git a/tests/tools/test_bot_mode_probe.py b/tests/tools/test_bot_mode_probe.pyindex 85f99a0867e..7d0a287cc27 100644--- a/tests/tools/test_bot_mode_probe.py+++ b/tests/tools/test_bot_mode_probe.py@@ -94,15 +94,16 @@ def test_roster_lines_carry_roles(tmp_path):assert "Deep research and literature review" in section-def test_silent_when_soul_already_carries_protocol(tmp_path):- """Legacy plugin-side append — never double the section."""+def test_soul_legacy_protocol_no_longer_suppresses_live_section(tmp_path):+ """Plugin-era SOUL append is stripped at load time; the live roster is the only copy."""home = tmp_path / ".hermes"home.mkdir()_make_bot_profile(home, "coder", managed=True)(home / "SOUL.md").write_text("# Me\n\n## Messaging other agents\nold plugin text\n", encoding="utf-8")- assert bot_mode_probe.get_bot_mode_protocol_section(home) == ""+ assert "`@coder`" in bot_mode_probe.get_bot_mode_protocol_section(home)+ assert bot_mode_probe.strip_legacy_protocol((home / "SOUL.md").read_text()) == "# Me\n"def test_deterministic_across_calls(tmp_path):@@ -211,14 +212,8 @@ def test_legacy_bot_chat_upgrade(tmp_path):upgraded = legacy + "\n\n" + bot_mode_probe.get_bot_mode_protocol_section(home) + "\n\n" + bot_mode_probe.epoch_line(home)assert not bot_mode_probe.stored_bot_chat_prompt_needs_upgrade(upgraded, home)- # SOUL already carries the legacy plugin-side append → probe silent →- # no upgrade (rebuilding would loop: the new prompt would be unstamped too)- bot_mode_probe._reset_cache_for_tests()- (home / "SOUL.md").write_text("# Me\n\n## Messaging other agents\nlegacy\n", encoding="utf-8")- assert not bot_mode_probe.stored_bot_chat_prompt_needs_upgrade(legacy, home)-- # prompt whose SOUL section rode into it → protocol heading present → no upgrade- assert not bot_mode_probe.stored_bot_chat_prompt_needs_upgrade(+ # SOUL-era prompt (frozen roster rode in from SOUL.md, no stamp) → upgrade once+ assert bot_mode_probe.stored_bot_chat_prompt_needs_upgrade("prompt containing\n## Messaging other agents\nfrom SOUL", home)diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.pyindex 5ec13225783..9172cce4455 100644--- a/tests/tools/test_bot_relay.py+++ b/tests/tools/test_bot_relay.py@@ -287,18 +287,12 @@ def _fresh_probe_cache():def test_tool_injects_despite_legacy_soul_protocol(tmp_path):- """The legacy-SOUL dedupe empties the SECTION, never the TOOL.-- Regression: upgraded installs whose SOUL.md still carries the old- plugin-appended protocol silently lost message_agent because the gate- keyed on section non-emptiness.- """+ """A SOUL.md still carrying the plugin-appended protocol must not cost the TOOL (nor,+ since load-time stripping, the live section)."""from tools import bot_mode_probehome = _managed_home(tmp_path, legacy_soul=True)- # Premise: the dedupe really does empty the section for this profile...- assert bot_mode_probe.get_bot_mode_protocol_section(home) == ""- # ...but the install is managed, so the tool must still inject.+ assert bot_mode_probe.get_bot_mode_protocol_section(home) != ""agent = _FakeAgent(home)assert ensure_message_agent_tool(agent) is Trueassert [t["function"]["name"] for t in agent.tools] == [MESSAGE_AGENT_TOOL_NAME]diff --git a/tools/bot_mode_probe.py b/tools/bot_mode_probe.pyindex 4b5dcd35b2e..cb71c4b5693 100644--- a/tools/bot_mode_probe.py+++ b/tools/bot_mode_probe.py@@ -3,8 +3,9 @@When any profile carries ``ui_meta['hermes-bots']`` in profile.yaml (Bot-Mode-managed),a bot's canonical "Bot Chat" session — ONLY that session (agent/system_prompt.py enforcesthe ``BOT_CHAT_TITLE`` gate) — gets a "Messaging other agents" section. Silent (``""``)-when no profile is managed, when SOUL.md already carries the heading (legacy plugin text-must never double up), or on any error. Cached per (process, home) so compression rebuilds+when no profile is managed or on any error. Older desktop builds appended a frozen copy of+the section to SOUL.md; ``strip_legacy_protocol`` drops it at load time so the live roster+here is the only copy any session sees. Cached per (process, home) so compression rebuildsproduce identical bytes. Toggle: ``agent.bot_mode_protocol``. Also hosts path/rosterhelpers shared by ``bot_mode_dm`` and ``bot_relay``."""@@ -12,10 +13,18 @@ helpers shared by ``bot_mode_dm`` and ``bot_relay``.from __future__ import annotationsimport os+import reimport threadingfrom pathlib import Path_PROTOCOL_HEADING = "## Messaging other agents"+# The legacy section through the next H2 heading (or EOF), plus the blank lines before it.+_LEGACY_PROTOCOL_RE = re.compile(r"\n*" + re.escape(_PROTOCOL_HEADING) + r"[ \t]*\n.*?(?=\n## |\Z)", re.S)+++def strip_legacy_protocol(text: str) -> str:+ """SOUL text without the plugin-era "## Messaging other agents" section (idempotent)."""+ return _LEGACY_PROTOCOL_RE.sub("\n", text).strip() + "\n" if _PROTOCOL_HEADING in text else text# The only session title that receives the protocol section. Must match the# desktop plugin's createCanonicalChat title and the `-c "Bot Chat"` resume target.@@ -105,11 +114,6 @@ def is_bot_mode_managed(home: str | os.PathLike | None = None) -> bool:return _swallow(lambda: _any_managed(_hermes_root(_resolve_home(home))), False)-def _soul_has_protocol(profile_dir: Path) -> bool:- soul = profile_dir / "SOUL.md"- return _swallow(lambda: soul.is_file() and _PROTOCOL_HEADING in soul.read_text(encoding="utf-8", errors="replace"), False)--def _role_line(*parts: str) -> str:"""'title — description' from the non-empty parts (either may be absent)."""return " — ".join(p for p in parts if p)@@ -191,9 +195,6 @@ def _build_section(home: Path) -> str:me = _profile_name(home)if not _any_managed(root):return ""- # An older plugin build may have appended the protocol to SOUL.md — never double it.- if _soul_has_protocol(home if me == "default" else root / "profiles" / me):- return ""roster_lines = [_bullet(f"@{_handle(name)}", _profile_role(d)) for name, d in _roster(root) if name != me]roster_block = "\n".join(roster_lines) or "- (no teammates yet)"@@ -333,13 +334,11 @@ def stored_prompt_capability_stale(stored_prompt: str, home: str | os.PathLike |def stored_bot_chat_prompt_needs_upgrade(stored_prompt: str, home: str | os.PathLike | None = None) -> bool:- """True when a Bot Chat session's stored prompt PREDATES the epoch mechanism. Legacy- prompts carry neither section nor stamp, so the staleness check (stamped only) would strand- them forever. The caller must only ask for sessions titled "Bot Chat"; we rebuild only when- the probe would actually emit a section — a SOUL.md carrying the legacy protocol yields an- empty section, and rebuilding would mint another unstamped prompt and loop. Fails closed."""- text = stored_prompt or ""- if _EPOCH_PREFIX in text or _PROTOCOL_HEADING in text:+ """True when a Bot Chat session's stored prompt PREDATES the epoch mechanism (no stamp —+ including SOUL-era prompts whose frozen roster rode in from SOUL.md). The caller must only+ ask for sessions titled "Bot Chat"; we rebuild only when the probe would actually emit a+ section, and every rebuilt prompt is stamped so this fires once. Fails closed."""+ if _EPOCH_PREFIX in (stored_prompt or ""):return Falsereturn _swallow(lambda: bool(get_bot_mode_protocol_section(home)), False)