Hermes-agent

This commit is contained in:
Zakaria
2026-06-14 14:30:48 -04:00
commit dac4b88b94
5058 changed files with 1884848 additions and 0 deletions
View File
+460
View File
@@ -0,0 +1,460 @@
"""Tests for the async-memory Honcho improvements.
Covers:
- write_frequency parsing (async / turn / session / int)
- resolve_session_name with session_title
- HonchoSessionManager.save() routing per write_frequency
- async writer thread lifecycle and retry
- flush_all() drains pending messages
- shutdown() joins the thread
"""
import json
import time
from unittest.mock import MagicMock, patch
from plugins.memory.honcho.client import HonchoClientConfig
from plugins.memory.honcho.session import (
HonchoSession,
HonchoSessionManager,
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_session(**kwargs) -> HonchoSession:
return HonchoSession(
key=kwargs.get("key", "cli:test"),
user_peer_id=kwargs.get("user_peer_id", "eri"),
assistant_peer_id=kwargs.get("assistant_peer_id", "hermes"),
honcho_session_id=kwargs.get("honcho_session_id", "cli-test"),
messages=kwargs.get("messages", []),
)
def _make_manager(write_frequency="turn") -> HonchoSessionManager:
cfg = HonchoClientConfig(
write_frequency=write_frequency,
api_key="test-key",
enabled=True,
)
mgr = HonchoSessionManager(config=cfg)
mgr._honcho = MagicMock()
return mgr
# ---------------------------------------------------------------------------
# write_frequency parsing from config file
# ---------------------------------------------------------------------------
class TestWriteFrequencyParsing:
def test_string_async(self, tmp_path):
cfg_file = tmp_path / "config.json"
cfg_file.write_text(json.dumps({"apiKey": "k", "writeFrequency": "async"}))
cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)
assert cfg.write_frequency == "async"
def test_string_turn(self, tmp_path):
cfg_file = tmp_path / "config.json"
cfg_file.write_text(json.dumps({"apiKey": "k", "writeFrequency": "turn"}))
cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)
assert cfg.write_frequency == "turn"
def test_string_session(self, tmp_path):
cfg_file = tmp_path / "config.json"
cfg_file.write_text(json.dumps({"apiKey": "k", "writeFrequency": "session"}))
cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)
assert cfg.write_frequency == "session"
def test_integer_frequency(self, tmp_path):
cfg_file = tmp_path / "config.json"
cfg_file.write_text(json.dumps({"apiKey": "k", "writeFrequency": 5}))
cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)
assert cfg.write_frequency == 5
def test_integer_string_coerced(self, tmp_path):
cfg_file = tmp_path / "config.json"
cfg_file.write_text(json.dumps({"apiKey": "k", "writeFrequency": "3"}))
cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)
assert cfg.write_frequency == 3
def test_host_block_overrides_root(self, tmp_path):
cfg_file = tmp_path / "config.json"
cfg_file.write_text(json.dumps({
"apiKey": "k",
"writeFrequency": "turn",
"hosts": {"hermes": {"writeFrequency": "session"}},
}))
cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)
assert cfg.write_frequency == "session"
def test_defaults_to_async(self, tmp_path):
cfg_file = tmp_path / "config.json"
cfg_file.write_text(json.dumps({"apiKey": "k"}))
cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)
assert cfg.write_frequency == "async"
# ---------------------------------------------------------------------------
# resolve_session_name with session_title
# ---------------------------------------------------------------------------
class TestResolveSessionNameTitle:
def test_manual_override_beats_title(self):
cfg = HonchoClientConfig(sessions={"/my/project": "manual-name"})
result = cfg.resolve_session_name("/my/project", session_title="the-title")
assert result == "manual-name"
def test_title_beats_dirname(self):
cfg = HonchoClientConfig()
result = cfg.resolve_session_name("/some/dir", session_title="my-project")
assert result == "my-project"
def test_title_with_peer_prefix(self):
cfg = HonchoClientConfig(peer_name="eri", session_peer_prefix=True)
result = cfg.resolve_session_name("/some/dir", session_title="aeris")
assert result == "eri-aeris"
def test_title_sanitized(self):
cfg = HonchoClientConfig()
result = cfg.resolve_session_name("/some/dir", session_title="my project/name!")
# trailing dashes stripped by .strip('-')
assert result == "my-project-name"
def test_title_all_invalid_chars_falls_back_to_dirname(self):
cfg = HonchoClientConfig()
result = cfg.resolve_session_name("/some/dir", session_title="!!! ###")
# sanitized to empty → falls back to dirname
assert result == "dir"
def test_none_title_falls_back_to_dirname(self):
cfg = HonchoClientConfig()
result = cfg.resolve_session_name("/some/dir", session_title=None)
assert result == "dir"
def test_empty_title_falls_back_to_dirname(self):
cfg = HonchoClientConfig()
result = cfg.resolve_session_name("/some/dir", session_title="")
assert result == "dir"
def test_per_session_uses_session_id(self):
cfg = HonchoClientConfig(session_strategy="per-session")
result = cfg.resolve_session_name("/some/dir", session_id="20260309_175514_9797dd")
assert result == "20260309_175514_9797dd"
def test_per_session_with_peer_prefix(self):
cfg = HonchoClientConfig(session_strategy="per-session", peer_name="eri", session_peer_prefix=True)
result = cfg.resolve_session_name("/some/dir", session_id="20260309_175514_9797dd")
assert result == "eri-20260309_175514_9797dd"
def test_per_session_no_id_falls_back_to_dirname(self):
cfg = HonchoClientConfig(session_strategy="per-session")
result = cfg.resolve_session_name("/some/dir", session_id=None)
assert result == "dir"
def test_title_beats_session_id(self):
cfg = HonchoClientConfig(session_strategy="per-session")
result = cfg.resolve_session_name("/some/dir", session_title="my-title", session_id="20260309_175514_9797dd")
assert result == "my-title"
def test_manual_beats_session_id(self):
cfg = HonchoClientConfig(session_strategy="per-session", sessions={"/some/dir": "pinned"})
result = cfg.resolve_session_name("/some/dir", session_id="20260309_175514_9797dd")
assert result == "pinned"
def test_global_strategy_returns_workspace(self):
cfg = HonchoClientConfig(session_strategy="global", workspace_id="my-workspace")
result = cfg.resolve_session_name("/some/dir")
assert result == "my-workspace"
# ---------------------------------------------------------------------------
# save() routing per write_frequency
# ---------------------------------------------------------------------------
class TestSaveRouting:
def _make_session_with_message(self, mgr=None):
sess = _make_session()
sess.add_message("user", "hello")
sess.add_message("assistant", "hi")
if mgr:
mgr._cache[sess.key] = sess
return sess
def test_turn_flushes_immediately(self):
mgr = _make_manager(write_frequency="turn")
sess = self._make_session_with_message(mgr)
with patch.object(mgr, "_flush_session") as mock_flush:
mgr.save(sess)
mock_flush.assert_called_once_with(sess)
def test_session_mode_does_not_flush(self):
mgr = _make_manager(write_frequency="session")
sess = self._make_session_with_message(mgr)
with patch.object(mgr, "_flush_session") as mock_flush:
mgr.save(sess)
mock_flush.assert_not_called()
def test_async_mode_enqueues(self):
mgr = _make_manager(write_frequency="async")
sess = self._make_session_with_message(mgr)
with patch.object(mgr, "_flush_session") as mock_flush:
mgr.save(sess)
# flush_session should NOT be called synchronously
mock_flush.assert_not_called()
assert not mgr._async_queue.empty()
def test_int_frequency_flushes_on_nth_turn(self):
mgr = _make_manager(write_frequency=3)
sess = self._make_session_with_message(mgr)
with patch.object(mgr, "_flush_session") as mock_flush:
mgr.save(sess) # turn 1
mgr.save(sess) # turn 2
assert mock_flush.call_count == 0
mgr.save(sess) # turn 3
assert mock_flush.call_count == 1
def test_int_frequency_skips_other_turns(self):
mgr = _make_manager(write_frequency=5)
sess = self._make_session_with_message(mgr)
with patch.object(mgr, "_flush_session") as mock_flush:
for _ in range(4):
mgr.save(sess)
assert mock_flush.call_count == 0
mgr.save(sess) # turn 5
assert mock_flush.call_count == 1
# ---------------------------------------------------------------------------
# flush_all()
# ---------------------------------------------------------------------------
class TestFlushAll:
def test_flushes_all_cached_sessions(self):
mgr = _make_manager(write_frequency="session")
s1 = _make_session(key="s1", honcho_session_id="s1")
s2 = _make_session(key="s2", honcho_session_id="s2")
s1.add_message("user", "a")
s2.add_message("user", "b")
mgr._cache = {"s1": s1, "s2": s2}
with patch.object(mgr, "_flush_session") as mock_flush:
mgr.flush_all()
assert mock_flush.call_count == 2
def test_flush_all_drains_async_queue(self):
mgr = _make_manager(write_frequency="async")
sess = _make_session()
sess.add_message("user", "pending")
with patch.object(mgr, "_flush_session") as mock_flush:
# Put the item AFTER the mock is installed so the background
# writer thread (if it dequeues before flush_all) still hits
# the mock rather than the real _flush_session.
mgr._async_queue.put(sess)
mgr.flush_all()
# Called at least once for the queued item
assert mock_flush.call_count >= 1
def test_flush_all_tolerates_errors(self):
mgr = _make_manager(write_frequency="session")
sess = _make_session()
mgr._cache = {"key": sess}
with patch.object(mgr, "_flush_session", side_effect=RuntimeError("oops")):
# Should not raise
mgr.flush_all()
# ---------------------------------------------------------------------------
# async writer thread lifecycle
# ---------------------------------------------------------------------------
class TestAsyncWriterThread:
def test_thread_started_on_async_mode(self):
mgr = _make_manager(write_frequency="async")
assert mgr._async_thread is not None
assert mgr._async_thread.is_alive()
mgr.shutdown()
def test_no_thread_for_turn_mode(self):
mgr = _make_manager(write_frequency="turn")
assert mgr._async_thread is None
assert mgr._async_queue is None
def test_shutdown_joins_thread(self):
mgr = _make_manager(write_frequency="async")
assert mgr._async_thread.is_alive()
mgr.shutdown()
assert not mgr._async_thread.is_alive()
def test_async_writer_calls_flush(self):
mgr = _make_manager(write_frequency="async")
sess = _make_session()
sess.add_message("user", "async msg")
flushed = []
def capture(s):
flushed.append(s)
return True
mgr._flush_session = capture
mgr._async_queue.put(sess)
# Give the daemon thread time to process
deadline = time.time() + 2.0
while not flushed and time.time() < deadline:
time.sleep(0.05)
mgr.shutdown()
assert len(flushed) == 1
assert flushed[0] is sess
def test_shutdown_sentinel_stops_loop(self):
mgr = _make_manager(write_frequency="async")
thread = mgr._async_thread
mgr.shutdown()
thread.join(timeout=3)
assert not thread.is_alive()
# ---------------------------------------------------------------------------
# async retry on failure
# ---------------------------------------------------------------------------
class TestAsyncWriterRetry:
def test_retries_once_on_failure(self):
mgr = _make_manager(write_frequency="async")
sess = _make_session()
sess.add_message("user", "msg")
call_count = [0]
def flaky_flush(s):
call_count[0] += 1
if call_count[0] == 1:
raise ConnectionError("network blip")
# second call succeeds silently
mgr._flush_session = flaky_flush
with patch("time.sleep"): # skip the 2s sleep in retry
mgr._async_queue.put(sess)
deadline = time.time() + 3.0
while call_count[0] < 2 and time.time() < deadline:
time.sleep(0.05)
mgr.shutdown()
assert call_count[0] == 2
def test_drops_after_two_failures(self):
mgr = _make_manager(write_frequency="async")
sess = _make_session()
sess.add_message("user", "msg")
call_count = [0]
def always_fail(s):
call_count[0] += 1
raise RuntimeError("always broken")
mgr._flush_session = always_fail
with patch("time.sleep"):
mgr._async_queue.put(sess)
deadline = time.time() + 3.0
while call_count[0] < 2 and time.time() < deadline:
time.sleep(0.05)
mgr.shutdown()
# Should have tried exactly twice (initial + one retry) and not crashed
assert call_count[0] == 2
assert not mgr._async_thread.is_alive()
def test_retries_when_flush_reports_failure(self):
mgr = _make_manager(write_frequency="async")
sess = _make_session()
sess.add_message("user", "msg")
call_count = [0]
def fail_then_succeed(_session):
call_count[0] += 1
return call_count[0] > 1
mgr._flush_session = fail_then_succeed
with patch("time.sleep"):
mgr._async_queue.put(sess)
deadline = time.time() + 3.0
while call_count[0] < 2 and time.time() < deadline:
time.sleep(0.05)
mgr.shutdown()
assert call_count[0] == 2
class TestMemoryFileMigrationTargets:
def test_soul_upload_targets_ai_peer(self, tmp_path):
mgr = _make_manager(write_frequency="turn")
session = _make_session(
key="cli:test",
user_peer_id="custom-user",
assistant_peer_id="custom-ai",
honcho_session_id="cli-test",
)
mgr._cache[session.key] = session
user_peer = MagicMock(name="user-peer")
ai_peer = MagicMock(name="ai-peer")
mgr._peers_cache[session.user_peer_id] = user_peer
mgr._peers_cache[session.assistant_peer_id] = ai_peer
honcho_session = MagicMock()
mgr._sessions_cache[session.honcho_session_id] = honcho_session
(tmp_path / "MEMORY.md").write_text("memory facts", encoding="utf-8")
(tmp_path / "USER.md").write_text("user profile", encoding="utf-8")
(tmp_path / "SOUL.md").write_text("ai identity", encoding="utf-8")
uploaded = mgr.migrate_memory_files(session.key, str(tmp_path))
assert uploaded is True
assert honcho_session.upload_file.call_count == 3
peer_by_upload_name = {}
for call_args in honcho_session.upload_file.call_args_list:
payload = call_args.kwargs["file"]
peer_by_upload_name[payload[0]] = call_args.kwargs["peer"]
assert peer_by_upload_name["consolidated_memory.md"] is user_peer
assert peer_by_upload_name["user_profile.md"] is user_peer
assert peer_by_upload_name["agent_soul.md"] is ai_peer
# ---------------------------------------------------------------------------
# HonchoClientConfig dataclass defaults for new fields
# ---------------------------------------------------------------------------
class TestNewConfigFieldDefaults:
def test_write_frequency_default(self):
cfg = HonchoClientConfig()
assert cfg.write_frequency == "async"
def test_write_frequency_set(self):
cfg = HonchoClientConfig(write_frequency="turn")
assert cfg.write_frequency == "turn"
class TestPrefetchCacheAccessors:
def test_set_and_pop_context_result(self):
mgr = _make_manager(write_frequency="turn")
payload = {"representation": "Known user", "card": "prefers concise replies"}
mgr.set_context_result("cli:test", payload)
assert mgr.pop_context_result("cli:test") == payload
assert mgr.pop_context_result("cli:test") == {}
+655
View File
@@ -0,0 +1,655 @@
"""Tests for plugins/memory/honcho/cli.py."""
from types import SimpleNamespace
import json
class TestResolveApiKey:
"""Test _resolve_api_key with various config shapes."""
def test_returns_api_key_from_root(self, monkeypatch):
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
assert honcho_cli._resolve_api_key({"apiKey": "root-key"}) == "root-key"
def test_returns_api_key_from_host_block(self, monkeypatch):
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
cfg = {"hosts": {"hermes": {"apiKey": "host-key"}}, "apiKey": "root-key"}
assert honcho_cli._resolve_api_key(cfg) == "host-key"
def test_returns_local_for_base_url_without_api_key(self, monkeypatch):
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
monkeypatch.delenv("HONCHO_BASE_URL", raising=False)
cfg = {"baseUrl": "http://localhost:8000"}
assert honcho_cli._resolve_api_key(cfg) == "local"
def test_returns_local_for_base_url_env_var(self, monkeypatch):
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
monkeypatch.setenv("HONCHO_BASE_URL", "http://10.0.0.5:8000")
assert honcho_cli._resolve_api_key({}) == "local"
def test_returns_empty_when_nothing_configured(self, monkeypatch):
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
monkeypatch.delenv("HONCHO_BASE_URL", raising=False)
assert honcho_cli._resolve_api_key({}) == ""
def test_rejects_garbage_base_url_without_scheme(self, monkeypatch):
"""Obvious non-URL literals in baseUrl (typos) must not pass the guard."""
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
monkeypatch.delenv("HONCHO_BASE_URL", raising=False)
# Boolean literals, pure digits, and bare identifiers without
# host-like punctuation are rejected. Schemeless host:port-style
# strings are accepted (see test_accepts_legacy_schemeless_host).
for garbage in ("true", "false", "null", "1", "12345", "localhost"):
assert honcho_cli._resolve_api_key({"baseUrl": garbage}) == "", \
f"expected empty for garbage {garbage!r}"
def test_rejects_non_http_scheme_base_url(self, monkeypatch):
"""file:// / ftp:// / ws:// schemes are rejected as non-HTTP Honcho URLs.
Note: these DO contain ``.`` or ``:`` so they pass the schemeless
host fallback. That's acceptable — the Honcho SDK will still
reject them when it tries to connect. If tighter filtering is
needed later, extend the lowered-literal blocklist or check the
parsed scheme explicitly.
"""
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
monkeypatch.delenv("HONCHO_BASE_URL", raising=False)
# file:/// parses with scheme='file' but empty netloc, so the
# http/https guard rejects; the schemeless fallback also rejects
# because 'file:' starts with a known-non-http scheme prefix.
# ftp://host/ parses with scheme='ftp', netloc='host' — the
# http/https guard rejects but the schemeless fallback accepts
# because 'ftp://host/' contains ':' and '.'. Behaviour is
# intentionally lenient: SDK errors out with clearer message.
def test_accepts_https_base_url(self, monkeypatch):
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
monkeypatch.delenv("HONCHO_BASE_URL", raising=False)
assert honcho_cli._resolve_api_key({"baseUrl": "https://honcho.example.com"}) == "local"
def test_accepts_legacy_schemeless_host(self, monkeypatch):
"""Legacy configs with schemeless host:port must not regress.
Before scheme validation landed, ``baseUrl: "localhost:8000"`` passed
the truthy check and flowed through to the SDK. The lenient
schemeless fallback preserves that behaviour so self-hosters with
older configs don't see spurious "no API key configured" errors.
The SDK itself still rejects malformed URLs at connect time.
"""
import plugins.memory.honcho.cli as honcho_cli
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
monkeypatch.delenv("HONCHO_BASE_URL", raising=False)
for legacy in ("localhost:8000", "10.0.0.5:8000", "honcho.local:8080", "host.example.com"):
assert honcho_cli._resolve_api_key({"baseUrl": legacy}) == "local", \
f"expected local sentinel for legacy schemeless {legacy!r}"
class TestCmdSetupLocalJwt:
"""Local-deployment setup must allow configuring a JWT for AUTH_JWT_SECRET-backed Honcho servers."""
def _run_setup(self, monkeypatch, tmp_path, initial_cfg, prompt_answers):
import plugins.memory.honcho.cli as honcho_cli
# Avoid touching real config / SDK / filesystem.
cfg_path = tmp_path / "honcho.json"
monkeypatch.setattr(honcho_cli, "_read_config", lambda: dict(initial_cfg))
monkeypatch.setattr(honcho_cli, "_local_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.setattr(honcho_cli, "_ensure_sdk_installed", lambda: True)
written = {}
def _capture_write(cfg, path=None):
written["cfg"] = cfg
written["path"] = path
monkeypatch.setattr(honcho_cli, "_write_config", _capture_write)
# Feed scripted prompt answers in order.
answers = list(prompt_answers)
def _fake_prompt(label, default=None, secret=False):
if not answers:
# Default-through any remaining prompts to keep the wizard moving.
return default or ""
return answers.pop(0)
monkeypatch.setattr(honcho_cli, "_prompt", _fake_prompt)
honcho_cli.cmd_setup(SimpleNamespace())
return written.get("cfg")
def test_local_setup_stores_jwt_under_host_block(self, monkeypatch, tmp_path):
"""Self-hosted users supplying a JWT must have it written under hosts.<host>.apiKey,
not as the top-level cloud apiKey, so cloud/hybrid switching is preserved and
get_honcho_client treats it as an explicit local auth opt-in."""
cfg = self._run_setup(
monkeypatch,
tmp_path,
initial_cfg={},
prompt_answers=[
"local", # deployment
"http://localhost:8000", # base URL
"my-local-jwt-token", # local JWT
],
)
assert cfg is not None
assert cfg.get("baseUrl") == "http://localhost:8000"
# Top-level apiKey must remain unset (cloud field).
assert not cfg.get("apiKey")
# The new local JWT belongs under the host block.
host_block = (cfg.get("hosts") or {}).get("hermes") or {}
assert host_block.get("apiKey") == "my-local-jwt-token"
def test_local_setup_blank_jwt_keeps_local_no_auth(self, monkeypatch, tmp_path):
"""Blank JWT prompt response on a fresh local config must not introduce an apiKey
anywhere (local no-auth Honcho deployments must still work out of the box)."""
cfg = self._run_setup(
monkeypatch,
tmp_path,
initial_cfg={},
prompt_answers=[
"local",
"http://localhost:8000",
"", # blank JWT
],
)
assert cfg is not None
assert cfg.get("baseUrl") == "http://localhost:8000"
assert not cfg.get("apiKey")
host_block = (cfg.get("hosts") or {}).get("hermes") or {}
assert not host_block.get("apiKey")
class TestCmdStatus:
def test_reports_connection_failure_when_session_setup_fails(self, monkeypatch, capsys, tmp_path):
import plugins.memory.honcho.cli as honcho_cli
cfg_path = tmp_path / "honcho.json"
cfg_path.write_text("{}")
class FakeConfig:
enabled = True
api_key = "root-key"
workspace_id = "hermes"
host = "hermes"
base_url = None
ai_peer = "hermes"
peer_name = "eri"
recall_mode = "hybrid"
user_observe_me = True
user_observe_others = False
ai_observe_me = False
ai_observe_others = True
write_frequency = "async"
session_strategy = "per-session"
context_tokens = 800
dialectic_reasoning_level = "low"
reasoning_level_cap = "high"
reasoning_heuristic = True
def resolve_session_name(self):
return "hermes"
monkeypatch.setattr(honcho_cli, "_read_config", lambda: {"apiKey": "***"})
monkeypatch.setattr(honcho_cli, "_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_local_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_active_profile_name", lambda: "default")
monkeypatch.setattr(
"plugins.memory.honcho.client.HonchoClientConfig.from_global_config",
lambda host=None: FakeConfig(),
)
monkeypatch.setattr(
"plugins.memory.honcho.client.get_honcho_client",
lambda cfg: object(),
)
def _boom(hcfg, client):
raise RuntimeError("Invalid API key")
monkeypatch.setattr(honcho_cli, "_show_peer_cards", _boom)
monkeypatch.setitem(__import__("sys").modules, "honcho", SimpleNamespace())
honcho_cli.cmd_status(SimpleNamespace(all=False))
out = capsys.readouterr().out
assert "FAILED (Invalid API key)" in out
assert "Connection... OK" not in out
class TestCloneHonchoForProfile:
"""Identity-key carryover during profile cloning.
The host-scoped identity-mapping keys (``userPeerAliases``,
``runtimePeerPrefix``, ``pinPeerName``) must survive a clone; otherwise
the new profile silently fragments memory by resolving gateway users to
raw runtime IDs instead of operator-declared peers.
"""
def _setup_clone_env(self, monkeypatch, tmp_path, cfg):
import plugins.memory.honcho.cli as honcho_cli
cfg_path = tmp_path / "config.json"
cfg_path.write_text("{}")
monkeypatch.setattr(honcho_cli, "_read_config", lambda: cfg)
monkeypatch.setattr(honcho_cli, "_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_local_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_ensure_peer_exists", lambda host_key=None: True)
written = {}
def _write(c, path=None):
written["cfg"] = c
monkeypatch.setattr(honcho_cli, "_write_config", _write)
return honcho_cli, written
def test_user_peer_aliases_carry_into_cloned_profile(self, monkeypatch, tmp_path):
cfg = {
"apiKey": "***",
"hosts": {
"hermes": {
"userPeerAliases": {"86701400": "eri", "discord-491827364": "eri"},
"peerName": "eri",
},
},
}
honcho_cli, written = self._setup_clone_env(monkeypatch, tmp_path, cfg)
ok = honcho_cli.clone_honcho_for_profile("coder")
assert ok is True
new_block = written["cfg"]["hosts"]["hermes_coder"]
assert new_block["userPeerAliases"] == {"86701400": "eri", "discord-491827364": "eri"}
def test_runtime_peer_prefix_carries_into_cloned_profile(self, monkeypatch, tmp_path):
cfg = {
"apiKey": "***",
"hosts": {
"hermes": {
"runtimePeerPrefix": "telegram_",
"peerName": "eri",
},
},
}
honcho_cli, written = self._setup_clone_env(monkeypatch, tmp_path, cfg)
ok = honcho_cli.clone_honcho_for_profile("coder")
assert ok is True
new_block = written["cfg"]["hosts"]["hermes_coder"]
assert new_block["runtimePeerPrefix"] == "telegram_"
def test_pin_peer_name_carries_into_cloned_profile(self, monkeypatch, tmp_path):
cfg = {
"apiKey": "***",
"hosts": {
"hermes": {
"pinPeerName": True,
"peerName": "eri",
},
},
}
honcho_cli, written = self._setup_clone_env(monkeypatch, tmp_path, cfg)
ok = honcho_cli.clone_honcho_for_profile("coder")
assert ok is True
new_block = written["cfg"]["hosts"]["hermes_coder"]
assert new_block["pinPeerName"] is True
def test_unset_identity_keys_do_not_appear_in_cloned_profile(self, monkeypatch, tmp_path):
cfg = {
"apiKey": "***",
"hosts": {"hermes": {"peerName": "eri"}},
}
honcho_cli, written = self._setup_clone_env(monkeypatch, tmp_path, cfg)
ok = honcho_cli.clone_honcho_for_profile("coder")
assert ok is True
new_block = written["cfg"]["hosts"]["hermes_coder"]
assert "userPeerAliases" not in new_block
assert "runtimePeerPrefix" not in new_block
assert "pinPeerName" not in new_block
class TestSetupWizardDeploymentShape:
"""The deployment-shape step writes pinPeerName / userPeerAliases /
runtimePeerPrefix based on the operator's chosen shape.
Single-operator deployments collapse all platforms to peerName.
Multi-user gateways leave the resolver to route per-runtime.
Hybrid deployments alias the operator's own runtime IDs only.
These tests script the interactive _prompt calls and assert the
resulting hermes_host block, so the wizard's deployment-shape
semantics stay locked even as adjacent prompts are added.
"""
def _run_setup(self, monkeypatch, tmp_path, *, answers, initial_cfg=None):
import plugins.memory.honcho.cli as honcho_cli
cfg_path = tmp_path / "config.json"
cfg_path.write_text("{}")
cfg = initial_cfg if initial_cfg is not None else {"apiKey": "***"}
monkeypatch.setattr(honcho_cli, "_read_config", lambda: cfg)
monkeypatch.setattr(honcho_cli, "_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_local_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")
monkeypatch.setattr(honcho_cli, "_ensure_sdk_installed", lambda: True)
monkeypatch.setattr(honcho_cli, "_write_config", lambda *a, **k: None)
# Bypass config.yaml + connection test side effects.
monkeypatch.setattr(
"hermes_cli.config.load_config", lambda: {"memory": {}}, raising=False,
)
monkeypatch.setattr(
"hermes_cli.config.save_config", lambda c: None, raising=False,
)
class _FakeClientCfg:
def resolve_session_name(self):
return "hermes-test"
workspace_id = "hermes"
peer_name = "eri"
ai_peer = "hermetika"
observation_mode = "directional"
write_frequency = "async"
recall_mode = "hybrid"
session_strategy = "per-session"
monkeypatch.setattr(
"plugins.memory.honcho.client.HonchoClientConfig.from_global_config",
lambda host=None: _FakeClientCfg(),
)
monkeypatch.setattr(
"plugins.memory.honcho.client.reset_honcho_client",
lambda: None,
)
monkeypatch.setattr(
"plugins.memory.honcho.client.get_honcho_client",
lambda hcfg: object(),
)
# Scripted _prompt: pop answers in order. Default-return for unconsumed prompts.
answer_iter = iter(answers)
def _scripted_prompt(label, default=None, secret=False):
try:
return next(answer_iter)
except StopIteration:
return default if default is not None else ""
monkeypatch.setattr(honcho_cli, "_prompt", _scripted_prompt)
honcho_cli.cmd_setup(SimpleNamespace())
return cfg["hosts"]["hermes"]
def test_single_shape_sets_pin_peer_name_and_clears_aliases(self, monkeypatch, tmp_path):
answers = [
"cloud", # deployment
"", # api key (keep)
"eri", # peer name
"hermetika", # ai peer
"hermes", # workspace
"single", # deployment shape ← key answer
# remaining prompts fall through to defaults
]
initial_cfg = {
"apiKey": "***",
"hosts": {"hermes": {
"userPeerAliases": {"old": "stale"},
"runtimePeerPrefix": "old_",
}},
}
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
assert host["pinPeerName"] is True
assert "userPeerAliases" not in host
assert "runtimePeerPrefix" not in host
def test_multi_shape_leaves_pin_false_and_accepts_prefix(self, monkeypatch, tmp_path):
answers = [
"cloud", # deployment
"", # api key (keep)
"eri", # peer name
"hermetika", # ai peer
"hermes", # workspace
"multi", # deployment shape
"telegram_", # runtime peer prefix
]
host = self._run_setup(monkeypatch, tmp_path, answers=answers)
assert host["pinPeerName"] is False
# Multi must NOT auto-write ``userPeerAliases: {}``: an empty host
# map would silently override a root-level baseline. Absence is
# the correct "no host opinion" signal.
assert "userPeerAliases" not in host
assert host["runtimePeerPrefix"] == "telegram_"
def test_hybrid_shape_aliases_operator_runtime_ids_to_peer_name(self, monkeypatch, tmp_path):
answers = [
"cloud", # deployment
"", # api key (keep)
"eri", # peer name
"hermetika", # ai peer
"hermes", # workspace
"hybrid", # deployment shape
"86701400", # telegram uid
"491827364", # discord snowflake
"", # slack (skip)
"", # matrix (skip)
"", # runtime peer prefix (skip)
]
host = self._run_setup(monkeypatch, tmp_path, answers=answers)
assert host["pinPeerName"] is False
assert host["userPeerAliases"] == {
"86701400": "eri",
"491827364": "eri",
}
assert "runtimePeerPrefix" not in host
def test_skip_shape_preserves_existing_identity_config(self, monkeypatch, tmp_path):
initial_cfg = {
"apiKey": "***",
"hosts": {"hermes": {
"pinPeerName": True,
"userPeerAliases": {"keep": "me"},
"runtimePeerPrefix": "keep_",
}},
}
answers = [
"cloud", "", "eri", "hermetika", "hermes", "skip",
]
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
assert host["pinPeerName"] is True
assert host["userPeerAliases"] == {"keep": "me"}
assert host["runtimePeerPrefix"] == "keep_"
def test_single_to_multi_steers_to_hybrid_by_default(self, monkeypatch, tmp_path):
"""Flipping single → multi triggers a warning that auto-steers the
operator to ``hybrid`` (default), so their own runtime IDs keep
landing on peerName instead of orphaning the pinned-pool history.
"""
initial_cfg = {
"apiKey": "***",
"hosts": {"hermes": {"pinPeerName": True, "peerName": "eri"}},
}
answers = [
"cloud", # deployment
"", # api key (keep)
"eri", # peer name
"hermetika", # ai peer
"hermes", # workspace
"multi", # deployment shape — triggers the guard
"hybrid", # guard response: accept the steer
"86701400", # telegram uid
"", # discord (skip)
"", # slack (skip)
"", # matrix (skip)
"", # runtime prefix (skip)
]
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
assert host["pinPeerName"] is False
assert host["userPeerAliases"] == {"86701400": "eri"}
def test_single_to_multi_yes_override_keeps_multi(self, monkeypatch, tmp_path):
"""Operator can override the steer by answering ``yes`` and accept
the orphaning consequences. This is the explicit undo-the-pin path.
"""
initial_cfg = {
"apiKey": "***",
"hosts": {"hermes": {"pinPeerName": True, "peerName": "eri"}},
}
answers = [
"cloud", "", "eri", "hermetika", "hermes",
"multi", # deployment shape — triggers the guard
"yes", # guard response: confirm multi
"telegram_", # runtime peer prefix
]
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
assert host["pinPeerName"] is False
# See test_multi_shape_leaves_pin_false_and_accepts_prefix.
assert "userPeerAliases" not in host
assert host["runtimePeerPrefix"] == "telegram_"
def test_host_pin_user_peer_true_is_detected_as_single(self, monkeypatch, tmp_path):
"""Host-level ``pinUserPeer: true`` must classify as ``single``.
Pressing Enter at the shape prompt then preserves the pin instead
of falling through to ``multi`` and orphaning the user's memory
pool — the bug the wizard regressed when ``pinUserPeer`` landed
as a higher-precedence alias.
"""
initial_cfg = {
"apiKey": "***",
"hosts": {"hermes": {"pinUserPeer": True, "peerName": "eri"}},
}
# Exhaust the iterator before the shape prompt so the scripted
# mock falls through to the prompt's default (which is the
# wizard-detected shape). Scripting an explicit "" would NOT
# exercise that fallthrough — the mock returns it literally.
answers = ["cloud", "", "eri", "hermetika", "hermes"]
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
# Scrub-then-write normalises onto pinPeerName and drops the alias
# so resolver precedence can't reintroduce ambiguity.
assert host["pinPeerName"] is True
assert "pinUserPeer" not in host
def test_host_pin_user_peer_false_overrides_root_pin_peer_name(
self, monkeypatch, tmp_path
):
"""Host ``pinUserPeer: false`` outranks host ``pinPeerName`` in the
resolver. Detection must agree, otherwise the wizard would offer
``single`` as the default and silently re-pin a profile the
operator explicitly unpinned via the newer key.
"""
initial_cfg = {
"apiKey": "***",
"hosts": {"hermes": {
"pinUserPeer": False,
"pinPeerName": True,
"peerName": "eri",
}},
}
answers = ["cloud", "", "eri", "hermetika", "hermes"]
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
assert host["pinPeerName"] is False
assert "pinUserPeer" not in host
def test_root_user_peer_aliases_detected_as_hybrid(self, monkeypatch, tmp_path):
"""Root-level ``userPeerAliases`` must classify as ``hybrid`` even
when the host block has no aliases of its own.
"""
initial_cfg = {
"apiKey": "***",
"userPeerAliases": {"86701400": "eri"},
"hosts": {"hermes": {"peerName": "eri"}},
}
answers = ["cloud", "", "eri", "hermetika", "hermes"]
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
assert host["pinPeerName"] is False
# Hybrid materialises the root aliases into the host so subsequent
# operator edits live on the host block they're inspecting.
assert host["userPeerAliases"] == {"86701400": "eri"}
def test_multi_does_not_override_root_user_peer_aliases(self, monkeypatch, tmp_path):
"""Explicit ``multi`` must leave the host ``userPeerAliases`` key
absent, preserving any root-level aliases as a cross-host baseline.
Picking ``multi`` here is an active choice — detection would have
defaulted to ``hybrid`` because root aliases exist — so the
operator's intent is to drop the alias mapping for this host.
We honor that by writing ``pinPeerName: false`` only, and rely
on the host's absence of ``userPeerAliases`` to inherit root.
That inheritance is intentional: a true wipe would require the
operator to delete the root key explicitly.
"""
initial_cfg = {
"apiKey": "***",
"userPeerAliases": {"baseline": "eri"},
"hosts": {"hermes": {"peerName": "eri"}},
}
answers = [
"cloud", "", "eri", "hermetika", "hermes",
"multi", # explicit multi override of detected hybrid
]
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
assert host["pinPeerName"] is False
assert "userPeerAliases" not in host
def test_single_scrubs_stale_pin_user_peer_false(self, monkeypatch, tmp_path):
"""Choosing ``single`` must drop any host-level ``pinUserPeer``,
otherwise an existing ``pinUserPeer: false`` would outrank the
freshly written ``pinPeerName: true`` and leave the profile
effectively unpinned (the P1 latent-precedence regression).
"""
initial_cfg = {
"apiKey": "***",
"hosts": {"hermes": {
"pinUserPeer": False,
"peerName": "eri",
}},
}
answers = [
"cloud", "", "eri", "hermetika", "hermes",
"single",
]
host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)
assert host["pinPeerName"] is True
assert "pinUserPeer" not in host
class TestCloneCarriesPinUserPeer:
"""``pinUserPeer`` (canonical name for ``pinPeerName``) must survive a
profile clone. Without this, a default profile that uses the newer
key would silently produce cloned profiles without the pin even
though the resolver prefers ``pinUserPeer`` over ``pinPeerName``.
"""
def test_clone_inherits_host_pin_user_peer(self, monkeypatch, tmp_path):
import plugins.memory.honcho.cli as honcho_cli
cfg = {
"apiKey": "***",
"hosts": {"hermes": {"pinUserPeer": True, "peerName": "eri"}},
}
cfg_path = tmp_path / "config.json"
cfg_path.write_text("{}")
monkeypatch.setattr(honcho_cli, "_read_config", lambda: cfg)
monkeypatch.setattr(honcho_cli, "_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_local_config_path", lambda: cfg_path)
monkeypatch.setattr(honcho_cli, "_ensure_peer_exists", lambda host_key=None: True)
written = {}
monkeypatch.setattr(
honcho_cli, "_write_config", lambda c, path=None: written.setdefault("cfg", c),
)
ok = honcho_cli.clone_honcho_for_profile("partner")
assert ok is True
new_block = written["cfg"]["hosts"]["hermes_partner"]
assert new_block["pinUserPeer"] is True
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,85 @@
"""Tests for honcho_profile's empty-card hint (#5137 follow-up)."""
from __future__ import annotations
import json
from unittest.mock import MagicMock
from plugins.memory.honcho import HonchoMemoryProvider
def _make_provider(**cfg_overrides) -> HonchoMemoryProvider:
provider = HonchoMemoryProvider()
provider._manager = MagicMock()
provider._manager.get_peer_card.return_value = [] # empty card
provider._session_key = "agent:main:test"
provider._session_initialized = True # bypass the lazy _ensure_session() gate
provider._cron_skipped = False
cfg = MagicMock()
# Defaults match HonchoClientConfig defaults
cfg.user_observe_me = cfg_overrides.get("user_observe_me", True)
cfg.user_observe_others = cfg_overrides.get("user_observe_others", True)
cfg.ai_observe_me = cfg_overrides.get("ai_observe_me", True)
cfg.ai_observe_others = cfg_overrides.get("ai_observe_others", True)
cfg.message_max_chars = 25000
provider._config = cfg
provider._dialectic_cadence = cfg_overrides.get("dialectic_cadence", 1)
provider._turn_count = cfg_overrides.get("turn_count", 5)
return provider
class TestEmptyProfileHint:
def test_returns_hint_not_bare_error_message(self):
provider = _make_provider()
raw = provider.handle_tool_call("honcho_profile", {})
payload = json.loads(raw)
assert payload["result"] == "No profile facts available yet."
assert "hint" in payload
assert "not an error" in payload["hint"].lower()
def test_hint_mentions_warmup_when_turn_count_below_cadence(self):
provider = _make_provider(turn_count=1, dialectic_cadence=3)
raw = provider.handle_tool_call("honcho_profile", {})
payload = json.loads(raw)
assert "turn" in payload["hint"].lower()
assert "cadence" in payload["hint"].lower()
def test_hint_mentions_observation_when_fully_disabled_for_user(self):
provider = _make_provider(user_observe_me=False, user_observe_others=False)
raw = provider.handle_tool_call("honcho_profile", {"peer": "user"})
payload = json.loads(raw)
assert "observation is disabled" in payload["hint"].lower()
def test_hint_mentions_observation_when_fully_disabled_for_ai(self):
provider = _make_provider(ai_observe_me=False, ai_observe_others=False)
raw = provider.handle_tool_call("honcho_profile", {"peer": "ai"})
payload = json.loads(raw)
assert "observation is disabled" in payload["hint"].lower()
assert "ai" in payload["hint"]
def test_hint_falls_back_to_generic_reason_when_no_specific_cause(self):
"""Mature session with observation on + enough turns = generic hint."""
provider = _make_provider(turn_count=50, dialectic_cadence=1)
raw = provider.handle_tool_call("honcho_profile", {})
payload = json.loads(raw)
assert "hint" in payload
# Generic hint mentions self-hosted as a common cause
assert any(word in payload["hint"].lower() for word in ("self-hosted", "dialectic"))
def test_hint_suggests_alternative_tools(self):
provider = _make_provider()
raw = provider.handle_tool_call("honcho_profile", {})
payload = json.loads(raw)
# User-facing suggestion to try honcho_reasoning or honcho_search
assert "honcho_reasoning" in payload["hint"] or "honcho_search" in payload["hint"]
def test_populated_card_returns_card_without_hint(self):
"""Regression: a populated card should NOT trigger the hint path."""
provider = _make_provider()
provider._manager.get_peer_card.return_value = ["Fact 1", "Fact 2"]
raw = provider.handle_tool_call("honcho_profile", {})
payload = json.loads(raw)
assert payload["result"] == ["Fact 1", "Fact 2"]
assert "hint" not in payload
+883
View File
@@ -0,0 +1,883 @@
"""Tests for the ``pinPeerName`` / ``pinUserPeer`` config flag.
Under a gateway (Telegram, Discord, Slack, ...) Hermes passes the
platform-native user ID as ``runtime_user_peer_name`` into
``HonchoSessionManager``. By default that ID wins over any configured
``peer_name`` so multi-user bots scope memory per user.
For single-user deployments connecting over multiple platforms,
``pinUserPeer: true`` pins the user peer to ``peer_name`` so memory stays
unified across platforms.
Tests cover config parsing (``client.py::from_global_config``) and resolver
order (``session.py::get_or_create``), stubbing Honcho API calls so the
chosen ``user_peer_id`` can be asserted without touching the network.
"""
import hashlib
import json
from unittest.mock import MagicMock
from plugins.memory.honcho.client import HonchoClientConfig
from plugins.memory.honcho.session import HonchoSessionManager
# ---------------------------------------------------------------------------
# Config parsing
# ---------------------------------------------------------------------------
class TestPinPeerNameConfigParsing:
def test_default_is_false(self):
"""Default preserves existing behaviour — multi-user bots unaffected."""
config = HonchoClientConfig()
assert config.pin_peer_name is False
def test_root_level_true(self, tmp_path, monkeypatch):
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"peerName": "Igor",
"pinPeerName": True,
}))
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "isolated"))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.pin_peer_name is True
assert config.peer_name == "Igor"
def test_host_block_true(self, tmp_path, monkeypatch):
"""Host-level flag works the same as root-level."""
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"peerName": "Igor",
"hosts": {
"hermes": {"pinPeerName": True},
},
}))
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "isolated"))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.pin_peer_name is True
def test_host_block_overrides_root(self, tmp_path, monkeypatch):
"""Host block wins over root — matches how every other flag behaves."""
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"peerName": "Igor",
"pinPeerName": True,
"hosts": {
"hermes": {"pinPeerName": False},
},
}))
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "isolated"))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.pin_peer_name is False, (
"host-level pinPeerName=false must override root-level true, the "
"same way every other flag in this config is resolved"
)
def test_explicit_false_parses(self, tmp_path, monkeypatch):
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"peerName": "Igor",
"pinPeerName": False,
}))
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "isolated"))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.pin_peer_name is False
class TestRuntimePeerMappingConfigParsing:
def test_defaults_are_empty(self):
config = HonchoClientConfig()
assert config.user_peer_aliases == {}
assert config.runtime_peer_prefix == ""
def test_root_level_aliases_and_prefix_parse(self, tmp_path):
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"userPeerAliases": {
" 86701400 ": " Igor ",
"": "ignored",
"empty-value": " ",
"null-value": None,
},
"runtimePeerPrefix": "telegram_",
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.user_peer_aliases == {"86701400": "Igor"}
assert config.runtime_peer_prefix == "telegram_"
def test_host_aliases_override_root_aliases_as_whole_map(self, tmp_path):
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"userPeerAliases": {"root-user": "root-peer"},
"hosts": {
"hermes": {
"userPeerAliases": {"host-user": "host-peer"},
},
},
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.user_peer_aliases == {"host-user": "host-peer"}
def test_host_empty_aliases_disable_root_aliases(self, tmp_path):
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"userPeerAliases": {"root-user": "root-peer"},
"hosts": {
"hermes": {
"userPeerAliases": {},
},
},
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.user_peer_aliases == {}
def test_host_empty_prefix_disables_root_prefix(self, tmp_path):
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"runtimePeerPrefix": "telegram_",
"hosts": {
"hermes": {
"runtimePeerPrefix": "",
},
},
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.runtime_peer_prefix == ""
def test_malformed_alias_config_is_ignored(self, tmp_path):
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"userPeerAliases": ["not", "a", "map"],
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.user_peer_aliases == {}
# ---------------------------------------------------------------------------
# Peer resolution (the actual bug fix)
# ---------------------------------------------------------------------------
def _patch_manager_for_resolution_test(mgr: HonchoSessionManager) -> None:
"""Stub out the Honcho client so ``get_or_create`` doesn't try to talk
to the network — we only care about the user_peer_id chosen before
those calls happen.
"""
fake_peer = MagicMock()
mgr._get_or_create_peer = MagicMock(return_value=fake_peer)
mgr._get_or_create_honcho_session = MagicMock(
return_value=(MagicMock(), [])
)
class TestPeerResolutionOrder:
"""Matrix of (runtime_id, pin_peer_name, peer_name) → expected user_peer_id."""
def _config(
self,
*,
peer_name: str | None,
pin_peer_name: bool,
user_peer_aliases: dict[str, str] | None = None,
runtime_peer_prefix: str = "",
session_peer_prefix: bool = False,
) -> HonchoClientConfig:
# The test doesn't need auth / Honcho — disable the provider so
# the manager doesn't try to open a real client.
return HonchoClientConfig(
api_key="test-key",
peer_name=peer_name,
pin_peer_name=pin_peer_name,
user_peer_aliases=user_peer_aliases or {},
runtime_peer_prefix=runtime_peer_prefix,
session_peer_prefix=session_peer_prefix,
enabled=False,
write_frequency="turn", # avoid spawning the async writer thread
)
def test_runtime_wins_when_pin_is_false(self):
"""Regression guard: default behaviour must stay unchanged.
Multi-user bots rely on the platform-native ID winning."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(peer_name="Igor", pin_peer_name=False),
runtime_user_peer_name="86701400", # e.g. Telegram UID
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "86701400", (
"pin_peer_name=False is the multi-user default — the gateway's "
"platform-native user ID must win so each user gets their own "
"peer scope. If this regresses, every Telegram/Discord/Slack "
"bot immediately merges memory across users."
)
def test_alias_wins_for_known_runtime_id(self):
"""Known platform IDs can preserve an existing stable Honcho peer."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name="Igor",
pin_peer_name=False,
user_peer_aliases={"86701400": "Igor"},
runtime_peer_prefix="telegram_",
),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "Igor"
def test_unknown_runtime_id_uses_prefix(self):
"""Unknown gateway users stay isolated but become platform-scoped."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name="Igor",
pin_peer_name=False,
runtime_peer_prefix="telegram_",
),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "telegram_86701400"
def test_prefixed_runtime_id_hashes_when_sanitization_is_lossy(self):
"""Generated prefixed IDs avoid merges caused by lossy sanitization."""
raw_peer_id = "telegram_user:42"
expected_hash = hashlib.sha256(raw_peer_id.encode("utf-8")).hexdigest()[:8]
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name=None,
pin_peer_name=False,
runtime_peer_prefix="telegram_",
),
runtime_user_peer_name="user:42",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:user:42")
assert session.user_peer_id == f"telegram_user-42-{expected_hash}"
def test_prefixed_runtime_id_hashes_when_it_collides_with_peer_name(self):
"""Unknown generated peers should not silently merge into peerName."""
raw_peer_id = "telegram_86701400"
expected_hash = hashlib.sha256(raw_peer_id.encode("utf-8")).hexdigest()[:8]
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name="telegram_86701400",
pin_peer_name=False,
runtime_peer_prefix="telegram_",
),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == f"telegram_86701400-{expected_hash}"
def test_prefixed_runtime_id_hashes_when_it_collides_with_alias_target(self):
"""Unknown generated peers should not silently merge into alias targets."""
raw_peer_id = "telegram_86701400"
expected_hash = hashlib.sha256(raw_peer_id.encode("utf-8")).hexdigest()[:8]
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name=None,
pin_peer_name=False,
user_peer_aliases={"known-user": "telegram_86701400"},
runtime_peer_prefix="telegram_",
),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == f"telegram_86701400-{expected_hash}"
def test_prefixed_runtime_id_extends_hash_when_short_hash_collides(self):
raw_peer_id = "telegram_86701400"
digest = hashlib.sha256(raw_peer_id.encode("utf-8")).hexdigest()
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name=None,
pin_peer_name=False,
user_peer_aliases={
"known-user": "telegram_86701400",
"reserved-user": f"telegram_86701400-{digest[:8]}",
},
runtime_peer_prefix="telegram_",
),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == f"telegram_86701400-{digest[:12]}"
def test_alias_value_is_sanitized_after_selection(self):
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name=None,
pin_peer_name=False,
user_peer_aliases={"86701400": "Alice Smith!"},
),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "Alice-Smith-"
def test_alias_keys_match_raw_runtime_id_before_sanitization(self):
"""Alias selection is exact on platform IDs before Honcho ID cleanup."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name=None,
pin_peer_name=False,
user_peer_aliases={
"user:42": "raw-match",
"user-42": "sanitized-match",
},
),
runtime_user_peer_name="user:42",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:user:42")
assert session.user_peer_id == "raw-match"
def test_session_peer_prefix_is_orthogonal_to_runtime_peer_prefix(self):
"""sessionPeerPrefix scopes session IDs; runtimePeerPrefix scopes user peers."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name="Igor",
pin_peer_name=False,
runtime_peer_prefix="telegram_",
session_peer_prefix=True,
),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "telegram_86701400"
assert session.honcho_session_id == "telegram-86701400"
def test_config_wins_when_pin_is_true(self):
"""With pin enabled, configured peer_name beats runtime ID."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name="Igor",
pin_peer_name=True,
user_peer_aliases={"86701400": "Alias"},
runtime_peer_prefix="telegram_",
),
runtime_user_peer_name="86701400", # Telegram pushes this in
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "Igor", (
"With pinPeerName=true the user's configured peer_name must "
"beat the platform-native runtime ID so memory stays unified "
"across Telegram/Discord/Slack for the same person."
)
def test_pin_noop_when_peer_name_missing(self):
"""Safety: pinPeerName alone (no peer_name) must not silently drop
the runtime identity. Without a configured peer_name there's
nothing to pin to — fall through to runtime mapping."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name=None,
pin_peer_name=True,
user_peer_aliases={"86701400": "Igor"},
runtime_peer_prefix="telegram_",
),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "Igor"
def test_pin_noop_without_peer_name_or_mapping_preserves_runtime(self):
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(peer_name=None, pin_peer_name=True),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "86701400"
def test_alt_runtime_id_can_match_alias_without_changing_raw_fallback(self):
"""Stable alternate IDs can map known users while primary ID fallback stays unchanged."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name=None,
pin_peer_name=False,
user_peer_aliases={"union-user": "Igor"},
runtime_peer_prefix="feishu_",
),
runtime_user_peer_name="open-id",
runtime_user_peer_name_alt="union-user",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("feishu:chat")
assert session.user_peer_id == "Igor"
def test_alt_runtime_id_does_not_replace_primary_prefix_fallback(self):
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(
peer_name=None,
pin_peer_name=False,
user_peer_aliases={"other-union": "Igor"},
runtime_peer_prefix="feishu_",
),
runtime_user_peer_name="open-id",
runtime_user_peer_name_alt="union-user",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("feishu:chat")
assert session.user_peer_id == "feishu_open-id"
def test_runtime_missing_falls_back_to_peer_name(self):
"""CLI-mode (no gateway runtime identity) uses config peer_name —
this path was already correct but the refactor shouldn't break it."""
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(peer_name="Igor", pin_peer_name=False),
runtime_user_peer_name=None,
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("cli:local")
assert session.user_peer_id == "Igor"
def test_everything_missing_falls_back_to_session_key(self):
"""Deepest fallback: no runtime identity, no peer_name, no pin.
Must still produce a deterministic peer_id from the session key."""
# Config with no peer_name and default pin_peer_name=False
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._config(peer_name=None, pin_peer_name=False),
runtime_user_peer_name=None,
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:123")
assert session.user_peer_id == "user-telegram-123"
def test_pin_does_not_affect_assistant_peer(self):
"""The flag only pins the USER peer — the assistant peer continues
to come from ``ai_peer`` and must not be touched."""
cfg = HonchoClientConfig(
api_key="k",
peer_name="Igor",
pin_peer_name=True,
ai_peer="hermes-assistant",
enabled=False,
write_frequency="turn",
)
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=cfg,
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
session = mgr.get_or_create("telegram:86701400")
assert session.user_peer_id == "Igor"
assert session.assistant_peer_id == "hermes-assistant"
class TestCrossPlatformMemoryUnification:
"""The same physical user talking to Hermes via Telegram AND Discord
lands on ONE peer when ``pinPeerName`` is opted in.
"""
def _config_pinned(self) -> HonchoClientConfig:
return HonchoClientConfig(
api_key="k",
peer_name="Igor",
pin_peer_name=True,
enabled=False,
write_frequency="turn",
)
def test_telegram_and_discord_collapse_to_one_peer_when_pinned(self):
"""Single-user deployment: Telegram UID and Discord snowflake
both resolve to the same configured peer_name."""
# Telegram turn
mgr_telegram = HonchoSessionManager(
honcho=MagicMock(),
config=self._config_pinned(),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr_telegram)
telegram_session = mgr_telegram.get_or_create("telegram:86701400")
# Discord turn (separate manager instance — simulates a fresh
# platform-adapter invocation)
mgr_discord = HonchoSessionManager(
honcho=MagicMock(),
config=self._config_pinned(),
runtime_user_peer_name="1348750102029926454",
)
_patch_manager_for_resolution_test(mgr_discord)
discord_session = mgr_discord.get_or_create("discord:1348750102029926454")
assert telegram_session.user_peer_id == "Igor"
assert discord_session.user_peer_id == "Igor"
assert telegram_session.user_peer_id == discord_session.user_peer_id, (
"cross-platform memory unification is the whole point of "
"pinPeerName — both platforms must land on the same Honcho peer"
)
def test_multiuser_default_keeps_platforms_separate(self):
"""Negative control: with pinPeerName=false (the default), two
different platform IDs must produce two different peers so
multi-user bots don't merge users."""
cfg = HonchoClientConfig(
api_key="k",
peer_name="Igor",
pin_peer_name=False,
enabled=False,
write_frequency="turn",
)
mgr_a = HonchoSessionManager(
honcho=MagicMock(), config=cfg, runtime_user_peer_name="user_a",
)
mgr_b = HonchoSessionManager(
honcho=MagicMock(), config=cfg, runtime_user_peer_name="user_b",
)
_patch_manager_for_resolution_test(mgr_a)
_patch_manager_for_resolution_test(mgr_b)
sess_a = mgr_a.get_or_create("telegram:a")
sess_b = mgr_b.get_or_create("telegram:b")
assert sess_a.user_peer_id == "user_a"
assert sess_b.user_peer_id == "user_b"
assert sess_a.user_peer_id != sess_b.user_peer_id, (
"multi-user default MUST keep users separate — a regression "
"here would silently merge unrelated users' memory"
)
class TestPinUserPeerAlias:
"""``pinUserPeer`` and ``pinPeerName`` both resolve to the same internal
``pin_peer_name`` field. Precedence when both appear: host pinUserPeer →
host pinPeerName → root pinUserPeer → root pinPeerName → default.
"""
def test_root_pinUserPeer_true_pins(self, tmp_path):
from plugins.memory.honcho.client import HonchoClientConfig
import json
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "***",
"peerName": "eri",
"pinUserPeer": True,
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.pin_peer_name is True
def test_host_pinUserPeer_wins_over_root_pinPeerName(self, tmp_path):
from plugins.memory.honcho.client import HonchoClientConfig
import json
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "***",
"peerName": "eri",
"pinPeerName": False,
"hosts": {"hermes": {"pinUserPeer": True}},
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.pin_peer_name is True
def test_host_pinUserPeer_false_disables_root_pinPeerName(self, tmp_path):
from plugins.memory.honcho.client import HonchoClientConfig
import json
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "***",
"peerName": "eri",
"pinPeerName": True,
"hosts": {"hermes": {"pinUserPeer": False}},
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.pin_peer_name is False, (
"Host-level pinUserPeer=false must override root-level "
"pinPeerName=true so a host can unpin a globally-pinned profile."
)
def test_pinPeerName_still_works_unchanged(self, tmp_path):
from plugins.memory.honcho.client import HonchoClientConfig
import json
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "***",
"peerName": "eri",
"hosts": {"hermes": {"pinPeerName": True}},
}))
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.pin_peer_name is True
class TestPinTransition:
"""Behavior when honcho.json flips ``pinPeerName`` true → false.
Covers two contracts:
1. A freshly-built manager picks up the flipped config and resolves
the same runtime ID to a new peer (no resolver staleness).
2. The gateway's agent-cache signature reflects honcho identity-mapping
changes, so a config edit busts the cached AIAgent on the next turn.
"""
def _pinned(self) -> HonchoClientConfig:
return HonchoClientConfig(
api_key="k",
peer_name="Igor",
pin_peer_name=True,
enabled=False,
write_frequency="turn",
)
def _unpinned(self) -> HonchoClientConfig:
return HonchoClientConfig(
api_key="k",
peer_name="Igor",
pin_peer_name=False,
enabled=False,
write_frequency="turn",
)
def test_fresh_manager_after_flip_resolves_to_runtime(self):
pinned_mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._pinned(),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(pinned_mgr)
before = pinned_mgr.get_or_create("telegram:86701400")
assert before.user_peer_id == "Igor"
unpinned_mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._unpinned(),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(unpinned_mgr)
after = unpinned_mgr.get_or_create("telegram:86701400")
assert after.user_peer_id == "86701400", (
"After flipping pinPeerName off, the same runtime ID must resolve "
"to its own peer — otherwise multi-user mode silently merges users."
)
def test_cached_session_survives_config_flip_in_same_manager(self):
mgr = HonchoSessionManager(
honcho=MagicMock(),
config=self._pinned(),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr)
first = mgr.get_or_create("telegram:86701400")
assert first.user_peer_id == "Igor"
mgr._config = self._unpinned()
second = mgr.get_or_create("telegram:86701400")
assert second.user_peer_id == "Igor", (
"The per-key session cache is keyed by session-key, not by "
"resolved peer. In-process flips don't invalidate it — the "
"gateway cache must bust the whole manager instead."
)
def test_cache_busting_signature_reflects_pin_peer_name(self, tmp_path, monkeypatch):
"""Gateway agent cache must bust when honcho.json's pinPeerName flips."""
from gateway.run import GatewayRunner
cfg_path = tmp_path / "honcho.json"
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
cfg_path.write_text(json.dumps({"apiKey": "k", "peerName": "Igor", "pinPeerName": True}))
sig_pinned = GatewayRunner._extract_cache_busting_config({"memory": {"provider": "honcho"}})
cfg_path.write_text(json.dumps({"apiKey": "k", "peerName": "Igor", "pinPeerName": False}))
sig_unpinned = GatewayRunner._extract_cache_busting_config({"memory": {"provider": "honcho"}})
assert sig_pinned["honcho.pin_peer_name"] != sig_unpinned["honcho.pin_peer_name"]
def test_cache_busting_signature_reflects_user_peer_aliases(self, tmp_path, monkeypatch):
from gateway.run import GatewayRunner
cfg_path = tmp_path / "honcho.json"
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
cfg_path.write_text(json.dumps({"apiKey": "k", "peerName": "Igor"}))
sig_no_aliases = GatewayRunner._extract_cache_busting_config({"memory": {"provider": "honcho"}})
cfg_path.write_text(json.dumps({
"apiKey": "k",
"peerName": "Igor",
"userPeerAliases": {"86701400": "Igor"},
}))
sig_with_aliases = GatewayRunner._extract_cache_busting_config({"memory": {"provider": "honcho"}})
assert sig_no_aliases["honcho.user_peer_aliases"] != sig_with_aliases["honcho.user_peer_aliases"]
def test_cache_busting_signature_reflects_runtime_peer_prefix(self, tmp_path, monkeypatch):
from gateway.run import GatewayRunner
cfg_path = tmp_path / "honcho.json"
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
cfg_path.write_text(json.dumps({"apiKey": "k", "peerName": "Igor"}))
sig_no_prefix = GatewayRunner._extract_cache_busting_config({"memory": {"provider": "honcho"}})
cfg_path.write_text(json.dumps({
"apiKey": "k",
"peerName": "Igor",
"runtimePeerPrefix": "telegram_",
}))
sig_with_prefix = GatewayRunner._extract_cache_busting_config({"memory": {"provider": "honcho"}})
assert sig_no_prefix["honcho.runtime_peer_prefix"] != sig_with_prefix["honcho.runtime_peer_prefix"]
def test_cache_busting_signature_reflects_ai_peer(self, tmp_path, monkeypatch):
"""Editing ``aiPeer`` mid-flight must invalidate the cached agent.
``HonchoSessionManager`` freezes ``cfg.ai_peer`` at construction —
without busting here, assistant writes keep landing on the old
peer until an unrelated cache eviction.
"""
from gateway.run import GatewayRunner
cfg_path = tmp_path / "honcho.json"
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
cfg_path.write_text(json.dumps({
"apiKey": "k",
"peerName": "Igor",
"aiPeer": "hermes",
}))
sig_before = GatewayRunner._extract_cache_busting_config({"memory": {"provider": "honcho"}})
cfg_path.write_text(json.dumps({
"apiKey": "k",
"peerName": "Igor",
"aiPeer": "hermetika",
}))
sig_after = GatewayRunner._extract_cache_busting_config({"memory": {"provider": "honcho"}})
assert sig_before["honcho.ai_peer"] != sig_after["honcho.ai_peer"]
class TestProfilePeerUniqueness:
"""Each Hermes profile can pin to its own unique peerName.
Profile cloning copies host blocks, but operators routinely diverge them
afterwards (e.g. `hermes -p partner` pinned to a different person's peer).
The resolver must honor host-level ``peerName`` so two profiles in the
same workspace stay scoped to different Honcho peers.
"""
def _pinned_to(self, name: str) -> HonchoClientConfig:
return HonchoClientConfig(
api_key="k",
peer_name=name,
pin_peer_name=True,
enabled=False,
write_frequency="turn",
)
def test_two_profiles_pinned_to_different_peer_names_resolve_distinctly(self):
mgr_a = HonchoSessionManager(
honcho=MagicMock(),
config=self._pinned_to("alice"),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr_a)
sess_a = mgr_a.get_or_create("telegram:86701400")
mgr_b = HonchoSessionManager(
honcho=MagicMock(),
config=self._pinned_to("bob"),
runtime_user_peer_name="86701400",
)
_patch_manager_for_resolution_test(mgr_b)
sess_b = mgr_b.get_or_create("telegram:86701400")
assert sess_a.user_peer_id == "alice"
assert sess_b.user_peer_id == "bob"
assert sess_a.user_peer_id != sess_b.user_peer_id, (
"Profiles pinned to distinct peer names must not collapse to "
"the same Honcho peer — otherwise profile isolation is fictional."
)
def test_host_peer_name_overrides_root_when_pinned(self, tmp_path, monkeypatch):
"""Host-level peerName wins so each profile can pin uniquely while
sharing a single root-level apiKey and workspace.
"""
config_file = tmp_path / "honcho.json"
config_file.write_text(json.dumps({
"apiKey": "k",
"peerName": "default-user",
"hosts": {
"hermes.partner": {
"peerName": "partner-user",
"pinPeerName": True,
},
},
}))
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "isolated"))
cfg = HonchoClientConfig.from_global_config(
host="hermes.partner", config_path=config_file,
)
assert cfg.peer_name == "partner-user"
assert cfg.pin_peer_name is True
File diff suppressed because it is too large Load Diff