bugfixes: transaction parameter collector, generic formatting messages, guardrails, prompts. Testing contas

This commit is contained in:
2026-08-20 00:23:50 -03:00
parent f9c66b4792
commit 762f6fb024
231 changed files with 3999 additions and 141 deletions

View File

@@ -88,3 +88,202 @@ async def test_transaction_waits_then_executes_after_confirmation():
assert runtime.calls[-1][0] == "solicitar_devolucao"
assert runtime.calls[-1][1]["confirmed"] is True
assert second[-1]["ok"] is True
class _ContestPolicyRouter:
def __init__(self):
from types import SimpleNamespace
self.registry = SimpleNamespace(
tools={"contestar_cobranca": object()},
get_tool=lambda name: SimpleNamespace(selection_keywords=["contestar", "não contratei", "nao contratei"]),
)
def resolve_execution_policy(self, tool_name, arguments=None):
return {
"operation_type": "transactional",
"require_confirmation": True,
"requires": ["subject", "valor"],
"policy_source": "test",
}
def validate_execution_policy(self, tool_name, arguments=None):
policy = self.resolve_execution_policy(tool_name, arguments)
return True, None, policy
class _ContestRuntime(AgentRuntimeMixin):
def __init__(self):
self.tool_router = _ContestPolicyRouter()
self.calls = []
async def _call_mcp_tool(self, tool_name, arguments, state):
self.calls.append((tool_name, dict(arguments)))
return {"ok": True, "tool_name": tool_name, "result": {"status": "OPENED"}}
@pytest.mark.asyncio
async def test_collecting_parameters_does_not_replace_collected_subject_with_stale_context():
"""A later value-only turn must not replace an already collected subject.
Regression reproduced from Contas: subject was collected as TIM CTRL, while
context/tool_arguments still exposed TIM Fashion from another transaction.
When the user supplied only R$ 71,99, the stale context used to overwrite
the collected subject before confirmation.
"""
runtime = _ContestRuntime()
state = {
"user_text": "R$ 71,99",
"sanitized_input": "R$ 71,99",
"route": "contestacao_agent",
"intent": "state:COLLECTING_CONTESTACAO_PARAMETERS",
"transaction_status": "COLLECTING_PARAMETERS",
"selected_tool_call": {
"tool_name": "contestar_cobranca",
"arguments": {
"subject": "TIM CTRL Redes Sociais 8.0",
"motivo": "não contratei",
},
},
# Simulates stale contextual arguments left by another action/session turn.
"context": {
"tool_arguments": {
"subject": "TIM Fashion Mensal",
"valor": 71.99,
}
},
}
result = await runtime.execute_tools_for_intent(state, tools=[])
assert result[-1]["transaction_status"] == "AWAITING_CONFIRMATION"
assert state["pending_tool_call"]["arguments"]["subject"] == "TIM CTRL Redes Sociais 8.0"
assert state["pending_tool_call"]["arguments"]["valor"] == 71.99
assert state["pending_tool_call"]["arguments"]["motivo"] == "não contratei"
assert state["pending_tool_call"]["arguments"]["query"] == "R$ 71,99"
assert runtime.calls == []
class _InitialContestLLM:
async def ainvoke(self, messages, **kwargs):
prompt = messages[0]["content"]
if "Campo: subject" in prompt:
return {"content": '{"subject": "TIM CTRL Redes Sociais 8.0"}'}
if "Campo: valor" in prompt:
return {"content": '{"valor": null}'}
if "Campo: motivo" in prompt:
return {"content": '{"motivo": "não contratei"}'}
return {"content": '{}'}
class _InitialContestRouter(_ContestPolicyRouter):
def resolve_execution_policy(self, tool_name, arguments=None):
return {
"operation_type": "transactional",
"require_confirmation": True,
"requires": ["subject"],
"policy_source": "test",
}
def parameter_extract_rules(self, tool_name):
return {
"subject": {"from": "message", "strategy": "llm", "type": "string", "description": "item"},
"valor": {"from": "message", "strategy": "llm", "type": "number", "description": "valor"},
"motivo": {"from": "message", "strategy": "llm", "type": "string", "description": "motivo"},
}
class _InitialContestRuntime(AgentRuntimeMixin):
def __init__(self):
self.tool_router = _InitialContestRouter()
self.llm = _InitialContestLLM()
self.calls = []
async def _call_mcp_tool(self, tool_name, arguments, state):
self.calls.append((tool_name, dict(arguments)))
return {"ok": True, "tool_name": tool_name, "result": {"status": "OPENED"}}
@pytest.mark.asyncio
async def test_new_contestation_does_not_inherit_subject_or_value_from_previous_transaction():
runtime = _InitialContestRuntime()
state = {
"user_text": "nao contratei TIM CTRL Redes Sociais 8.0",
"sanitized_input": "nao contratei TIM CTRL Redes Sociais 8.0",
"mcp_tools": ["contestar_cobranca"],
"route": "contestacao_agent",
"intent": "contas_contestation",
"context": {
"tool_arguments": {
"subject": "TIM Fashion Mensal",
"valor": 10.0,
"motivo": "contestação antiga",
}
},
}
result = await runtime.execute_tools_for_intent(state)
pending = state["pending_tool_call"]["arguments"]
assert result[-1]["transaction_status"] == "AWAITING_CONFIRMATION"
assert pending["subject"] == "TIM CTRL Redes Sociais 8.0"
assert pending["motivo"] == "não contratei"
assert "valor" not in pending
assert runtime.calls == []
@pytest.mark.asyncio
async def test_closed_transaction_is_not_operational_context_for_next_turn():
runtime = _InitialContestRuntime()
state = {
"user_text": "nao contratei TIM CTRL Redes Sociais 8.0",
"sanitized_input": "nao contratei TIM CTRL Redes Sociais 8.0",
"mcp_tools": ["contestar_cobranca"],
"route": "contestacao_agent",
"intent": "contas_contestation",
# Historical/closed transaction must never feed the new one.
"transaction_status": "COMPLETED",
"selected_tool_call": {
"tool_name": "cancelar_vas_avulso",
"arguments": {"subject": "TIM Fashion Mensal", "valor": 10.0},
},
"pending_tool_call": {},
"context": {
"tool_arguments": {
"subject": "TIM Fashion Mensal",
"valor": 10.0,
}
},
}
result = await runtime.execute_tools_for_intent(state)
assert result[-1]["transaction_status"] == "AWAITING_CONFIRMATION"
assert state["active_transaction"]["tool_name"] == "contestar_cobranca"
assert state["active_transaction"]["arguments"]["subject"] == "TIM CTRL Redes Sociais 8.0"
assert state["pending_tool_call"]["tool_name"] == "contestar_cobranca"
assert state["pending_tool_call"]["arguments"]["subject"] == "TIM CTRL Redes Sociais 8.0"
assert state["last_transaction"]["tool_name"] == "cancelar_vas_avulso"
assert state["last_transaction"]["arguments"]["subject"] == "TIM Fashion Mensal"
@pytest.mark.asyncio
async def test_terminal_confirmation_closes_active_transaction_and_clears_latches():
runtime = _Runtime()
state = {
"user_text": "Quero devolver o pedido 123 porque me arrependi",
"sanitized_input": "Quero devolver o pedido 123 porque me arrependi",
"mcp_tools": ["consultar_pedido", "solicitar_devolucao"],
"route": "support_agent",
"intent": "retail_support_exchange_return",
}
await runtime.execute_tools_for_intent(state)
assert state["active_transaction"]["status"] == "AWAITING_CONFIRMATION"
state["user_text"] = "sim"
state["sanitized_input"] = "sim"
await runtime.execute_tools_for_intent(state)
assert state["transaction_status"] == "COMPLETED"
assert state["active_transaction"] is None
assert state["selected_tool_call"] == {}
assert state["pending_tool_call"] == {}
assert state["missing_parameters"] == []
assert state["next_state"] is None
assert state["last_transaction"]["tool_name"] == "solicitar_devolucao"
assert state["last_transaction"]["status"] == "COMPLETED"