diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..e021425 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,28 @@ +## What kind of change is this? + +- [ ] bug fix +- [ ] bug fix + test +- [ ] feature +- [ ] refactor / cleanup +- [ ] docs / comments +- [ ] test-only +- [ ] security fix + +## Summary + +Briefly describe the change and why it is needed. + +## Branch + +This PR was opened from a branch using one of: +- `fix/…` +- `bugs/…` +- `feature/…` + +## Checklist + +- [ ] Tests pass: `python -m pytest -q` +- [ ] `verify.py` is green +- [ ] No raw tokens/secrets in code, logs, or tool output +- [ ] Adapter stays loopback-only unless an explicit guard is added +- [ ] Updated docs/README if user-facing behavior changed diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb30608..127316b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -75,9 +75,7 @@ jobs: HERMES_HOME: ${{ env.HERMES_HOME }} run: | set -euo pipefail - # Adapter tests bind a local port and can hang in CI; the same subset - # is excluded when running locally. - python -m pytest -q -k "not adapter" + python -m pytest -q - name: Run plugin self-checks (verify.py) working-directory: ${{ env.HERMES_HOME }}/plugins/builder diff --git a/.github/workflows/pr-label.yml b/.github/workflows/pr-label.yml new file mode 100644 index 0000000..8510504 --- /dev/null +++ b/.github/workflows/pr-label.yml @@ -0,0 +1,30 @@ +name: PR auto-label by branch prefix + +on: + pull_request: + types: [opened, synchronize, reopened] + +jobs: + label: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - uses: actions/github-script@v7 + with: + script: | + const branch = context.payload.pull_request.head.ref + const labels = { + 'fix/': 'bug', + 'bugs/': 'bug', + 'feature/': 'enhancement' + } + const mapping = Object.entries(labels).find(([prefix]) => branch.startsWith(prefix)) + if (!mapping) return + const [, label] = mapping + await github.rest.issues.addLabels({ + ...context.repo, + issue_number: context.issue.number, + labels: [label] + }) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c723fdd..7bd4165 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,6 +22,10 @@ set up, test, and submit changes. `test(builder):`, `refactor(builder):`, `sec(builder):`. Bodies only when a critical bug/security reason must be recorded. Keep subjects ≤ ~72 chars. +- **Branches:** use one of `fix/`, `bugs/`, or `feature/` plus a short + descriptor. Examples: `fix/setup-dual-activation`, `feature/chat-tools`. + This repo uses lightweight auto-labeling, so matching these prefixes keeps + PRs labeled automatically. ## Development setup diff --git a/backend.py b/backend.py index d5d00de..18cf527 100644 --- a/backend.py +++ b/backend.py @@ -145,7 +145,7 @@ def _resolve_model_id(model: Optional[str]) -> str: return requested import logging - logging.getLogger(__name__).warning( + logging.getLogger(__name__).debug( "builder: unknown model %r not in catalog %s; using 'auto' " "(Q returns HTTP 500 for unsupported modelId)", requested, diff --git a/requirements.txt b/requirements.txt index 69c259c..ba3831a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,9 +5,9 @@ # core. CI therefore checks out Hermes core (hermes-agent) as a sibling and runs # the suite from that layout (see .github/workflows/ci.yml). These pins match # the versions in the hermes-agent venv so CI behaves like the real environment. -hermes-agent @ git+https://github.com/NousResearch/hermes-agent.git@main#egg=hermes-agent +hermes-agent @ git+https://github.com/NousResearch/hermes-agent.git@a88512b114059fff642d60d54cbf30d5793c6c37#egg=hermes-agent pytest==9.0.3 requests==2.33.0 PyYAML==6.0.3 botocore==1.42.97 -cryptography==48.0.1 +cryptography>=46.0.7 diff --git a/scripts/setup.sh b/scripts/setup.sh index d886007..abc4dd9 100755 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -6,6 +6,9 @@ # compatible adapter (adapter.py, launched by register()) that translates to # Amazon Q. This script adds the providers: builder entry pointing at that # adapter (localhost :8077) — NO :8088 bridge daemon, no orphaned ref. +# It ALSO adds builder to plugins.enabled so the plugin module loads and +# register() actually starts the adapter. Without both, the model picker +# shows a dead endpoint. # # SAFE: idempotent (skips if already present), always backs up config.yaml # first. Does NOT touch any other provider. User-invoked (never auto-run by @@ -20,69 +23,112 @@ CONFIG="${HERMES_HOME:-$HOME/.hermes}/config.yaml" BACKUP="${CONFIG}.bak.$(date +%Y%m%d_%H%M%S)" PORT="${AWS_BUILD_ADAPTER_PORT:-8077}" - if [[ ! -f "$CONFIG" ]]; then echo "✗ config.yaml not found at $CONFIG" >&2 exit 1 fi -# Idempotency: already present? -if grep -qE '^[[:space:]]*builder:' "$CONFIG"; then - echo "✓ providers: builder already present in $CONFIG — nothing to do." - echo " Restart Hermes if you haven't since installing the plugin." - exit 0 +# Resolve a Python that has PyYAML. Prefer `python3` on PATH; fall back to +# the Hermes venv if the user's PATH is minimal. +PYTHON="$(command -v python3 || true)" +if [[ -z "$PYTHON" ]]; then + # Try the Hermes venv under HERMES_HOME or ~/.hermes. + HM="${HERMES_HOME:-$HOME/.hermes}" + for candidate in \ + "$HM/hermes-agent/venv/bin/python3" \ + "$HM/venv/bin/python3"; do + if [[ -x "$candidate" ]]; then + PYTHON="$candidate" + break + fi + done +fi +if [[ -z "$PYTHON" ]]; then + echo "✗ python3 is required for config edits (install Python or add it to PATH)." >&2 + exit 1 fi -# Backup +# Backup once cp "$CONFIG" "$BACKUP" echo "✓ backed up config → $BACKUP" -# Insert the block as a top-level providers: key, using Python -# (reliable indentation handling). Idempotent: only if absent. -# Write the block to a temp file (real newlines, not escaped). +# Resolve plugin root and manifest. +PLUGIN_DIR="${HERMES_HOME:-$HOME/.hermes}/plugins/builder" +PLUGIN_YAML="$PLUGIN_DIR/plugin.yaml" + +# Write the provider block to a temp file. +# NOTE: model list is read from plugin.yaml at install time so setup.sh and +# backend.py cannot drift. key_env removed: the adapter does not need one. BLOCK_FILE="$(mktemp)" cat > "$BLOCK_FILE" <&2 + exit 1 +fi - # Remove the providers: builder block (the 'builder:' key, which is - # indented under 'providers:', plus its child lines). Match on stripped - # line == 'builder:' (unique key, any indentation). - python3 - "$CONFIG" <<'PY' +# Backup once +BACKUP="${CONFIG}.bak.$(date +%Y%m%d_%H%M%S)" +cp "$CONFIG" "$BACKUP" +echo "✓ backed up config → $BACKUP" + +# 1) Remove the providers: builder block (idempotent) +"$PYTHON" - "$CONFIG" <<'PY' import sys cfg = sys.argv[1] lines = open(cfg).read().splitlines() @@ -52,21 +63,26 @@ for ln in lines: out.append(ln) open(cfg, "w").write("\n".join(out).rstrip("\n") + "\n") PY + +if grep -qE '^[[:space:]]*builder:' "$CONFIG"; then + echo "✓ providers: builder still present — check backup $BACKUP" +else echo "✓ removed providers: builder from $CONFIG" fi -# Normalize plugins.enabled (remove builder if present) — backup-safe. -python3 - "$CONFIG" <<'PY' +# 2) Normalize plugins.enabled (remove builder if present) +"$PYTHON" - "$CONFIG" <<'PY' import sys, yaml cfg = sys.argv[1] -c = yaml.safe_load(open(cfg)) +c = yaml.safe_load(open(cfg)) or {} en = (c.get("plugins") or {}).get("enabled") or [] +en = [str(x) for x in en] if "builder" in en: c.setdefault("plugins", {})["enabled"] = [x for x in en if x != "builder"] yaml.safe_dump(c, open(cfg, "w"), sort_keys=False, default_flow_style=False) - print("✓ removed builder from plugins.enabled") + print("removed_builder_from_enabled") else: - print("✓ builder not in plugins.enabled — nothing to do.") + print("builder_not_in_enabled") PY echo diff --git a/tests/test_backend.py b/tests/test_backend.py index 628f151..bcad216 100644 --- a/tests/test_backend.py +++ b/tests/test_backend.py @@ -325,7 +325,8 @@ def iter_content(self, chunk_size=1024): # Refresh "succeeds" but the next 401 still happens -> bounded retry. monkeypatch.setattr(sso_oidc, "refresh_token", lambda: True) with pytest.raises(RuntimeError): - backend.chat("hi", model="claude-sonnet-4") + # The first call retries once after refresh; the second 401 must raise + # rather than recursing forever. backend.chat("hi", model="claude-sonnet-4") diff --git a/tests/test_chat_dispatch.py b/tests/test_chat_dispatch.py index c43fc86..7e10c8a 100644 --- a/tests/test_chat_dispatch.py +++ b/tests/test_chat_dispatch.py @@ -1,95 +1,244 @@ -"""Robust integration tests for the builder plugin's models/tags tools. +"""Tests for the builder plugin registration / dispatch lifecycle. -These drive the REAL hermes chat/TUI tool-dispatch path — the same code the -`hermes chat` / TUI loop calls when the agent emits a tool call: +Two layers, deliberately kept apart: - hermes_cli.plugins (discovery) -> tools.registry (registration) - -> registry.get_entry(name).handler(args) (what run_agent.py invokes) +* Real discovery (``TestDiscoveryAndRegistry``) — the same chain the + ``hermes chat`` / TUI loop runs at startup: -No LLM is in the loop, so the test is deterministic and does not depend on the -live Amazon Q backend or its rate limits. Per hermes-agent AGENTS.md we exercise -the real resolution chain with actual imports (not mocks) and assert behavior -contracts, not current-data snapshots. + hermes_cli.plugins (discovery) -> tools.registry (registration) + -> registry.get_entry(name).handler(args) (what run_agent.py calls) + + No LLM and no network, so it is deterministic; the handlers are the real + ones, so a rename in ``_TOOLS`` or a ``plugin.yaml`` drift fails here. + +* Unit lifecycle (``TestPluginLifecycle`` / ``TestSerialization``) — the + register()/unregister() contract with a stubbed adapter, plus the + (success, error) serializer shape. Run with the plugin's own pytest (HERMES_HOME is redirected to a temp profile by conftest.py, so no real user secrets are read). """ +from __future__ import annotations + import json +import os import sys +import types +from pathlib import Path import pytest -# conftest.py already put HERMES_AGENT_DIR on sys.path and redirected HERMES_HOME. -from conftest import HERMES_AGENT_DIR, PLUGIN_DIR # noqa: E402 +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +from conftest import load_plugin # noqa: E402 + + +EXPECTED_TOOLS = { + "ask_q", + "bid_login", + "bid_status", + "bid_show_identity", + "bid_logout", + "models", + "tags", +} + -# Importing model_tools triggers plugin discovery (the same side effect the chat -# CLI relies on), so tools.registry is fully populated with builder's tools. -if HERMES_AGENT_DIR.exists(): - sys.path.insert(0, str(HERMES_AGENT_DIR)) -else: # pragma: no cover - layout guard - pytest.skip("hermes-agent not found", allow_module_level=True) +@pytest.fixture(scope="module") +def mod(): # noqa: ANN + return load_plugin() -import model_tools # noqa: E402,F401 (imports tools.registry, discovers plugins) -from tools.registry import registry # noqa: E402 +@pytest.fixture(scope="module") +def discovered(): + """Drive the REAL plugin discovery chain once, like `hermes chat` startup. -def _plugin_manager(): + Yields the global plugin manager; ``tools.registry`` is populated as a side + effect of ``register()`` (builder's tools land under toolset ``builder``). + """ from hermes_cli import plugins as P - return P._ensure_plugins_discovered() - - -def test_build_discovered_and_registers_model_tools(): - mgr = _plugin_manager() - assert "builder" in mgr._plugins, "builder plugin must be discovered" - registered = set(mgr._plugins["builder"].tools_registered) - assert {"models", "tags"}.issubset(registered) - - -def test_models_and_tags_resolve_in_global_registry(): - # The chat/TUI loop resolves a tool call by name via the global registry. - for name in ("models", "tags"): - entry = registry.get_entry(name) - assert entry is not None, f"{name} must be in the tool registry" - assert entry.toolset == "builder" - - -def test_models_tool_returns_plugin_yaml_catalog(): - entry = registry.get_entry("models") - out = json.loads(entry.handler({}, task_id="test-dispatch")) - assert out.get("success") is True - models = out.get("models", []) - # Behavior contract (not a snapshot): the served catalog must be the - # plugin.yaml override and must include the current Claude variants Q serves. - assert isinstance(models, list) and len(models) >= 1 - assert "claude-sonnet-4.5" in models - assert "claude-sonnet-4" in models - assert "claude-haiku-4.5" in models - # Q's chat endpoint rejects claude-opus-*; the catalog must never advertise it. - assert not any("opus" in m for m in models) - # models and tags tools must agree on the tag set (single source of truth). - assert set(out.get("tags", [])) == set( - json.loads(registry.get_entry("tags").handler({}, task_id="t")).get("tags", []) + manager = P._ensure_plugins_discovered() + yield manager + # register() starts the local adapter; release the listener afterwards so + # the suite does not leave :8077 bound. Discovery imports the adapter as a + # submodule, so stop THAT module, not the top-level `adapter`. + adapter_mod = sys.modules.get("hermes_plugins.builder.adapter") + if adapter_mod is not None: + adapter_mod.stop() + + +class FakeAdapter: + started = False + stopped = False + requested_port = None + actual_port = None + + @classmethod + def start(cls, port=None): + cls.started = True + cls.requested_port = port + # Mirror the real adapter's (server, actual_port) contract: the second + # element is what register() is supposed to report. + cls.actual_port = port + 1 + return (None, cls.actual_port) + + @classmethod + def stop(cls): + cls.stopped = True + + +def _install_fake_adapter(monkeypatch): + """Put a stub adapter in place of the real one, for lifecycle tests only.""" + fake_pkg = types.ModuleType("hermes_plugins") + fake_pkg.__path__ = [] + fake_pkg.__package__ = "hermes_plugins" + fake_mod = types.ModuleType("hermes_plugins.builder") + fake_mod.__path__ = [] + fake_mod.__package__ = "hermes_plugins.builder" + fake_adapter = types.ModuleType("hermes_plugins.builder.adapter") + fake_adapter.__package__ = "hermes_plugins.builder" + fake_adapter.start = FakeAdapter.start + fake_adapter.stop = FakeAdapter.stop + fake_mod.adapter = fake_adapter + monkeypatch.setitem(sys.modules, "hermes_plugins", fake_pkg) + monkeypatch.setitem(sys.modules, "hermes_plugins.builder", fake_mod) + monkeypatch.setitem(sys.modules, "hermes_plugins.builder.adapter", fake_adapter) + return fake_adapter + + +def _ctx(captured): + return types.SimpleNamespace( + register_tool=lambda **kw: captured.update({kw["name"]: kw}), + register_hook=lambda *a, **k: None, ) -def test_tags_tool_returns_stable_identity_tags(): - entry = registry.get_entry("tags") - out = json.loads(entry.handler({}, task_id="test-dispatch")) - assert out.get("success") is True - tags = out.get("tags", []) - # Behavior contract: identity tags are always present (not a fixed count). - for required in ("aws", "amazon-q", "claude", "chat", "builder-id", "auth"): - assert required in tags - - -def test_tool_outputs_never_leak_secrets(): - # The chat/TUI surfaces these handler outputs to the agent/user; secrets must - # never appear, regardless of auth state. - for name in ("models", "tags"): - entry = registry.get_entry(name) - blob = json.dumps(json.loads(entry.handler({}, task_id="t"))) - assert "access_token" not in blob - assert "client_secret" not in blob - assert "refresh_token" not in blob +# --- real discovery -> global registry --------------------------------------- + + +class TestDiscoveryAndRegistry: + def test_builder_discovered_and_enabled(self, discovered): + loaded = discovered._plugins.get("builder") + assert loaded is not None, "builder plugin must be discovered" + assert loaded.enabled is True + assert EXPECTED_TOOLS.issubset(set(loaded.tools_registered)) + + def test_tools_resolve_in_global_registry(self, discovered): + # The chat/TUI loop resolves a tool call by NAME via the global registry. + from tools.registry import registry + + for name in sorted(EXPECTED_TOOLS): + entry = registry.get_entry(name) + assert entry is not None, f"{name} must be in the tool registry" + assert entry.toolset == "builder" + assert entry.handler is not None + + def test_models_tool_returns_plugin_yaml_catalog(self, discovered): + from tools.registry import registry + + out = json.loads(registry.get_entry("models").handler({}, task_id="test-dispatch")) + assert out.get("success") is True + models = out.get("models", []) + assert isinstance(models, list) and len(models) >= 1 + # Behavior contract, not a snapshot: the catalog is the plugin.yaml + # override, includes the current Claude variants Q serves, and never + # advertises claude-opus-* (Q's chat endpoint rejects them). + assert {"claude-sonnet-4", "claude-sonnet-4.5", "claude-haiku-4.5"} <= set(models) + assert not any("opus" in m for m in models) + # models and tags tools must agree on the tag set (single source of truth). + tags = json.loads(registry.get_entry("tags").handler({}, task_id="t")).get("tags", []) + assert set(out.get("tags", [])) == set(tags) + + def test_tags_tool_returns_stable_identity_tags(self, discovered): + from tools.registry import registry + + out = json.loads(registry.get_entry("tags").handler({}, task_id="test-dispatch")) + assert out.get("success") is True + # Identity tags are always present (not a fixed count). + for required in ("aws", "amazon-q", "claude", "chat", "builder-id", "auth"): + assert required in out.get("tags", []) + + def test_tool_outputs_never_leak_secrets(self, discovered): + # The chat/TUI surfaces these handler outputs to the agent/user. + from tools.registry import registry + + for name in sorted(EXPECTED_TOOLS): + blob = json.dumps(json.loads(registry.get_entry(name).handler({}, task_id="t"))) + assert "access_token" not in blob + assert "client_secret" not in blob + assert "refresh_token" not in blob + + +# --- register()/unregister() lifecycle ---------------------------------------- + + +class TestPluginLifecycle: + def test_register_and_unregister_exist(self, mod): + assert callable(mod.register) + assert callable(mod.unregister) + + def test_expected_tools_registered(self, mod): + captured = {} + mod.register(_ctx(captured)) + assert EXPECTED_TOOLS.issubset(set(captured)) + + def test_register_starts_adapter_on_configured_port(self, mod, monkeypatch, capsys): + _install_fake_adapter(monkeypatch) + FakeAdapter.started = False + FakeAdapter.requested_port = None + FakeAdapter.actual_port = None + captured = {} + + mod.register(_ctx(captured)) + + assert FakeAdapter.started is True + # register() must forward the configured port (env or adapter default), + # not a hardcoded constant, and report the port start() returned. + expected = int(os.environ.get("AWS_BUILD_ADAPTER_PORT", "8077")) + assert FakeAdapter.requested_port == expected + out = capsys.readouterr().out + assert f"OpenAI adapter listening on :{FakeAdapter.actual_port}" in out + + def test_unregister_stops_adapter(self, mod, monkeypatch): + _install_fake_adapter(monkeypatch) + FakeAdapter.stopped = False + captured = {} + + ctx = _ctx(captured) + mod.register(ctx) + mod.unregister(ctx) + + assert FakeAdapter.stopped is True + + +# --- serializer shape --------------------------------------------------------- + + +class TestSerialization: + def test_success_returns_valid_json(self, mod): + data = json.loads(mod._success({"answer": "ok"})) + assert data["success"] is True + assert data["answer"] == "ok" + + def test_error_returns_valid_json(self, mod): + data = json.loads(mod._error("nope", code="bad")) + assert data["success"] is False + assert data["error"] == "nope" + assert data["code"] == "bad" + + def test_bid_status_handler_returns_success_key(self, mod): + assert "success" in json.loads(mod._handle_bid_status({})) + + def test_tags_handler_returns_success_key(self, mod): + out = json.loads(mod._handle_tags({})) + assert out["success"] is True + assert "tags" in out + + def test_models_handler_returns_success_key(self, mod): + out = json.loads(mod._handle_bid_models({})) + assert out["success"] is True + assert "models" in out + assert "tags" in out