The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(honcho): trim the peer mapping tests to one case per behavior
Erosikab1987ee51590
diff --git a/tests/honcho_plugin/test_cli.py b/tests/honcho_plugin/test_cli.pyindex b4ff74fc1ba..25d8380b081 100644--- a/tests/honcho_plugin/test_cli.py+++ b/tests/honcho_plugin/test_cli.py@@ -501,17 +501,8 @@ class TestSetupWizardDeploymentShape:def test_mapping_step_points_at_peers_map(self, monkeypatch, tmp_path, capsys):- answers = [- "cloud", # deployment- "", # api key (keep)- "eri", # peer name- "hermetika", # ai peer- "hermes", # workspace- "s", # tree: skip- ]- self._run_setup(monkeypatch, tmp_path, answers=answers)- out = capsys.readouterr().out- assert "hermes honcho peers map" in out+ self._run_setup(monkeypatch, tmp_path, answers=["cloud", "", "eri", "hermetika", "hermes", "s"])+ assert "hermes honcho peers map" in capsys.readouterr().outdef test_host_pin_user_peer_true_is_detected_as_single(self, monkeypatch, tmp_path):"""Host-level ``pinUserPeer: true`` must classify as ``single``.@@ -552,27 +543,15 @@ class TestSetupWizardDeploymentShape:# operator edits live on the host block they're inspecting.assert host["userPeerAliases"] == {"7654321": "eri"}- def test_fresh_config_defaults_to_single(self, monkeypatch, tmp_path):- """No identity key anywhere → the choice prompt defaults to [1].-- A solo operator pressing Enter gets the pinned personal shape- instead of silently fragmenting their gateway account away from- peerName's history.- """- answers = ["cloud", "", "eri", "hermetika", "hermes"]- host = self._run_setup(monkeypatch, tmp_path, answers=answers)- assert host["pinUserPeer"] is True-- def test_configured_multi_still_defaults_to_multi(self, monkeypatch, tmp_path):- """An explicit pinUserPeer: false config keeps [3] as its default —- the fresh-config [1] default must not override a chosen shape."""- initial_cfg = {- "apiKey": "***",- "hosts": {"hermes": {"pinUserPeer": False, "peerName": "eri"}},- }+ @pytest.mark.parametrize("initial_cfg, expected_pin", [+ (None, True),+ ({"apiKey": "***", "hosts": {"hermes": {"pinUserPeer": False, "peerName": "eri"}}}, False),+ ], ids=["fresh-config-defaults-to-single", "configured-multi-keeps-multi"])+ def test_choice_default_follows_config(self, monkeypatch, tmp_path, initial_cfg, expected_pin):+ """Enter on a fresh config picks the pinned personal shape; a chosen shape stays the default."""answers = ["cloud", "", "eri", "hermetika", "hermes"]host = self._run_setup(monkeypatch, tmp_path, answers=answers, initial_cfg=initial_cfg)- assert host["pinUserPeer"] is False+ assert host["pinUserPeer"] is expected_pindef test_no_gateway_connected_skips_mapping_when_declined(self, monkeypatch, tmp_path):diff --git a/tests/honcho_plugin/test_peers_map.py b/tests/honcho_plugin/test_peers_map.pyindex 4ca96abdc60..45aeca17037 100644--- a/tests/honcho_plugin/test_peers_map.py+++ b/tests/honcho_plugin/test_peers_map.py@@ -1,20 +1,13 @@-"""Tests for ``hermes honcho peers map``.--The command lists gateway accounts recorded in state.db (the gateway stamps-each session row with its routing peer) and interactively edits-``userPeerAliases``. Discovery, the resolution preview, and the write-level-rules (host block vs root cascade) are covered here.-"""+"""Tests for ``hermes honcho peers map``: account discovery, the resolution preview, and alias writes."""import jsonimport sqlite3from types import SimpleNamespace+import pytest+import plugins.memory.honcho.cli as honcho_cli-from plugins.memory.honcho.cli import (- _preview_peer_resolution,- _seen_gateway_accounts,-)+from plugins.memory.honcho.cli import _preview_peer_resolution, _seen_gateway_accountsdef _make_state_db(path, rows):@@ -22,273 +15,144 @@ def _make_state_db(path, rows):conn = sqlite3.connect(path)conn.execute("""CREATE TABLE sessions (- id TEXT PRIMARY KEY,- source TEXT,- user_id TEXT,- session_key TEXT,- display_name TEXT,- origin_json TEXT,- started_at REAL+ id TEXT PRIMARY KEY, source TEXT, user_id TEXT, session_key TEXT,+ display_name TEXT, origin_json TEXT, started_at REAL)""")- conn.executemany(- "INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, ?)", rows,- )+ conn.executemany("INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, ?)", rows)conn.commit()conn.close()def _origin(user_name=None, is_bot=False, user_id_alt=None):- return json.dumps({- "user_name": user_name, "is_bot": is_bot, "user_id_alt": user_id_alt,- })+ return json.dumps({"user_name": user_name, "is_bot": is_bot, "user_id_alt": user_id_alt})-class TestSeenGatewayAccounts:- def test_groups_rows_by_platform_and_user(self, tmp_path):- db = tmp_path / "state.db"- _make_state_db(db, [- ("s1", "telegram", "111", "telegram:dm:111", "Eri", _origin("eri"), 100.0),- ("s2", "telegram", "111", "telegram:dm:111", "Eri", _origin("eri"), 200.0),- ("s3", "discord", "222", "discord:dm:222", "Tek", _origin("teknium"), 50.0),- ])- accounts = _seen_gateway_accounts(db)- assert len(accounts) == 2- assert accounts[0] == {- "platform": "telegram", "user_id": "111", "user_id_alt": "",- "label": "eri", "sessions": 2, "profiles": [],- }- assert accounts[1]["user_id"] == "222"-- def test_orders_most_recent_first(self, tmp_path):- db = tmp_path / "state.db"- _make_state_db(db, [- ("s1", "telegram", "111", "k1", None, None, 100.0),- ("s2", "discord", "222", "k2", None, None, 900.0),- ])- accounts = _seen_gateway_accounts(db)- assert [a["user_id"] for a in accounts] == ["222", "111"]+def _row(user_id, platform="telegram", name="eri", started=100.0):+ return (f"s{user_id}", platform, user_id, "k", None, _origin(name), started)- def test_skips_bots_and_rows_without_identity(self, tmp_path):- db = tmp_path / "state.db"- _make_state_db(db, [- ("s1", "discord", "333", "k1", "Bot", _origin("webhook", is_bot=True), 100.0),- ("s2", "cli", None, None, None, None, 100.0),- ("s3", "telegram", "111", "k2", None, _origin("eri"), 100.0),- ])- accounts = _seen_gateway_accounts(db)- assert [a["user_id"] for a in accounts] == ["111"]- def test_legacy_rows_without_session_key_still_count(self, tmp_path):- """Gateway rows written before session_key was stamped are still accounts."""- db = tmp_path / "state.db"- _make_state_db(db, [- ("s1", "telegram", "111", None, "Eri", None, 100.0),- ("s2", "telegram", "111", "", "Eri", None, 200.0),- ])- accounts = _seen_gateway_accounts(db)- assert [a["user_id"] for a in accounts] == ["111"]- assert accounts[0]["sessions"] == 2+def _cfg(root=None, **host):+ return {"apiKey": "***", **(root or {}), "hosts": {"hermes": host}}- def test_label_falls_back_to_display_name(self, tmp_path):++class TestSeenGatewayAccounts:+ def test_groups_orders_and_filters_rows(self, tmp_path):db = tmp_path / "state.db"_make_state_db(db, [- ("s1", "telegram", "111", "k1", "Eri DM", None, 100.0),+ ("s1", "telegram", "111", None, "Eri", _origin("eri"), 100.0), # predates session_key+ ("s2", "telegram", "111", "", "Eri", _origin("eri"), 200.0),+ ("s3", "discord", "222", "k2", "Tek DM", None, 900.0),+ ("s4", "discord", "333", "k3", "Bot", _origin("webhook", is_bot=True), 950.0),+ ("s5", "cli", None, None, None, None, 999.0),])- accounts = _seen_gateway_accounts(db)- assert accounts[0]["label"] == "Eri DM"+ assert _seen_gateway_accounts(db) == [+ {"platform": "discord", "user_id": "222", "user_id_alt": "", "label": "Tek DM", "sessions": 1, "profiles": []},+ {"platform": "telegram", "user_id": "111", "user_id_alt": "", "label": "eri", "sessions": 2, "profiles": []},+ ]- def test_missing_db_returns_empty(self, tmp_path):+ def test_missing_db_or_table_returns_empty(self, tmp_path):assert _seen_gateway_accounts(tmp_path / "absent.db") == []-- def test_db_without_sessions_table_returns_empty(self, tmp_path):- db = tmp_path / "state.db"- sqlite3.connect(db).close()- assert _seen_gateway_accounts(db) == []---class TestPreviewPeerResolution:- def test_pin_wins_over_alias(self):- out = _preview_peer_resolution(- "111", pin=True, aliases={"111": "alice"}, prefix="tg_", peer_name="eri",- )- assert out == "eri (pinned)"-- def test_pin_without_peer_name_falls_through(self):- out = _preview_peer_resolution(- "111", pin=True, aliases={}, prefix="", peer_name="",- )- assert out == "111"-- def test_alias_hit(self):- out = _preview_peer_resolution(- "111", pin=False, aliases={"111": "alice"}, prefix="tg_", peer_name="eri",- )- assert out == "alice"-- def test_prefix_for_unknown_id(self):- out = _preview_peer_resolution(- "111", pin=False, aliases={}, prefix="tg_", peer_name="eri",- )- assert out == "tg_111 (prefixed)"-- def test_raw_sanitized_fallback(self):- out = _preview_peer_resolution(- "@you:matrix.org", pin=False, aliases={}, prefix="", peer_name="",- )- assert out == "-you-matrix-org"-- def test_alt_id_alias_hit(self):- out = _preview_peer_resolution(- "device-777", pin=False, aliases={"uuid-abc": "eri"}, prefix="",- peer_name="", user_id_alt="uuid-abc",- )- assert out == "eri"-- def test_primary_alias_wins_over_alt(self):- out = _preview_peer_resolution(- "111", pin=False, aliases={"111": "alice", "uuid-abc": "bob"},- prefix="", peer_name="", user_id_alt="uuid-abc",- )- assert out == "alice"+ sqlite3.connect(tmp_path / "empty.db").close()+ assert _seen_gateway_accounts(tmp_path / "empty.db") == []++[email protected]("user_id, kwargs, expected", [+ ("111", dict(pin=True, aliases={"111": "alice"}, prefix="tg_", peer_name="eri"), "eri (pinned)"),+ ("111", dict(pin=True, aliases={}, prefix="", peer_name=""), "111"),+ ("111", dict(pin=False, aliases={"111": "alice"}, prefix="tg_", peer_name="eri"), "alice"),+ ("111", dict(pin=False, aliases={}, prefix="tg_", peer_name="eri"), "tg_111 (prefixed)"),+ ("@you:matrix.org", dict(pin=False, aliases={}, prefix="", peer_name=""), "-you-matrix-org"),+ ("device-777", dict(pin=False, aliases={"uuid-abc": "eri"}, prefix="", peer_name="", user_id_alt="uuid-abc"), "eri"),+ ("111", dict(pin=False, aliases={"111": "alice", "uuid-abc": "bob"}, prefix="", peer_name="", user_id_alt="uuid-abc"),+ "alice"),+], ids=["pin-wins", "pin-without-peer-name", "alias", "prefix", "raw-sanitized", "alt-id-alias", "primary-alias-over-alt"])+def test_preview_peer_resolution(user_id, kwargs, expected):+ assert _preview_peer_resolution(user_id, **kwargs) == expected+++def _run_map(monkeypatch, tmp_path, *, answers, cfg, db_rows=(), ws_peers=None, workspaces=None):+ """Drive cmd_peers_map with scripted answers; returns what _write_config received."""+ db = tmp_path / "state.db"+ if db_rows:+ _make_state_db(db, list(db_rows))+ written = {}+ answer_iter = iter(answers)+ # One profile per host block: "hermes" is default, "hermes.<name>" is profile <name>.+ profiles = [("default" if k == "hermes" else k.removeprefix("hermes."), k, v) for k, v in cfg["hosts"].items()]+ # API seams are offline unless ws_peers is given, then a sentinel client stands in.+ client = object() if ws_peers is not None else None+ for name, value in {+ "_read_config": lambda: cfg,+ "_host_key": lambda: "hermes",+ "_active_profile_name": lambda: "default",+ "_state_db_path": lambda: db,+ "_local_config_path": lambda: tmp_path / "honcho.json",+ "_write_config": lambda c, path=None: written.update({"cfg": c}),+ "_all_profile_host_configs": lambda: profiles,+ "_peers_map_client": lambda workspace=None: (client, SimpleNamespace(workspace_id="hermes") if client else None),+ "_api_workspace_peers": lambda c: list(ws_peers) if c is not None and ws_peers is not None else None,+ "_api_workspaces": lambda c: list(workspaces) if workspaces is not None else None,+ "_api_peer_detail": lambda c, pid: f"(card of {pid})",+ "_prompt": lambda label, default=None, secret=False: next(answer_iter, default or ""),+ }.items():+ monkeypatch.setattr(honcho_cli, name, value)+ honcho_cli.cmd_peers_map(SimpleNamespace())+ return writtenclass TestCmdPeersMap:- def _run(self, monkeypatch, tmp_path, *, answers, cfg, db_rows=(),- ws_peers=None, workspaces=None, profiles=None):- db = tmp_path / "state.db"- if db_rows:- _make_state_db(db, list(db_rows))-- written = {}- monkeypatch.setattr(honcho_cli, "_read_config", lambda: cfg)- monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")- monkeypatch.setattr(honcho_cli, "_active_profile_name", lambda: "default")- monkeypatch.setattr(honcho_cli, "_state_db_path", lambda: db)- monkeypatch.setattr(honcho_cli, "_local_config_path", lambda: tmp_path / "honcho.json")- monkeypatch.setattr(- honcho_cli, "_write_config",- lambda c, path=None: written.update({"cfg": c}),- )- monkeypatch.setattr(- honcho_cli, "_all_profile_host_configs",- lambda: profiles if profiles is not None- else [("default", "hermes", (cfg.get("hosts") or {}).get("hermes", {}))],- )- # API seams: offline by default; a fake client sentinel when ws_peers given.- fake_client = object() if ws_peers is not None else None-- class _FakeCfg:- workspace_id = "hermes"- monkeypatch.setattr(- honcho_cli, "_peers_map_client",- lambda workspace=None: (fake_client, _FakeCfg() if fake_client else None),- )- monkeypatch.setattr(- honcho_cli, "_api_workspace_peers",- lambda client: list(ws_peers) if client is not None and ws_peers is not None else None,- )- monkeypatch.setattr(- honcho_cli, "_api_workspaces",- lambda client: list(workspaces) if workspaces is not None else None,- )- monkeypatch.setattr(- honcho_cli, "_api_peer_detail",- lambda client, pid: f"(card of {pid})",- )-- 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_peers_map(SimpleNamespace())- return written-- def test_maps_seen_account_to_host_block(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- rows = [("s1", "telegram", "111", "k1", None, _origin("eri"), 100.0)]- written = self._run(- monkeypatch, tmp_path,- answers=["1", "eri", ""],- cfg=cfg, db_rows=rows,- )+ @pytest.mark.parametrize("cfg, answers, kwargs", [+ (_cfg(peerName="eri"), ["1", "eri", ""], dict(db_rows=[_row("111")])),+ (_cfg(), ["111", "eri", ""], {}),+ (_cfg(peerName="eri"), ["1", "p1", ""], dict(db_rows=[_row("111")], ws_peers=["eri", "hermes"])),+ (_cfg(pinUserPeer=True, peerName="eri"), ["y", "111", "eri", ""], {}),+ ], ids=["account-number", "typed-runtime-id", "picked-from-peers-table", "pinned-but-accepted"])+ def test_writes_alias_to_host_block(self, monkeypatch, tmp_path, cfg, answers, kwargs):+ written = _run_map(monkeypatch, tmp_path, answers=answers, cfg=cfg, **kwargs)assert written["cfg"]["hosts"]["hermes"]["userPeerAliases"] == {"111": "eri"}- def test_raw_runtime_id_entry(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {}}}- written = self._run(- monkeypatch, tmp_path,- answers=["7654321", "eri", ""],- cfg=cfg,- )- assert written["cfg"]["hosts"]["hermes"]["userPeerAliases"] == {"7654321": "eri"}-- def test_clear_alias_with_dash(self, monkeypatch, tmp_path):- cfg = {- "apiKey": "***",- "hosts": {"hermes": {"userPeerAliases": {"111": "eri", "222": "tek"}}},- }- written = self._run(- monkeypatch, tmp_path,- answers=["111", "-", ""],- cfg=cfg,- )- assert written["cfg"]["hosts"]["hermes"]["userPeerAliases"] == {"222": "tek"}-- def test_clearing_last_alias_removes_key(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {"userPeerAliases": {"111": "eri"}}}}- written = self._run(- monkeypatch, tmp_path,- answers=["111", "-", ""],- cfg=cfg,- )- assert "userPeerAliases" not in written["cfg"]["hosts"]["hermes"]-- def test_root_sourced_aliases_write_back_to_root(self, monkeypatch, tmp_path):- cfg = {- "apiKey": "***",- "userPeerAliases": {"111": "eri"},- "hosts": {"hermes": {}},- }- written = self._run(- monkeypatch, tmp_path,- answers=["222", "tek", ""],- cfg=cfg,- )- assert written["cfg"]["userPeerAliases"] == {"111": "eri", "222": "tek"}- assert "userPeerAliases" not in written["cfg"]["hosts"]["hermes"]-- def test_no_changes_no_write(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {}}}- written = self._run(monkeypatch, tmp_path, answers=[""], cfg=cfg)- assert written == {}-- def test_keeping_current_value_is_not_a_change(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {"userPeerAliases": {"111": "eri"}}}}- written = self._run(- monkeypatch, tmp_path,- answers=["111", "eri", ""],- cfg=cfg,- )- assert written == {}-- def test_pinned_declined_exits_without_write(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {"pinUserPeer": True, "peerName": "eri"}}}- written = self._run(monkeypatch, tmp_path, answers=["n"], cfg=cfg)- assert written == {}-- def test_pinned_accepted_still_edits_aliases(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {"pinUserPeer": True, "peerName": "eri"}}}- written = self._run(- monkeypatch, tmp_path,- answers=["y", "111", "eri", ""],- cfg=cfg,- )- assert written["cfg"]["hosts"]["hermes"]["userPeerAliases"] == {"111": "eri"}+ @pytest.mark.parametrize("aliases, expected_host", [+ ({"111": "eri", "222": "tek"}, {"userPeerAliases": {"222": "tek"}}),+ ({"111": "eri"}, {}),+ ], ids=["one-of-two", "last-alias-drops-key"])+ def test_dash_clears_alias(self, monkeypatch, tmp_path, aliases, expected_host):+ written = _run_map(monkeypatch, tmp_path, answers=["111", "-", ""], cfg=_cfg(userPeerAliases=aliases))+ assert written["cfg"]["hosts"]["hermes"] == expected_host++ @pytest.mark.parametrize("cfg, answers, kwargs", [+ (_cfg(), [""], {}),+ (_cfg(userPeerAliases={"111": "eri"}), ["111", "eri", ""], {}),+ (_cfg(pinUserPeer=True, peerName="eri"), ["n"], {}),+ (_cfg(peerName="eri"), ["w", "2", "n", ""], dict(ws_peers=["eri"], workspaces=["hermes", "cosmania-dex"])),+ ], ids=["nothing-entered", "kept-current-value", "pinned-declined", "workspace-switch-declined"])+ def test_nothing_changed_writes_nothing(self, monkeypatch, tmp_path, cfg, answers, kwargs):+ assert _run_map(monkeypatch, tmp_path, answers=answers, cfg=cfg, **kwargs) == {}++ @pytest.mark.parametrize("cfg, answers, kwargs, expected", [+ (_cfg(peerName="eri"), ["1", "fresh-name", ""], dict(db_rows=[_row("111", name="bob")], ws_peers=["eri", "111"]),+ ["'fresh-name' is a new peer", "peer '111' keeps its existing history"]),+ (_cfg(peerName="eri"), [""], dict(db_rows=[_row("111"), _row("222", "discord", "b", 50.0)], ws_peers=["eri", "111"]),+ ["111 ✓", "222 ○ new"]),+ (_cfg(), ["7654321", "eri", ""], {}, ["peers unavailable"]),+ (_cfg(peerName="eri"), ["p2", ""], dict(ws_peers=["eri", "meow"]), ["(card of meow)"]),+ (_cfg(peerName="eri"), [""], dict(ws_peers=[]), ["No peers here yet", "Wrong workspace?"]),+ (_cfg(peerName="eri"), [""], dict(ws_peers=["stranger1", "stranger2"]),+ ["None of these match your configured identity"]),+ ({"apiKey": "***", "userPeerAliases": {},+ "hosts": {"hermes": {"workspace": "hermes"}, "hermes.dreamer": {"workspace": "dreamland"}}},+ ["222", "tek", "", "all"], {}, ["also apply in workspace 'dreamland'"]),+ ({"apiKey": "***", "hosts": {"hermes": {"peerName": "eri", "userPeerAliases": {"111": "eri"}},+ "hermes.dreamer": {"peerName": "eri", "userPeerAliases": {"111": "bob"}}}},+ [""], dict(db_rows=[_row("111", name="x")]), ["≠ dreamer→bob"]),+ ], ids=["new-peer-and-history-consequences", "exists-markers", "offline-typed-targets", "inspect-peer-card",+ "empty-workspace-hint", "unrecognized-workspace-hint", "cross-workspace-root-write-warns",+ "sibling-divergence-marked"])+ def test_view_and_consequence_messages(self, monkeypatch, tmp_path, capsys, cfg, answers, kwargs, expected):+ _run_map(monkeypatch, tmp_path, answers=answers, cfg=cfg, **kwargs)+ out = capsys.readouterr().out+ for text in expected:+ assert text in outdef test_peers_dispatches_map_action(self, monkeypatch):called = {}@@ -296,103 +160,17 @@ class TestCmdPeersMap:honcho_cli.cmd_peers(SimpleNamespace(peers_action="map"))assert called == {"map": True}- def test_target_picked_from_workspace_peers(self, monkeypatch, tmp_path):- """'p1' as the target resolves to the first workspace peer's id."""- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- rows = [("s1", "telegram", "111", "k1", None, _origin("eri"), 100.0)]- written = self._run(- monkeypatch, tmp_path,- answers=["1", "p1", ""],- cfg=cfg, db_rows=rows, ws_peers=["eri", "hermes"],- )- assert written["cfg"]["hosts"]["hermes"]["userPeerAliases"] == {"111": "eri"}-- def test_new_peer_and_history_consequences_printed(self, monkeypatch, tmp_path, capsys):- """Mapping onto a name not in the workspace warns about peer creation,- and moving an account off its existing runtime peer names the history- that stays behind."""- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- rows = [("s1", "telegram", "111", "k1", None, _origin("bob"), 100.0)]- self._run(- monkeypatch, tmp_path,- answers=["1", "fresh-name", ""],- cfg=cfg, db_rows=rows, ws_peers=["eri", "111"],- )- out = capsys.readouterr().out- assert "'fresh-name' is a new peer" in out- assert "peer '111' keeps its existing history" in out-- def test_exists_markers_in_accounts_table(self, monkeypatch, tmp_path, capsys):- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- rows = [- ("s1", "telegram", "111", "k1", None, _origin("a"), 100.0),- ("s2", "discord", "222", "k2", None, _origin("b"), 50.0),- ]- self._run(- monkeypatch, tmp_path, answers=[""],- cfg=cfg, db_rows=rows, ws_peers=["eri", "111"],- )- import re- out = capsys.readouterr().out- line_111 = next(ln for ln in out.splitlines() if re.match(r"\s+\d+\s+telegram\s", ln))- line_222 = next(ln for ln in out.splitlines() if re.match(r"\s+\d+\s+discord\s", ln))- assert "✓" in line_111- assert "○ new" in line_222-- def test_offline_degrades_to_typed_targets(self, monkeypatch, tmp_path, capsys):- cfg = {"apiKey": "***", "hosts": {"hermes": {}}}- written = self._run(- monkeypatch, tmp_path,- answers=["7654321", "eri", ""],- cfg=cfg, ws_peers=None,- )- out = capsys.readouterr().out- assert "peers unavailable" in out- assert written["cfg"]["hosts"]["hermes"]["userPeerAliases"] == {"7654321": "eri"}-- def test_inspect_peer_prints_card(self, monkeypatch, tmp_path, capsys):- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- self._run(- monkeypatch, tmp_path, answers=["p2", ""],- cfg=cfg, ws_peers=["eri", "meow"],- )- out = capsys.readouterr().out- assert "(card of meow)" in out-- def test_empty_workspace_hints_at_workspace_list(self, monkeypatch, tmp_path, capsys):- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- self._run(monkeypatch, tmp_path, answers=[""], cfg=cfg, ws_peers=[])- out = capsys.readouterr().out- assert "No peers here yet" in out- assert "Wrong workspace?" in out-- def test_unrecognized_workspace_hints_wrong_workspace(self, monkeypatch, tmp_path, capsys):- """Peers exist but none match local identity → wrong-workspace hint."""- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- self._run(- monkeypatch, tmp_path, answers=[""],- cfg=cfg, ws_peers=["stranger1", "stranger2"],- )- out = capsys.readouterr().out- assert "None of these match your configured identity" in out-class TestWorkspaceSwitch:- _run = TestCmdPeersMap._run-def test_browse_and_confirmed_switch_writes_workspace(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- written = self._run(- monkeypatch, tmp_path,- answers=["w", "2", "y", ""],- cfg=cfg, ws_peers=["eri"], workspaces=["hermes", "cosmania-dex"],+ written = _run_map(+ monkeypatch, tmp_path, answers=["w", "2", "y", ""],+ cfg=_cfg(peerName="eri"), ws_peers=["eri"], workspaces=["hermes", "cosmania-dex"],)assert written["cfg"]["hosts"]["hermes"]["workspace"] == "cosmania-dex"def test_browse_client_is_built_for_the_browsed_workspace(self, monkeypatch):- """The browse client must carry the browsed workspace, not the configured one.- get_honcho_client keys its cache on workspace_id, so this is what keeps a browse- from reusing the profile's own client."""+ """get_honcho_client keys its cache on workspace_id, so a browse must not reuse the profile's client."""import plugins.memory.honcho.client as client_modseen = []@@ -409,129 +187,45 @@ class TestWorkspaceSwitch:assert browsed.workspace_id == "cosmania-dex"assert [c.workspace_id for c in seen] == ["hermes", "cosmania-dex"]- def test_declined_switch_leaves_config_untouched(self, monkeypatch, tmp_path):- cfg = {"apiKey": "***", "hosts": {"hermes": {"peerName": "eri"}}}- written = self._run(- monkeypatch, tmp_path,- answers=["w", "2", "n", ""],- cfg=cfg, ws_peers=["eri"], workspaces=["hermes", "cosmania-dex"],- )- assert written == {}-class TestSaveScope:- _run = TestCmdPeersMap._run-- def _multi_profiles(self, cfg):- hosts = cfg.get("hosts") or {}- return [- ("default", "hermes", hosts.get("hermes", {})),- ("dreamer", "hermes.dreamer", hosts.get("hermes.dreamer", {})),- ]-- def test_root_sourced_multi_profile_prompts_scope_all(self, monkeypatch, tmp_path):- cfg = {- "apiKey": "***",- "userPeerAliases": {"111": "eri"},- "hosts": {"hermes": {}, "hermes.dreamer": {}},- }- written = self._run(- monkeypatch, tmp_path,- answers=["222", "tek", "", "all"],- cfg=cfg, profiles=self._multi_profiles(cfg),- )+ @pytest.mark.parametrize("hosts, answers", [+ ({"hermes": {}}, ["222", "tek", ""]),+ ({"hermes": {}, "hermes.dreamer": {}}, ["222", "tek", "", "all"]),+ ], ids=["single-profile-no-prompt", "multi-profile-all"])+ def test_root_sourced_aliases_write_back_to_root(self, monkeypatch, tmp_path, hosts, answers):+ cfg = {"apiKey": "***", "userPeerAliases": {"111": "eri"}, "hosts": hosts}+ written = _run_map(monkeypatch, tmp_path, answers=answers, cfg=cfg)assert written["cfg"]["userPeerAliases"] == {"111": "eri", "222": "tek"}assert "userPeerAliases" not in written["cfg"]["hosts"]["hermes"]- def test_root_sourced_multi_profile_scope_this_forks_host(self, monkeypatch, tmp_path):- cfg = {- "apiKey": "***",- "userPeerAliases": {"111": "eri"},- "hosts": {"hermes": {}, "hermes.dreamer": {}},- }- written = self._run(- monkeypatch, tmp_path,- answers=["222", "tek", "", "this"],- cfg=cfg, profiles=self._multi_profiles(cfg),- )- assert written["cfg"]["hosts"]["hermes"]["userPeerAliases"] == {- "111": "eri", "222": "tek",- }- # Root map stays as the other profiles' baseline.- assert written["cfg"]["userPeerAliases"] == {"111": "eri"}-- def test_cross_workspace_root_write_warns(self, monkeypatch, tmp_path, capsys):- cfg = {- "apiKey": "***",- "userPeerAliases": {},- "hosts": {- "hermes": {"workspace": "hermes"},- "hermes.dreamer": {"workspace": "dreamland"},- },- }- self._run(- monkeypatch, tmp_path,- answers=["222", "tek", "", "all"],- cfg=cfg, profiles=self._multi_profiles(cfg),- )- out = capsys.readouterr().out- assert "also apply in workspace 'dreamland'" in out-- def test_sibling_divergence_marked(self, monkeypatch, tmp_path, capsys):- """A sibling profile resolving the same account differently is shown."""- cfg = {- "apiKey": "***",- "hosts": {- "hermes": {"peerName": "eri", "userPeerAliases": {"111": "eri"}},- "hermes.dreamer": {"peerName": "eri", "userPeerAliases": {"111": "bob"}},- },- }- rows = [("s1", "telegram", "111", "k1", None, _origin("x"), 100.0)]- self._run(- monkeypatch, tmp_path, answers=[""],- cfg=cfg, db_rows=rows, profiles=self._multi_profiles(cfg),- )- out = capsys.readouterr().out- assert "≠ dreamer→bob" in out---class TestClassifyWorkspacePeers:- def test_labels_from_local_config(self, monkeypatch):- monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")- monkeypatch.setattr(- honcho_cli, "_all_profile_host_configs",- lambda: [- ("default", "hermes", {"peerName": "eri", "aiPeer": "hermetika"}),- ("dreamer", "hermes.dreamer", {"aiPeer": "dreamer-ai"}),- ],- )- cfg = {- "peerName": "eri",- "hosts": {"claude_code": {"aiPeer": "clawd"}},- }- accounts = [{"platform": "telegram", "user_id": "7654321", "user_id_alt": ""}]- labels = honcho_cli._classify_workspace_peers(- ["eri", "hermetika", "dreamer-ai", "clawd", "7654321",- "user-default-root", "meow"],- cfg, accounts, {"999": "friend"}, "",- )- assert labels["eri"] == "your peer (peerName)"- assert labels["hermetika"] == "AI peer · this profile"- assert labels["dreamer-ai"] == "AI peer · profile dreamer"- assert labels["clawd"] == "AI peer of app 'claude_code'"- assert labels["7654321"] == "runtime peer · telegram 7654321"- assert labels["user-default-root"] == "fallback peer (pre-identity traffic)"- assert labels["meow"] == "unrecognized"-- def test_alias_targets_and_prefix_recognized(self, monkeypatch):- monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")- monkeypatch.setattr(- honcho_cli, "_all_profile_host_configs",- lambda: [("default", "hermes", {})],- )- accounts = [{"platform": "telegram", "user_id": "42", "user_id_alt": ""}]- labels = honcho_cli._classify_workspace_peers(- ["friend", "tg_42"], {}, accounts, {"999": "friend"}, "tg_",- )- assert labels["friend"] == "alias target"- assert labels["tg_42"] == "runtime peer · telegram 42"+ def test_scope_this_forks_host_block(self, monkeypatch, tmp_path):+ cfg = {"apiKey": "***", "userPeerAliases": {"111": "eri"}, "hosts": {"hermes": {}, "hermes.dreamer": {}}}+ written = _run_map(monkeypatch, tmp_path, answers=["222", "tek", "", "this"], cfg=cfg)+ assert written["cfg"]["hosts"]["hermes"]["userPeerAliases"] == {"111": "eri", "222": "tek"}+ assert written["cfg"]["userPeerAliases"] == {"111": "eri"} # root stays the other profiles' baseline+++def test_classify_workspace_peers_labels_from_local_config(monkeypatch):+ monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")+ monkeypatch.setattr(honcho_cli, "_all_profile_host_configs", lambda: [+ ("default", "hermes", {"peerName": "eri", "aiPeer": "hermetika"}),+ ("dreamer", "hermes.dreamer", {"aiPeer": "dreamer-ai"}),+ ])+ cfg = {"peerName": "eri", "hosts": {"claude_code": {"aiPeer": "clawd"}}}+ accounts = [{"platform": "telegram", "user_id": "7654321", "user_id_alt": ""}]+ labels = honcho_cli._classify_workspace_peers(+ ["eri", "hermetika", "dreamer-ai", "clawd", "7654321", "tg_7654321", "friend", "user-default-root", "meow"],+ cfg, accounts, {"999": "friend"}, "tg_",+ )+ assert labels == {+ "eri": "your peer (peerName)",+ "hermetika": "AI peer · this profile",+ "dreamer-ai": "AI peer · profile dreamer",+ "clawd": "AI peer of app 'claude_code'",+ "7654321": "runtime peer · telegram 7654321",+ "tg_7654321": "runtime peer · telegram 7654321",+ "friend": "alias target",+ "user-default-root": "fallback peer (pre-identity traffic)",+ "meow": "unrecognized",+ }