Skip to content

The agent that grows with you

refactor(honcho): trim the oauth persistence tests to one case per behavior

Erosika9aa2f7714252
diff --git a/tests/honcho_plugin/test_auth_recovery.py b/tests/honcho_plugin/test_auth_recovery.py
index 2f6aaadd6ad..71d658380ed 100644
--- a/tests/honcho_plugin/test_auth_recovery.py
+++ b/tests/honcho_plugin/test_auth_recovery.py
@@ -195,100 +195,43 @@ class TestForceRefreshToken:
)
assert oauth.force_refresh_token(path, "hermes") == "hch-at-2"
- def test_serial_force_refresh_adopts_first_waiters_rotation(self, tmp_path, monkeypatch):
- """Waiter 2 force-refreshes with the token that 401'd while disk (and
- the expiry cache) already hold waiter 1's rotation: it must adopt
- without a second exchange — a replayed refresh token can revoke the
- grant."""
+ @pytest.mark.parametrize("rotated_by", ["first waiter", "sibling process"])
+ def test_401_on_a_bearer_disk_has_moved_off_adopts_without_exchange(self, tmp_path, monkeypatch, rotated_by):
+ """The failing bearer disagreeing with disk is enough to adopt: a replayed refresh token can
+ revoke the grant, and the expiry cache is empty in a sibling process."""
path = tmp_path / "honcho.json"
far = time.time() + 7200
_write(path, {"hosts": {"hermes": _host_block(expires_at=far)}})
- calls = []
-
- def exchange_once(url, data, timeout):
- calls.append(data["refresh_token"])
- body = _rotated_body()
- body["expires_in"] = 7200
- return 200, body
-
- monkeypatch.setattr(oauth, "_http_post_form_status", exchange_once)
- # Waiter 1: rotates for real (cache and disk now both hold new1).
- assert (
- oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
- == "hch-at-new1"
- )
- assert calls == ["hch-rt-old"]
- # Waiter 2: was queued on the lock with the same failing token; disk
- # has moved — must adopt, not exchange.
- monkeypatch.setattr(
- oauth, "_http_post_form_status",
- lambda *a, **k: pytest.fail("second waiter must adopt, not exchange"),
- )
- assert (
- oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
- == "hch-at-new1"
- )
-
- def test_cross_process_401_adopts_disk_with_empty_cache(self, tmp_path, monkeypatch):
- """A sibling process rotated on disk; this process's expiry cache is
- empty. The failing token disagreeing with disk must be enough to
- adopt with zero HTTP."""
- path = tmp_path / "honcho.json"
- far = time.time() + 7200
- rotated = _host_block(refresh="hch-rt-2", expires_at=far)
- rotated["apiKey"] = "hch-at-2"
- _write(path, {"hosts": {"hermes": rotated}})
- oauth._expiry_cache.clear()
- monkeypatch.setattr(
- oauth, "_http_post_form_status",
- lambda *a, **k: pytest.fail("must adopt the sibling's on-disk grant, not exchange"),
- )
- assert (
- oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
- == "hch-at-2"
- )
- assert oauth._expiry_cache[(str(path), "hermes")][1] == "hch-at-2"
-
- def test_invalid_grant_adopts_disk_rotated_during_exchange(self, tmp_path, monkeypatch):
- """The exchange loses the race (endpoint says invalid_grant because a
- sibling used the refresh token first) and the sibling persists before
- we give up: adopt its grant, do not mark the grant dead."""
+ if rotated_by == "first waiter":
+ monkeypatch.setattr(oauth, "_http_post_form_status", lambda *a, **k: (200, {**_rotated_body(2), "expires_in": 7200}))
+ assert oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old") == "hch-at-new2"
+ else:
+ _write(path, {"hosts": {"hermes": {**_host_block(refresh="hch-rt-new2", expires_at=far), "apiKey": "hch-at-new2"}}})
+ oauth._expiry_cache.clear()
+ monkeypatch.setattr(oauth, "_http_post_form_status", lambda *a, **k: pytest.fail("must adopt the on-disk grant, not exchange"))
+ assert oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old") == "hch-at-new2"
+ assert oauth._expiry_cache[(str(path), "hermes")][1] == "hch-at-new2"
+
+ @pytest.mark.parametrize("sibling_persists", [True, False], ids=["disk rotated during exchange", "disk unchanged"])
+ def test_invalid_grant_adopts_a_rotation_that_landed_during_the_exchange(self, tmp_path, monkeypatch, sibling_persists):
+ """The endpoint says invalid_grant because a sibling used the refresh token first. Its rotation
+ on disk is adopted; only an unchanged disk marks the grant dead."""
path = tmp_path / "honcho.json"
far = time.time() + 7200
_write(path, {"hosts": {"hermes": _host_block(expires_at=far)}})
monkeypatch.setattr(oauth, "_REFRESH_RETRY_DELAY_SECONDS", 0)
- def lost_race(url, data, timeout):
- # Sibling process persisted its rotation while our POST was in flight.
- sibling = _host_block(refresh="hch-rt-sibling", expires_at=far)
- sibling["apiKey"] = "hch-at-sibling"
- _write(path, {"hosts": {"hermes": sibling}})
+ def exchange(url, data, timeout):
+ if sibling_persists:
+ _write(path, {"hosts": {"hermes": {**_host_block(refresh="hch-rt-sibling", expires_at=far), "apiKey": "hch-at-sibling"}}})
return 400, {"error": "invalid_grant", "error_description": "reuse detected"}
- monkeypatch.setattr(oauth, "_http_post_form_status", lost_race)
- assert (
- oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
- == "hch-at-sibling"
- )
- assert oauth.reauth_required(path, "hermes") is False
- # And the adopted grant keeps working on later calls.
- token, _ = oauth.ensure_fresh_token(path, "hermes", now=time.time())
- assert token == "hch-at-sibling"
-
- def test_invalid_grant_with_unchanged_disk_still_marks_dead(self, tmp_path, monkeypatch):
- path = tmp_path / "honcho.json"
- far = time.time() + 7200
- _write(path, {"hosts": {"hermes": _host_block(expires_at=far)}})
- monkeypatch.setattr(oauth, "_REFRESH_RETRY_DELAY_SECONDS", 0)
- monkeypatch.setattr(
- oauth, "_http_post_form_status",
- lambda *a, **k: (400, {"error": "invalid_grant"}),
- )
- assert (
- oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
- is None
- )
- assert oauth.reauth_required(path, "hermes") is True
+ monkeypatch.setattr(oauth, "_http_post_form_status", exchange)
+ token = oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
+ assert token == ("hch-at-sibling" if sibling_persists else None)
+ assert oauth.reauth_required(path, "hermes") is (not sibling_persists)
+ if sibling_persists:
+ assert oauth.ensure_fresh_token(path, "hermes", now=time.time())[0] == "hch-at-sibling"
def test_transient_failure_returns_none(self, tmp_path, monkeypatch):
path = tmp_path / "honcho.json"
@@ -462,12 +405,9 @@ class TestForceReauth:
mgr = HonchoSessionManager(config=HonchoClientConfig(host="hermes"))
assert mgr._force_reauth() is False
- def test_passes_pre_call_bearer_not_the_mutated_one(self, tmp_path, monkeypatch):
- """_authed_call snapshots the bearer BEFORE the operation runs. A
- sibling waiter's apply_token_to_client mutates the shared client's
- api_key in place mid-operation; if the post-mutation token were
- passed, disk would match it and force_refresh_token would exchange
- again — the exact burst this fix removes."""
+ def test_passes_the_bearer_the_operation_sent_not_the_rotated_one(self, tmp_path, monkeypatch):
+ """A sibling waiter rotates the shared client's api_key in place while the operation fails with
+ the old bearer; passing the rotated one would match disk and exchange again."""
from plugins.memory.honcho import client as client_mod
from plugins.memory.honcho import session as session_mod
@@ -475,31 +415,19 @@ class TestForceReauth:
shared_client = SimpleNamespace(_http=http)
monkeypatch.setattr(session_mod, "get_honcho_client", lambda *a, **k: shared_client)
monkeypatch.setattr(client_mod, "resolve_config_path", lambda: tmp_path / "honcho.json")
-
seen = {}
-
- def fake_force_refresh(p, h, *, failed_access_token=None):
- seen["failed"] = failed_access_token
- return "hch-at-new1"
-
- monkeypatch.setattr(oauth, "force_refresh_token", fake_force_refresh)
+ monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h, **kw: seen.update(kw) or "hch-at-new1")
monkeypatch.setattr(oauth, "apply_token_to_client", lambda c, t: True)
-
mgr = HonchoSessionManager(config=HonchoClientConfig(host="hermes", enabled=True))
- calls = {"n": 0}
-
def operation():
- calls["n"] += 1
- if calls["n"] == 1:
- # Sibling waiter rotates the shared client's bearer in place
- # while our request is failing with the OLD token.
+ if http.api_key == "hch-at-old":
http.api_key = "hch-at-new1"
raise Exception("Invalid or expired access token")
return "ok"
assert mgr._authed_call("test op", operation) == "ok"
- assert seen["failed"] == "hch-at-old"
+ assert seen == {"failed_access_token": "hch-at-old"}
# ---------------------------------------------------------------------------
diff --git a/tests/honcho_plugin/test_cli.py b/tests/honcho_plugin/test_cli.py
index 46df1407b98..2534a680d79 100644
--- a/tests/honcho_plugin/test_cli.py
+++ b/tests/honcho_plugin/test_cli.py
@@ -747,288 +747,165 @@ class TestCmdSetupDeviceFlow:
assert "apiKey" not in cfg.get("hosts", {}).get("hermes", {})
+def _point_cli_at(monkeypatch, cfg_path, **attrs):
+ """Route the honcho CLI's config reads and writes at ``cfg_path``; ``attrs`` replace other module names."""
+ import plugins.memory.honcho.cli as honcho_cli
+ for name, value in {"_config_path": lambda: cfg_path, "_local_config_path": lambda: cfg_path, **attrs}.items():
+ monkeypatch.setattr(honcho_cli, name, value)
+ return honcho_cli
-class TestWriteRefusesUnparseableStore:
- """A honcho.json that exists but does not parse reads as {} on the tolerant path. Writing that
- back would replace every host and root key with the current command's block, so writes refuse."""
-
- def _point_at(self, monkeypatch, cfg_path):
- import plugins.memory.honcho.cli as honcho_cli
- 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_coder")
- monkeypatch.setattr(honcho_cli, "_ensure_peer_exists", lambda host_key=None: False)
- return honcho_cli
-
- def test_write_config_refuses_and_leaves_file_alone(self, monkeypatch, tmp_path):
- cfg_path = tmp_path / "honcho.json"
- cfg_path.write_text('{"hosts": {"hermes": {"apiKey": "k"', encoding="utf-8")
- honcho_cli = self._point_at(monkeypatch, cfg_path)
- with pytest.raises(honcho_cli.ConfigWriteRefused):
- honcho_cli._write_config({"hosts": {"hermes_coder": {"enabled": True}}})
- assert cfg_path.read_text(encoding="utf-8") == '{"hosts": {"hermes": {"apiKey": "k"'
- def test_write_config_still_bootstraps_a_missing_file(self, monkeypatch, tmp_path):
- cfg_path = tmp_path / "honcho.json"
- honcho_cli = self._point_at(monkeypatch, cfg_path)
- honcho_cli._write_config({"apiKey": "k"})
- assert json.loads(cfg_path.read_text(encoding="utf-8")) == {"apiKey": "k"}
+class TestWriteRefusesUnparseableStore:
+ """An unparseable honcho.json reads as {} on the tolerant path; writing that back would drop every other host."""
- def test_command_prints_one_sentence_and_writes_nothing(self, monkeypatch, tmp_path, capsys):
+ @pytest.mark.parametrize("run", [
+ lambda cli: cli.honcho_command(SimpleNamespace(honcho_command="mode", mode="tools", target_profile=None)),
+ lambda cli: cli.cmd_setup(SimpleNamespace()),
+ ], ids=["command", "setup"])
+ def test_command_prints_one_sentence_asks_nothing_and_writes_nothing(self, monkeypatch, tmp_path, capsys, run):
cfg_path = tmp_path / "honcho.json"
cfg_path.write_text("{not json", encoding="utf-8")
- honcho_cli = self._point_at(monkeypatch, cfg_path)
- honcho_cli.honcho_command(SimpleNamespace(honcho_command="mode", mode="tools", target_profile=None))
+ honcho_cli = _point_cli_at(monkeypatch, cfg_path, _host_key=lambda: "hermes_coder",
+ _prompt=lambda *a, **k: pytest.fail("asked a question"))
+ run(honcho_cli)
out = capsys.readouterr().out
- assert "could not be read as JSON" in out
- assert "Nothing was written" in out
- assert cfg_path.read_text(encoding="utf-8") == "{not json"
-
- def test_setup_refuses_before_asking_anything(self, monkeypatch, tmp_path, capsys):
- cfg_path = tmp_path / "honcho.json"
- cfg_path.write_text("{not json", encoding="utf-8")
- honcho_cli = self._point_at(monkeypatch, cfg_path)
- monkeypatch.setattr(honcho_cli, "_prompt", lambda *a, **k: pytest.fail("wizard asked a question"))
- honcho_cli.cmd_setup(SimpleNamespace())
- assert "Nothing was written" in capsys.readouterr().out
+ assert "could not be read as JSON" in out and "Nothing was written" in out
assert cfg_path.read_text(encoding="utf-8") == "{not json"
class TestSetupApiKeyReplacesStaleGrant:
- """#97990: choosing apikey after a revoked grant left hosts.<name>.oauth in place, so the dead
- grant kept shadowing the fresh key across every later setup run."""
-
- def _cfg_with_grant(self):
- return {"hosts": {"hermes": {
- "apiKey": "hch-at-dead",
- "oauth": {"refreshToken": "hch-rt-dead", "expiresAt": 1, "clientId": "hermes-agent",
- "tokenEndpoint": "https://api.honcho.dev/oauth/token"},
- }}}
-
- def _cloud_auth(self, monkeypatch, tmp_path, cfg, *, key_answer):
- import plugins.memory.honcho.cli as honcho_cli
- monkeypatch.setattr(honcho_cli, "_device_login_available", lambda: False)
- monkeypatch.setattr(honcho_cli, "_headless", lambda: (False, True))
- shown = []
-
- def _prompt(label, default=None, secret=False):
- shown.append(label)
- return "apikey" if "OAuth" in label else key_answer
- monkeypatch.setattr(honcho_cli, "_prompt", _prompt)
- ok = honcho_cli._setup_cloud_auth(cfg, cfg["hosts"]["hermes"], tmp_path / "honcho.json")
- return ok, cfg["hosts"]["hermes"]
-
- def test_new_key_clears_oauth_and_lands_on_the_host_block(self, monkeypatch, tmp_path):
- cfg = self._cfg_with_grant()
- ok, host = self._cloud_auth(monkeypatch, tmp_path, cfg, key_answer="hch-v3-fresh")
- assert ok is True
- assert "oauth" not in host
- assert host["apiKey"] == "hch-v3-fresh"
- assert cfg["apiKey"] == "hch-v3-fresh"
-
- def test_kept_root_key_still_clears_oauth(self, monkeypatch, tmp_path, capsys):
- cfg = self._cfg_with_grant()
- cfg["apiKey"] = "hch-v3-rootkey"
- ok, host = self._cloud_auth(monkeypatch, tmp_path, cfg, key_answer="")
- assert ok is True
- assert "oauth" not in host
- assert host["apiKey"] == "hch-v3-rootkey"
- assert "...-rootkey" in capsys.readouterr().out
-
- def test_dead_access_token_is_not_offered_as_current(self, monkeypatch, tmp_path, capsys):
- cfg = self._cfg_with_grant()
- ok, host = self._cloud_auth(monkeypatch, tmp_path, cfg, key_answer="")
- assert ok is False
- assert "Current API key: not set" in capsys.readouterr().out
-
- def test_static_host_key_without_grant_is_kept(self, monkeypatch, tmp_path):
- cfg = {"hosts": {"hermes": {"apiKey": "hch-v3-hostkey"}}}
- ok, host = self._cloud_auth(monkeypatch, tmp_path, cfg, key_answer="")
- assert ok is True
- assert host["apiKey"] == "hch-v3-hostkey"
- assert "apiKey" not in cfg
+ """Choosing apikey after a revoked grant left hosts.<name>.oauth in place, shadowing the fresh key."""
+
+ @pytest.mark.parametrize("grant, root_key, answer, ok, host_key, root_after, shown", [
+ (True, None, "hch-v3-fresh", True, "hch-v3-fresh", "hch-v3-fresh", ""),
+ (True, "hch-v3-rootkey", "", True, "hch-v3-rootkey", "hch-v3-rootkey", "...-rootkey"),
+ (True, None, "", False, "hch-at-dead", None, "Current API key: not set"),
+ (False, None, "", True, "hch-v3-hostkey", None, ""),
+ ], ids=["new key clears oauth", "kept root key clears oauth", "dead access token not offered", "static host key kept"])
+ def test_apikey_answer(self, monkeypatch, tmp_path, capsys, grant, root_key, answer, ok, host_key, root_after, shown):
+ host = {"apiKey": "hch-v3-hostkey"}
+ if grant:
+ host = {"apiKey": "hch-at-dead", "oauth": {"refreshToken": "hch-rt-dead", "expiresAt": 1,
+ "clientId": "hermes-agent", "tokenEndpoint": "https://api.honcho.dev/oauth/token"}}
+ cfg = {"hosts": {"hermes": host}, **({"apiKey": root_key} if root_key else {})}
+ honcho_cli = _point_cli_at(monkeypatch, tmp_path / "honcho.json", _device_login_available=lambda: False,
+ _headless=lambda: (False, True),
+ _prompt=lambda label, default=None, secret=False: "apikey" if "OAuth" in label else answer)
+ assert honcho_cli._setup_cloud_auth(cfg, host, tmp_path / "honcho.json") is ok
+ assert host["apiKey"] == host_key and cfg.get("apiKey") == root_after
+ assert ("oauth" in host) is (grant and not ok)
+ assert shown in capsys.readouterr().out
+
+
+_OAUTH_DEFAULT = {"peerName": "eri", "hosts": {"hermes": {
+ "enabled": True, "apiKey": "hch-at-live", "workspace": "hermes", "peerName": "eri", "oauth": {"refreshToken": "hch-rt-live"},
+}}}
+_KEYLESS_DEFAULT = {"hosts": {"hermes": {"workspace": "hermes"}}}
class TestEnabledRequiresACredential:
- """A host block must not be written with enabled: true unless it can authenticate. The default
- host's apiKey is not inherited by named profiles (#66125), so a clone of an OAuth-authenticated
- default block, or an enable on an empty block, has nothing to sign requests with."""
+ """A host block is written with enabled: true only when it can authenticate. Named profiles do not
+ inherit the default host's apiKey, so a clone of an OAuth default block has nothing to sign with."""
- def _env(self, monkeypatch, tmp_path, cfg, *, host="hermes_dreamer", profile="dreamer"):
- import plugins.memory.honcho.cli as honcho_cli
+ def _env(self, monkeypatch, tmp_path, cfg, *, env_key=None, host="hermes_dreamer", profile="dreamer"):
+ import copy
+ cfg, written = copy.deepcopy(cfg), {}
cfg_path = tmp_path / "honcho.json"
cfg_path.write_text("{}")
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
monkeypatch.delenv("HONCHO_BASE_URL", raising=False)
- 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: host)
- monkeypatch.setattr(honcho_cli, "_active_profile_name", lambda: profile)
- 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))
+ if env_key:
+ monkeypatch.setenv("HONCHO_API_KEY", env_key)
+ honcho_cli = _point_cli_at(
+ monkeypatch, cfg_path, _read_config=lambda: cfg, _host_key=lambda: host, _active_profile_name=lambda: profile,
+ _ensure_peer_exists=lambda host_key=None: True, _write_config=lambda c, path=None: written.setdefault("cfg", c))
return honcho_cli, written
- def _oauth_default(self):
- return {"peerName": "eri", "hosts": {"hermes": {
- "enabled": True, "apiKey": "hch-at-live", "workspace": "hermes", "peerName": "eri",
- "oauth": {"refreshToken": "hch-rt-live", "expiresAt": 9e9, "clientId": "hermes-agent",
- "tokenEndpoint": "https://api.honcho.dev/oauth/token"},
- }}}
-
- def test_clone_from_oauth_default_is_written_without_enabled(self, monkeypatch, tmp_path):
- honcho_cli, written = self._env(monkeypatch, tmp_path, self._oauth_default())
+ @pytest.mark.parametrize("cfg, env_key, enabled", [
+ (_OAUTH_DEFAULT, None, False),
+ ({"hosts": {"hermes": {"enabled": True, "apiKey": "hch-v3-hostonly", "workspace": "hermes"}}}, None, False),
+ ({"apiKey": "hch-v3-root", **_KEYLESS_DEFAULT}, None, True),
+ (_KEYLESS_DEFAULT, "hch-v3-from-env", False),
+ ({"baseUrl": "http://localhost:8000", **_KEYLESS_DEFAULT}, None, True),
+ ], ids=["oauth default", "host-only static key", "root key", "env key only", "self-hosted url"])
+ def test_clone_is_enabled_only_by_an_on_disk_credential(self, monkeypatch, tmp_path, cfg, env_key, enabled):
+ honcho_cli, written = self._env(monkeypatch, tmp_path, cfg, env_key=env_key)
assert honcho_cli.clone_honcho_for_profile("dreamer") is True
block = written["cfg"]["hosts"]["hermes_dreamer"]
- assert "enabled" not in block
+ assert block.get("enabled") is (True if enabled else None)
assert "apiKey" not in block and "oauth" not in block
assert block["aiPeer"] == "dreamer" and block["workspace"] == "hermes"
- def test_clone_from_host_only_static_key_is_written_without_enabled(self, monkeypatch, tmp_path):
- cfg = {"hosts": {"hermes": {"enabled": True, "apiKey": "hch-v3-hostonly", "workspace": "hermes"}}}
- honcho_cli, written = self._env(monkeypatch, tmp_path, cfg)
- assert honcho_cli.clone_honcho_for_profile("dreamer") is True
- assert "enabled" not in written["cfg"]["hosts"]["hermes_dreamer"]
-
- def test_clone_with_root_key_is_enabled(self, monkeypatch, tmp_path):
- cfg = {"apiKey": "hch-v3-root", "hosts": {"hermes": {"workspace": "hermes"}}}
- honcho_cli, written = self._env(monkeypatch, tmp_path, cfg)
- assert honcho_cli.clone_honcho_for_profile("dreamer") is True
- assert written["cfg"]["hosts"]["hermes_dreamer"]["enabled"] is True
-
- def test_env_key_alone_does_not_enable_a_clone(self, monkeypatch, tmp_path):
- """A variable can vanish from the next process; only what is on disk counts at write time."""
- cfg = {"hosts": {"hermes": {"workspace": "hermes"}}}
- honcho_cli, written = self._env(monkeypatch, tmp_path, cfg)
- monkeypatch.setenv("HONCHO_API_KEY", "hch-v3-from-env")
- assert honcho_cli.clone_honcho_for_profile("dreamer") is True
- assert "enabled" not in written["cfg"]["hosts"]["hermes_dreamer"]
-
- def test_enable_refuses_with_only_an_env_key(self, monkeypatch, tmp_path, capsys):
- from types import SimpleNamespace
- cfg = {"hosts": {"hermes_dreamer": {"workspace": "hermes"}}}
- honcho_cli, written = self._env(monkeypatch, tmp_path, cfg)
- monkeypatch.setenv("HONCHO_API_KEY", "hch-v3-from-env")
- honcho_cli.cmd_enable(SimpleNamespace())
- assert written == {}
- assert "setup" in capsys.readouterr().out
-
-
- def test_clone_with_self_hosted_url_is_enabled(self, monkeypatch, tmp_path):
- cfg = {"baseUrl": "http://localhost:8000", "hosts": {"hermes": {"workspace": "hermes"}}}
- honcho_cli, written = self._env(monkeypatch, tmp_path, cfg)
- assert honcho_cli.clone_honcho_for_profile("dreamer") is True
- assert written["cfg"]["hosts"]["hermes_dreamer"]["enabled"] is True
-
- def test_enable_on_empty_block_refuses_and_writes_nothing(self, monkeypatch, tmp_path, capsys):
- honcho_cli, written = self._env(monkeypatch, tmp_path, self._oauth_default())
- honcho_cli.cmd_enable(SimpleNamespace())
- out = capsys.readouterr().out
- assert "stays disabled" in out
- assert "hermes honcho setup --target-profile dreamer" in out
- assert "hosts.hermes_dreamer" in out
- assert written == {}
-
- def test_enable_on_legacy_enabled_keyless_block_explains_instead_of_already_enabled(self, monkeypatch, tmp_path, capsys):
- cfg = self._oauth_default()
- cfg["hosts"]["hermes_dreamer"] = {"enabled": True, "aiPeer": "dreamer", "workspace": "hermes", "peerName": "eri"}
- honcho_cli, written = self._env(monkeypatch, tmp_path, cfg)
- honcho_cli.cmd_enable(SimpleNamespace())
- out = capsys.readouterr().out
- assert "stays disabled" in out
- assert "already enabled" not in out
- assert written == {}
-
- def test_enable_with_root_key_still_enables(self, monkeypatch, tmp_path, capsys):
- cfg = {"apiKey": "hch-v3-root", "hosts": {"hermes": {"workspace": "hermes"}}}
- honcho_cli, written = self._env(monkeypatch, tmp_path, cfg)
- honcho_cli.cmd_enable(SimpleNamespace())
- assert "Honcho enabled" in capsys.readouterr().out
- assert written["cfg"]["hosts"]["hermes_dreamer"]["enabled"] is True
-
- def test_enable_on_default_profile_hint_omits_target_profile(self, monkeypatch, tmp_path, capsys):
- honcho_cli, written = self._env(monkeypatch, tmp_path, {"hosts": {}}, host="hermes", profile="default")
+ @pytest.mark.parametrize("cfg, env_key, profile, expect, enabled", [
+ ({"hosts": {"hermes_dreamer": {"workspace": "hermes"}}}, "hch-v3-from-env", "dreamer", ["setup"], False),
+ (_OAUTH_DEFAULT, None, "dreamer",
+ ["stays disabled", "hermes honcho setup --target-profile dreamer", "hosts.hermes_dreamer"], False),
+ ({"hosts": {"hermes_dreamer": {"enabled": True, "aiPeer": "dreamer", "workspace": "hermes"}}}, None, "dreamer",
+ ["stays disabled"], False),
+ ({"hosts": {}}, None, "default", ["Run 'hermes honcho setup' to sign in"], False),
+ ({"apiKey": "hch-v3-root", **_KEYLESS_DEFAULT}, None, "dreamer", ["Honcho enabled"], True),
+ ], ids=["env key only", "empty block", "legacy enabled keyless block", "default profile hint", "root key"])
+ def test_enable_writes_enabled_only_for_an_on_disk_credential(self, monkeypatch, tmp_path, capsys,
+ cfg, env_key, profile, expect, enabled):
+ host = "hermes" if profile == "default" else "hermes_dreamer"
+ honcho_cli, written = self._env(monkeypatch, tmp_path, cfg, env_key=env_key, host=host, profile=profile)
honcho_cli.cmd_enable(SimpleNamespace())
out = capsys.readouterr().out
- assert "Run 'hermes honcho setup' to sign in" in out
- assert written == {}
+ assert all(s in out for s in expect) and "already enabled" not in out
+ assert written["cfg"]["hosts"][host]["enabled"] is True if enabled else written == {}
class TestWriteConfigMergesOntoDisk:
- """A command reads honcho.json, works, then writes. A refresh in another process may have rotated
- the token in between; the write must keep that rotation and apply only the command's own edits."""
+ """A refresh in another process may rotate the token while a command runs; the write must keep it."""
def _paths(self, monkeypatch, tmp_path, disk):
- import plugins.memory.honcho.cli as honcho_cli
cfg_path = tmp_path / "honcho.json"
cfg_path.write_text(json.dumps(disk))
- monkeypatch.setattr(honcho_cli, "_config_path", lambda: cfg_path)
- monkeypatch.setattr(honcho_cli, "_local_config_path", lambda: cfg_path)
- return honcho_cli, cfg_path
+ return _point_cli_at(monkeypatch, cfg_path), cfg_path
- def _rotated(self, cfg_path, disk):
- disk["hosts"]["hermes"]["apiKey"] = "hch-at-new"
- disk["hosts"]["hermes"]["oauth"] = {"refreshToken": "hch-rt-new"}
+ def _rotate_on_disk(self, cfg_path):
+ disk = json.loads(cfg_path.read_text())
+ disk["hosts"]["hermes"].update(apiKey="hch-at-new", oauth={"refreshToken": "hch-rt-new"})
cfg_path.write_text(json.dumps(disk))
- def test_rotation_between_read_and_write_survives(self, monkeypatch, tmp_path):
+ def test_untouched_keys_take_disk_and_the_commands_edits_apply(self, monkeypatch, tmp_path):
disk = {"apiKey": "root", "hosts": {"hermes": {"apiKey": "hch-at-old", "oauth": {"refreshToken": "hch-rt-old"},
- "recallMode": "hybrid"}}}
+ "recallMode": "hybrid", "runtimePeerPrefix": "tg_"}}}
honcho_cli, cfg_path = self._paths(monkeypatch, tmp_path, disk)
cfg = honcho_cli._read_config()
- self._rotated(cfg_path, json.loads(cfg_path.read_text()))
+ self._rotate_on_disk(cfg_path)
cfg["hosts"]["hermes"]["recallMode"] = "tools"
+ cfg["hosts"]["hermes"].pop("runtimePeerPrefix")
cfg["dialecticCadence"] = 3
honcho_cli._write_config(cfg)
out = json.loads(cfg_path.read_text())
- assert out["hosts"]["hermes"]["apiKey"] == "hch-at-new"
- assert out["hosts"]["hermes"]["oauth"] == {"refreshToken": "hch-rt-new"}
- assert out["hosts"]["hermes"]["recallMode"] == "tools" and out["dialecticCadence"] == 3
+ assert out["hosts"]["hermes"] == {"apiKey": "hch-at-new", "oauth": {"refreshToken": "hch-rt-new"}, "recallMode": "tools"}
+ assert out["apiKey"] == "root" and out["dialecticCadence"] == 3
def test_a_credential_the_command_set_wins(self, monkeypatch, tmp_path):
disk = {"hosts": {"hermes": {"apiKey": "hch-at-old", "oauth": {"refreshToken": "hch-rt-old"}}}}
honcho_cli, cfg_path = self._paths(monkeypatch, tmp_path, disk)
cfg = honcho_cli._read_config()
- self._rotated(cfg_path, json.loads(cfg_path.read_text()))
+ self._rotate_on_disk(cfg_path)
cfg["hosts"]["hermes"]["apiKey"] = "hch-v3-pasted"
cfg["hosts"]["hermes"].pop("oauth")
honcho_cli._write_config(cfg)
- out = json.loads(cfg_path.read_text())
- assert out["hosts"]["hermes"]["apiKey"] == "hch-v3-pasted" and "oauth" not in out["hosts"]["hermes"]
-
- def test_a_key_the_command_removed_is_removed(self, monkeypatch, tmp_path):
- disk = {"hosts": {"hermes": {"apiKey": "k", "runtimePeerPrefix": "tg_"}}}
- honcho_cli, cfg_path = self._paths(monkeypatch, tmp_path, disk)
- cfg = honcho_cli._read_config()
- cfg["hosts"]["hermes"].pop("runtimePeerPrefix")
- honcho_cli._write_config(cfg)
- assert "runtimePeerPrefix" not in json.loads(cfg_path.read_text())["hosts"]["hermes"]
-
- def test_write_without_a_prior_read_writes_the_whole_config(self, monkeypatch, tmp_path):
- honcho_cli, cfg_path = self._paths(monkeypatch, tmp_path, {"hosts": {"hermes": {"apiKey": "k"}}})
- honcho_cli._write_config({"hosts": {"other": {"apiKey": "o"}}})
- assert json.loads(cfg_path.read_text()) == {"hosts": {"other": {"apiKey": "o"}}}
-
- def test_a_rebuilt_plain_dict_is_written_whole(self, monkeypatch, tmp_path):
- disk = {"hosts": {"hermes": {"apiKey": "hch-at-old", "recallMode": "hybrid"}}}
- honcho_cli, cfg_path = self._paths(monkeypatch, tmp_path, disk)
- cfg = dict(honcho_cli._read_config())
- self._rotated(cfg_path, json.loads(cfg_path.read_text()))
+ assert json.loads(cfg_path.read_text())["hosts"]["hermes"] == {"apiKey": "hch-v3-pasted"}
+
+ @pytest.mark.parametrize("build", [lambda cli: {"hosts": {"other": {"apiKey": "o"}}}, lambda cli: dict(cli._read_config())],
+ ids=["never read", "rebuilt from the read"])
+ def test_a_plain_dict_is_written_whole(self, monkeypatch, tmp_path, build):
+ honcho_cli, cfg_path = self._paths(monkeypatch, tmp_path, {"hosts": {"hermes": {"apiKey": "hch-at-old"}}})
+ cfg = build(honcho_cli)
+ self._rotate_on_disk(cfg_path)
honcho_cli._write_config(cfg)
- assert json.loads(cfg_path.read_text())["hosts"]["hermes"]["apiKey"] == "hch-at-old"
+ assert json.loads(cfg_path.read_text()) == cfg
- def test_write_holds_the_refresh_file_lock(self, monkeypatch, tmp_path):
+ def test_write_holds_the_refresh_file_lock_and_bootstraps_a_missing_file(self, monkeypatch, tmp_path):
import contextlib
import plugins.memory.honcho.oauth as oauth
- honcho_cli, cfg_path = self._paths(monkeypatch, tmp_path, {})
- locked = []
-
- @contextlib.contextmanager
- def _lock(path):
- locked.append(path)
- yield
-
- monkeypatch.setattr(oauth, "_config_refresh_lock", _lock)
+ cfg_path = tmp_path / "honcho.json"
+ honcho_cli, locked = _point_cli_at(monkeypatch, cfg_path), []
+ monkeypatch.setattr(oauth, "_config_refresh_lock", lambda path: locked.append(path) or contextlib.nullcontext())
honcho_cli._write_config({"apiKey": "k"})
- assert locked == [cfg_path]
+ assert locked == [cfg_path] and json.loads(cfg_path.read_text(encoding="utf-8")) == {"apiKey": "k"}
diff --git a/tests/honcho_plugin/test_oauth.py b/tests/honcho_plugin/test_oauth.py
index 3415412c612..fa7967aab28 100644
--- a/tests/honcho_plugin/test_oauth.py
+++ b/tests/honcho_plugin/test_oauth.py
@@ -1,6 +1,7 @@
"""Tests for plugins/memory/honcho/oauth.py — OAuth grant storage + refresh."""
import json
+from contextlib import nullcontext
from pathlib import Path
import pytest
@@ -187,31 +188,22 @@ class TestInstallGrant:
def test_reads_and_writes_under_the_refresh_locks(self, tmp_path, monkeypatch):
path = tmp_path / "honcho.json"
_write(path, {"hosts": {"other": _host_block()}})
- seen = {}
- real_read, real_persist = oauth._read_config_strict, oauth._persist_credential
- locked_paths = []
-
- @oauth.contextmanager
- def spy_file_lock(p):
- locked_paths.append(p)
- yield
-
- def spy_read(p):
- seen["read_locked"] = oauth._refresh_lock.locked()
- return real_read(p)
-
- def spy_persist(p, host, cred, raw=None):
- seen["persist_locked"] = oauth._refresh_lock.locked()
- return real_persist(p, host, cred, raw)
-
- monkeypatch.setattr(oauth, "_config_refresh_lock", spy_file_lock)
- monkeypatch.setattr(oauth, "_read_config_strict", spy_read)
- monkeypatch.setattr(oauth, "_persist_credential", spy_persist)
+ seen, locked_paths = {}, []
+
+ def spy(name, real):
+ def wrapped(*a, **k):
+ seen[name] = oauth._refresh_lock.locked()
+ return real(*a, **k)
+ return wrapped
+
+ monkeypatch.setattr(oauth, "_config_refresh_lock", lambda p: locked_paths.append(p) or nullcontext())
+ monkeypatch.setattr(oauth, "_read_config_strict", spy("read", oauth._read_config_strict))
+ monkeypatch.setattr(oauth, "_persist_credential", spy("persist", oauth._persist_credential))
oauth.install_grant(
path, "hermes", {"access_token": "hch-at-new", "refresh_token": "hch-rt-new", "expires_in": 60},
client_id="c", token_endpoint="e",
)
- assert seen == {"read_locked": True, "persist_locked": True}
+ assert seen == {"read": True, "persist": True}
assert locked_paths == [path]
assert not oauth._refresh_lock.locked()
assert "other" in json.loads(path.read_text())["hosts"]
diff --git a/tests/test_honcho_client_config.py b/tests/test_honcho_client_config.py
index f186280d880..38301f8e9c2 100644
--- a/tests/test_honcho_client_config.py
+++ b/tests/test_honcho_client_config.py
@@ -206,22 +206,16 @@ class TestProfileKeyIsolationWarning:
assert not any('NOT inherited' in r.message for r in caplog.records)
-def test_save_config_refuses_to_replace_a_file_that_does_not_parse(tmp_path, monkeypatch):
+def test_save_config_refuses_to_replace_a_file_that_does_not_parse(tmp_path):
"""A corrupt honcho.json must not be rewritten from the new values alone."""
- import pytest
- from plugins.memory.honcho import HonchoMemoryProvider
-
config_path = tmp_path / "honcho.json"
config_path.write_text("{ not json")
- provider = HonchoMemoryProvider()
with pytest.raises(ValueError):
- provider.save_config({"api_key": "hc-test-key"}, str(tmp_path))
+ HonchoMemoryProvider().save_config({"api_key": "hc-test-key"}, str(tmp_path))
assert config_path.read_text() == "{ not json"
def test_save_config_merges_into_a_parseable_file(tmp_path):
- from plugins.memory.honcho import HonchoMemoryProvider
-
config_path = tmp_path / "honcho.json"
config_path.write_text(json.dumps({"hosts": {"other": {"apiKey": "keep-me"}}}))
HonchoMemoryProvider().save_config({"api_key": "hc-test-key"}, str(tmp_path))