feat(api): implementa /executions con invoke + HITL approve/reject + persistencia

- POST /agents/{name}/invoke, GET /executions, GET /executions/{trace_id},
  POST /executions/{trace_id}/{approve,reject}.
- execution_index.json persiste trace_id → (agent_name, version) para reconstruir
  el contexto en approve/reject tras un reinicio.
- Refactor del orchestrator: split _snapshot → _build_execution + _snapshot, nuevo
  método público snapshot() (lee estado sin avanzar). Sustituye a los helpers
  _snapshot_execution/_build_graph_for_snapshot del plan, incompatibles con el
  checkpointer por-llamada.
- Aliases Annotated[...] de dependencias movidos a deps.py.
- Fixture mínima tests/fixtures/policies/default/.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Juan
2026-05-10 15:38:44 +02:00
co-authored by Claude Opus 4.7
parent 13ba1f7826
commit 8927b192f8
9 changed files with 420 additions and 39 deletions
+8
View File
@@ -0,0 +1,8 @@
name: default
versions:
- id: v1
hash: testhashp1
author: Juan
message: fixture mínima
created_at: 2026-04-01T00:00:00Z
active_version: v1
+6
View File
@@ -0,0 +1,6 @@
name: default
version: v1
description: Política mínima para tests del core (sin validadores)
input_validators: []
output_validators: []
on_validator_error: fail_closed
+124
View File
@@ -0,0 +1,124 @@
"""Tests del router /executions: invoke, get, list, approve, reject."""
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from agentforge_core.api import deps
from agentforge_core.main import create_app
FIXTURES = Path(__file__).parent.parent / "fixtures"
@pytest.fixture(autouse=True)
def patch_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("DATA_DIR", str(tmp_path))
monkeypatch.setenv("AGENTS_DIR", str(FIXTURES / "agents"))
monkeypatch.setenv("POLICIES_DIR", str(FIXTURES / "policies"))
monkeypatch.setenv("LLM_PROVIDER", "mock")
for fn in (
deps.get_settings,
deps.get_registry,
deps.get_policy_store,
deps.get_orchestrator,
deps.get_llm_provider,
deps.get_guardrail_engine,
):
fn.cache_clear()
@pytest.fixture
def client() -> TestClient:
return TestClient(create_app())
def test_invoke_devuelve_execution_completada(client: TestClient) -> None:
r = client.post("/agents/incident_analyzer/invoke", json={"input": "degradación MOS pool SBC"})
assert r.status_code == 200
body = r.json()
assert body["status"] == "completed"
assert body["agent_name"] == "incident_analyzer"
assert body["agent_version"] == "v1"
assert body["needs_human_for"] is None
def test_invoke_agente_inexistente_404(client: TestClient) -> None:
r = client.post("/agents/inexistente/invoke", json={"input": "x"})
assert r.status_code == 404
def test_invoke_riesgo_alto_pausa_hitl(client: TestClient) -> None:
r = client.post("/agents/incident_analyzer/invoke", json={"input": "caída registros sip"})
assert r.status_code == 200
body = r.json()
assert body["status"] == "awaiting_approval"
assert body["needs_human_for"]
assert {a["id"] for a in body["needs_human_for"]} == {"act-1"}
def test_get_execution_existe_tras_invoke(client: TestClient) -> None:
trace_id = client.post(
"/agents/incident_analyzer/invoke", json={"input": "degradación MOS pool SBC"}
).json()["trace_id"]
r = client.get(f"/executions/{trace_id}")
assert r.status_code == 200
assert r.json()["trace_id"] == trace_id
def test_get_execution_inexistente_404(client: TestClient) -> None:
r = client.get("/executions/00000000-0000-0000-0000-000000000000")
assert r.status_code == 404
def test_list_executions_incluye_la_completada(client: TestClient) -> None:
client.post("/agents/incident_analyzer/invoke", json={"input": "degradación MOS pool SBC"})
r = client.get("/executions")
assert r.status_code == 200
rows = r.json()
assert len(rows) == 1
assert rows[0]["status"] == "completed"
assert rows[0]["n_proposed_actions"] == 1
def test_approve_resume_completa_ejecucion(client: TestClient) -> None:
invoked = client.post(
"/agents/incident_analyzer/invoke", json={"input": "caída registros sip"}
).json()
trace_id = invoked["trace_id"]
action_ids = [a["id"] for a in invoked["needs_human_for"]]
r = client.post(
f"/executions/{trace_id}/approve",
json={"approved_action_ids": action_ids, "comment": "OK adelante"},
)
assert r.status_code == 200
body = r.json()
assert body["status"] == "completed"
assert {a["id"] for a in body["final_output"]["approved_actions"]} == {"act-1"}
def test_reject_marca_failed(client: TestClient) -> None:
trace_id = client.post(
"/agents/incident_analyzer/invoke", json={"input": "caída registros sip"}
).json()["trace_id"]
r = client.post(f"/executions/{trace_id}/reject", json={"reason": "no procede ahora"})
assert r.status_code == 200
body = r.json()
assert body["status"] == "failed"
assert "rejected_by_human" in body["error"]
def test_approve_sobre_estado_no_pausado_da_409(client: TestClient) -> None:
trace_id = client.post(
"/agents/incident_analyzer/invoke", json={"input": "degradación MOS pool SBC"}
).json()["trace_id"]
r = client.post(f"/executions/{trace_id}/approve", json={"approved_action_ids": []})
assert r.status_code == 409
def test_approve_trace_id_desconocido_da_404(client: TestClient) -> None:
r = client.post(
"/executions/11111111-1111-1111-1111-111111111111/approve",
json={"approved_action_ids": []},
)
assert r.status_code == 404
+18
View File
@@ -2,6 +2,7 @@
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
import pytest
@@ -64,6 +65,23 @@ async def test_invoke_camino_feliz(orchestrator: AgentOrchestrator) -> None:
]
async def test_snapshot_relee_estado_sin_avanzar(orchestrator: AgentOrchestrator) -> None:
agent = _agent()
paused = await orchestrator.invoke(
agent_def=agent, policy=_policy(), user_input="caída registros sip"
)
again = await orchestrator.snapshot(agent_def=agent, policy=_policy(), trace_id=paused.trace_id)
assert again is not None
assert again.status == "awaiting_approval"
assert again.trace_id == paused.trace_id
# Idempotente: leer no añade pasos al decision_path.
assert [s.step for s in again.decision_path] == [s.step for s in paused.decision_path]
async def test_snapshot_trace_id_desconocido_devuelve_none(orchestrator: AgentOrchestrator) -> None:
assert await orchestrator.snapshot(agent_def=_agent(), policy=_policy(), trace_id=uuid4()) is None
async def test_invoke_pausa_hitl_y_resume_aprueba(orchestrator: AgentOrchestrator) -> None:
agent = _agent()
paused = await orchestrator.invoke(