Files
roboco/tests/unit/runtime/test_mcp_cli_arg_uuid_auth.py
312ec990dd fix: prod triage 2026-07-08 — MCP auth residue, gateway envelopes, verb-loop cap, A2A interjection, manual spawn UX (#334)
* fix(auth): pass agent UUID to CLI-arg MCP servers (optimal/docs/search)

The container token is HMAC-signed over the agent UUID (#314), but the
optimal/docs/search MCP servers received the slug as their CLI arg and
sent X-Agent-ID=<slug>, so every research/RAG/docs call 401ed with
signature mismatch under enforced auth. Pass the already-computed
agent_uuid in the three args lists instead.

* fix(gateway): include remediate in gateway.rejected audit details

Conventions-gate rejections carry the offending file:line listing only
in the envelope's remediate field, which the audit row dropped -- ops
logs showed just the violation count with no way to see what blocked.

* fix(gateway): return envelope on do/commit git failure

A GitError from the commit verb propagated to the generic middleware
handler, so agents got a raw error blob with no remediate/next. Catch
it and return an error envelope; 'no changes added to commit' with an
explicit files list now names the mismatch and the omit-files fallback.

* fix(agent-sdk): absolute rejection cap breaks slow-drip verb loops

The verb circuit breaker only counted rejections inside a 60s sliding
window, so an agent retrying i_am_done every 3-4 minutes looped for 30+
minutes without tripping it. Add a session-scoped cumulative per-(verb,
task) cap at 3x the windowed limit that trips regardless of pacing.

* feat(a2a): CEO chime-in interjects into the viewed conversation

Previously reply_as_ceo re-homed the message into a canonical CEO<->target
conversation with no panel surface, so a chime-in reported success but was
invisible and only opportunistically delivered. interject_as_ceo now inserts
the message into the conversation being viewed (from_agent=ceo, directed via
an @target content prefix), bumps that conversation's counters with the
unread ping keyed to the addressed participant, and both participants see it
in transcript and read_a2a.

* feat(panel): manual spawn carries task + message, surfaces refusals

The agent detail page spawned with no request body (task/message impossible),
the spawn button could double-fire (2.5ms double-POST seen live), and refusal
reasons never reached the UI: readiness refusals were generic 500s and the
already-running no-op looked like success. Detail page now uses
SpawnAgentDialog, a synchronous ref guard blocks re-entry, AgentReadinessError
maps to 409 with its reason shown, already_running is signalled and toasted,
and a task_id builds a task-aware prompt instructing the claim (task_id alone
never did), with the CEO's message appended as a note.

* test(panel): align a2a page test with the interjection footer copy

The chime-in rebuild changed the composer footer; the page-level test
asserting the old copy was outside the rebuild's scoped vitest run.

* fix(api): commit the request DB session before the response is sent

FastAPI unwinds yield-dependencies after the response bytes go out, so
get_db's post-yield commit raced the client's next request -- a verb
could return ok while its claim/status write was still uncommitted (the
e2e ok-without-effect flake family), and a failed commit was silently
lost behind an already-sent 200. DbCommitMiddleware (innermost, pure
ASGI) commits the session stashed by get_db_committed before forwarding
http.response.start; commit failure now surfaces as a 5xx. get_db is
untouched for its direct non-request callers.

* fix(db): invalidate, not rollback, the session on request cancellation

With the commit moved into the send path, the flow-verb timeout can
cancel mid-commit; rolling back then issues another command over an
asyncpg connection stranded mid-wire-protocol, and the poisoned
connection segfaults uvloop/asyncpg when a later checkout recycles it
(3/3 identical CI faulthandler dumps). On CancelledError discard the
connection via session.invalidate() -- SQLAlchemy's documented handling
for a timeout during commit -- and keep rollback for plain exceptions.

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-07-08 10:41:02 +02:00

88 lines
3.6 KiB
Python

"""roboco-optimal/docs/search receive the agent's CLI arg as sys.argv[1] and
forward it verbatim as X-Agent-ID via ApiClient/_get_agent_headers. The spawn
token (_append_agent_auth_env) is signed over the agent's UUID, so that CLI
arg must be the UUID too, or verify_agent_token 401s with a signature
mismatch even though role/team resolve fine either way (get_agent_role/
get_agent_team accept slug or UUID via _resolve_to_slug).
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import TYPE_CHECKING
from roboco.agents_config import AGENT_UUIDS, verify_agent_token
from roboco.config import settings
from roboco.mcp import utils as mcp_utils
from roboco.models.runtime import OrchestratorAgentConfig as AgentConfig
from roboco.runtime.orchestrator import AgentOrchestrator
if TYPE_CHECKING:
import pytest
# main-pm carries roboco-optimal (always), roboco-docs (docs_roles) and
# roboco-search (research_roles, research_enabled defaults True) all at once.
_AGENT_SLUG = "main-pm"
_CLI_ARG_SERVERS = ("roboco-optimal", "roboco-docs", "roboco-search")
def _spawn_token(monkeypatch: pytest.MonkeyPatch) -> str:
"""Mint the token exactly as _append_agent_auth_env does at spawn."""
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", "spawn-secret")
monkeypatch.setattr(settings, "agent_token_ttl_seconds", 3600)
cmd: list[str] = []
config = AgentConfig(
agent_id=_AGENT_SLUG,
blueprint_path=Path("/app/blueprints/main-pm.md"),
provider_type="anthropic",
)
AgentOrchestrator._append_agent_auth_env(cmd, config)
for i, flag in enumerate(cmd):
if flag == "-e" and cmd[i + 1].startswith("ROBOCO_AGENT_TOKEN="):
return cmd[i + 1].split("=", 1)[1]
raise AssertionError("ROBOCO_AGENT_TOKEN not found in cmd")
async def test_cli_arg_servers_get_uuid_not_slug() -> None:
"""_generate_mcp_config passes the UUID (not the slug) as sys.argv[1]
to the three servers that identify their agent via CLI arg."""
orch = AgentOrchestrator.__new__(AgentOrchestrator)
config_path = await orch._generate_mcp_config(_AGENT_SLUG)
config = json.loads(Path(config_path).read_text())
servers = config["mcpServers"]
expected_uuid = AGENT_UUIDS[_AGENT_SLUG]
for name in _CLI_ARG_SERVERS:
assert name in servers, f"{name} should be mounted for {_AGENT_SLUG}"
cli_arg = servers[name]["args"][-1]
assert cli_arg == expected_uuid, (
f"{name} sys.argv[1] is {cli_arg!r}, expected the UUID "
f"{expected_uuid!r} — a slug here mismatches the UUID-signed "
f"spawn token and every call 401s."
)
async def test_cli_arg_servers_headers_verify_against_spawn_token(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The header tuple _get_agent_headers builds from the CLI arg
_generate_mcp_config hands these servers must verify against the token
the orchestrator actually injects into the container env."""
token = _spawn_token(monkeypatch)
monkeypatch.setenv("ROBOCO_AGENT_TOKEN", token)
orch = AgentOrchestrator.__new__(AgentOrchestrator)
config_path = await orch._generate_mcp_config(_AGENT_SLUG)
config = json.loads(Path(config_path).read_text())
servers = config["mcpServers"]
for name in _CLI_ARG_SERVERS:
cli_arg = servers[name]["args"][-1]
headers = mcp_utils._get_agent_headers(cli_arg)
assert verify_agent_token(
headers["X-Agent-Token"],
headers["X-Agent-ID"],
headers["X-Agent-Role"],
headers.get("X-Agent-Team", ""),
), f"{name}'s header tuple ({headers}) failed verify_agent_token"