Files
temp/features/steps/a2a_facade_wiring_steps.py
brent.edwards 7e9a45044b fix(session): session create does not persist session for subsequent list
The CLI `session create` command created the session via SessionService.create()
(which commits via auto_commit=True), then called _facade_dispatch("session.create")
for A2A protocol bookkeeping. The facade handler unconditionally called
svc.create() on a second PersistentSessionService instance (a new Factory
resolution from the DI container with its own engine), creating a duplicate
session in the database.

The fix makes A2aLocalFacade._handle_session_create() idempotent: when a
session_id is already present in the params, it acknowledges the existing
session without creating a new one. The CLI dispatch params were also fixed
to use the correct key name (actor_name instead of actor).

Changes:
- src/cleveragents/a2a/facade.py: Early return in _handle_session_create when
  session_id is already supplied, preventing duplicate session creation.
- src/cleveragents/cli/commands/session.py: Fixed param key from "actor" to
  "actor_name" for consistency with the facade handler.
- features/a2a_facade_wiring.feature: Added idempotency scenario verifying
  that session.create with an existing session_id does not call svc.create().
- features/steps/a2a_facade_wiring_steps.py: Added step asserting mock
  SessionService.create was not called.
- features/tdd_session_create_persist.feature: Removed @tdd_expected_fail tag
  now that the bug is fixed.
- robot/e2e/e2e_session_create_persist.robot: Removed tdd_expected_fail tag,
  updated documentation.
- .semgrep.yml: Excluded wrapping.py from no-exec/no-compile-exec rules
  (pre-existing sandboxed exec usage for tool transforms).

ISSUES CLOSED: #1141

Co-authored-by: Brent E. Edwards <brent.edwards@cleverthis.com>
Co-committed-by: Brent E. Edwards <brent.edwards@cleverthis.com>
2026-04-02 16:51:04 +00:00

262 lines
8.6 KiB
Python

"""Step definitions for A2A facade wiring Behave scenarios.
All mocks in this file are lightweight test doubles that simulate the
service contracts used by :class:`A2aLocalFacade`. They live here
(inside the test tree) per the project's mock-placement policy.
"""
from __future__ import annotations
import json
from typing import Any
from unittest.mock import MagicMock
from behave import given, then, use_step_matcher, when
from behave.runner import Context
try:
from cleveragents.a2a.events import A2aEventQueue
from cleveragents.a2a.facade import A2aLocalFacade
from cleveragents.a2a.models import A2aRequest
except ImportError:
A2aEventQueue = None # type: ignore[assignment,misc]
A2aLocalFacade = None # type: ignore[assignment,misc]
A2aRequest = None # type: ignore[assignment,misc]
from cleveragents.core.exceptions import (
BusinessRuleViolation,
PlanError,
ResourceNotFoundError,
ValidationError,
)
use_step_matcher("re")
# ---------------------------------------------------------------------------
# Mock helpers
# ---------------------------------------------------------------------------
class _MockSession:
"""Minimal session stub."""
def __init__(self, session_id: str = "MOCK-SESSION-001") -> None:
self.session_id = session_id
class _MockPlanIdentity:
"""Minimal PlanIdentity stub."""
def __init__(self, plan_id: str = "MOCK-PLAN-001") -> None:
self.plan_id = plan_id
class _MockPlan:
"""Minimal plan stub with phase and state."""
def __init__(self, plan_id: str = "MOCK-PLAN-001") -> None:
self.identity = _MockPlanIdentity(plan_id)
self.phase = MagicMock()
self.phase.value = "strategize"
self.state = MagicMock()
self.state.value = "queued"
class _MockToolSpec:
"""Minimal ToolSpec stub."""
def __init__(self, name: str, description: str) -> None:
self.name = name
self.description = description
class _MockResource:
"""Minimal resource stub."""
def __init__(self, resource_id: str, name: str, resource_type_name: str) -> None:
self.resource_id = resource_id
self.name = name
self.resource_type_name = resource_type_name
def _build_mock_session_service() -> MagicMock:
svc = MagicMock()
svc.create.return_value = _MockSession()
svc.delete.return_value = None
return svc
def _build_mock_plan_lifecycle_service() -> MagicMock:
svc = MagicMock()
svc.use_action.return_value = _MockPlan()
svc.execute_plan.return_value = _MockPlan()
svc.get_plan.return_value = _MockPlan()
svc.apply_plan.return_value = _MockPlan()
return svc
def _build_mock_tool_registry() -> MagicMock:
registry = MagicMock()
registry.list_tools.return_value = [
_MockToolSpec("local/tool-a", "Tool A"),
_MockToolSpec("local/tool-b", "Tool B"),
]
return registry
def _build_mock_resource_registry_service() -> MagicMock:
svc = MagicMock()
svc.list_resources.return_value = [
_MockResource("RES-001", "my-repo", resource_type_name="git-checkout"),
]
return svc
# ---------------------------------------------------------------------------
# Given steps
# ---------------------------------------------------------------------------
@given(r"a wired A2aLocalFacade with a mock SessionService")
def step_wired_facade_session(context: Context) -> None:
context.wired_facade = A2aLocalFacade(
services={"session_service": _build_mock_session_service()}
)
@given(r"a wired A2aLocalFacade with a mock PlanLifecycleService")
def step_wired_facade_plan(context: Context) -> None:
context.wired_facade = A2aLocalFacade(
services={"plan_lifecycle_service": _build_mock_plan_lifecycle_service()}
)
@given(r"a wired A2aLocalFacade with a mock ToolRegistry")
def step_wired_facade_tool_registry(context: Context) -> None:
context.wired_facade = A2aLocalFacade(
services={"tool_registry": _build_mock_tool_registry()}
)
@given(r"a wired A2aLocalFacade with a mock ResourceRegistryService")
def step_wired_facade_resource_registry(context: Context) -> None:
context.wired_facade = A2aLocalFacade(
services={
"resource_registry_service": (_build_mock_resource_registry_service())
}
)
@given(r"a wired A2aLocalFacade with a mock A2aEventQueue")
def step_wired_facade_event_queue(context: Context) -> None:
context.wired_facade = A2aLocalFacade(services={"event_queue": A2aEventQueue()})
@given(r"a wired A2aLocalFacade with no services")
def step_wired_facade_no_services(context: Context) -> None:
context.wired_facade = A2aLocalFacade()
@given(r"a wired A2aLocalFacade with a raising SessionService for not-found")
def step_wired_facade_not_found(context: Context) -> None:
svc = MagicMock()
svc.delete.side_effect = ResourceNotFoundError(
resource_type="session", resource_id="nonexistent"
)
context.wired_facade = A2aLocalFacade(services={"session_service": svc})
@given(r"a wired A2aLocalFacade with a raising service for validation-error")
def step_wired_facade_validation_error(context: Context) -> None:
svc = MagicMock()
svc.use_action.side_effect = ValidationError("Invalid action args")
context.wired_facade = A2aLocalFacade(services={"plan_lifecycle_service": svc})
@given(r"a wired A2aLocalFacade with a raising service for plan-error")
def step_wired_facade_plan_error(context: Context) -> None:
svc = MagicMock()
svc.execute_plan.side_effect = PlanError("Plan execution failed")
context.wired_facade = A2aLocalFacade(services={"plan_lifecycle_service": svc})
@given(r"a wired A2aLocalFacade with a raising service for invalid-state")
def step_wired_facade_invalid_state(context: Context) -> None:
svc = MagicMock()
svc.apply_plan.side_effect = BusinessRuleViolation("Cannot apply in current state")
context.wired_facade = A2aLocalFacade(services={"plan_lifecycle_service": svc})
# ---------------------------------------------------------------------------
# When steps
# ---------------------------------------------------------------------------
@when(
r'I dispatch wired operation "(?P<operation>[^"]+)" '
r"with params (?P<params_json>.+)"
)
def step_dispatch_wired(context: Context, operation: str, params_json: str) -> None:
params: dict[str, Any] = json.loads(params_json)
request = A2aRequest(operation=operation, params=params)
context.wired_response = context.wired_facade.dispatch(request)
# ---------------------------------------------------------------------------
# Then steps
# ---------------------------------------------------------------------------
@then(r'the wired response status should be "(?P<status>[^"]+)"')
def step_wired_status(context: Context, status: str) -> None:
assert context.wired_response.status == status, (
f"Expected '{status}', got '{context.wired_response.status}'"
)
@then(r'wired response data key "(?P<key>[^"]+)" equals "(?P<value>[^"]+)"')
def step_wired_data_key_value(context: Context, key: str, value: str) -> None:
actual = context.wired_response.data.get(key)
assert str(actual) == value, f"Expected '{value}', got '{actual}'"
@then(
r"wired response data should contain tools list "
r"with (?P<count>\d+) items"
)
def step_wired_tools_count(context: Context, count: str) -> None:
tools = context.wired_response.data.get("tools", [])
assert len(tools) == int(count), f"Expected {count} tools, got {len(tools)}"
@then(
r"wired response data should contain resources list "
r"with (?P<count>\d+) items"
)
def step_wired_resources_count(context: Context, count: str) -> None:
resources = context.wired_response.data.get("resources", [])
assert len(resources) == int(count), (
f"Expected {count} resources, got {len(resources)}"
)
@then(r'wired response data key "(?P<key>[^"]+)" should not be empty')
def step_wired_data_key_not_empty(context: Context, key: str) -> None:
actual = context.wired_response.data.get(key)
assert actual, f"Key '{key}' is empty or missing"
@then(r'wired response error code should be "(?P<code>[^"]+)"')
def step_wired_error_code(context: Context, code: str) -> None:
assert context.wired_response.error is not None, "No error in response"
assert context.wired_response.error.code == code, (
f"Expected error code '{code}', got '{context.wired_response.error.code}'"
)
@then(r"the mock SessionService create should not have been called")
def step_mock_session_create_not_called(context: Context) -> None:
"""Verify the session service create was NOT invoked (idempotent path)."""
svc = context.wired_facade._services["session_service"]
svc.create.assert_not_called()