"""Recording an Execution's progress for audit and reporting. Two adapters sit behind ExecutionRecorder: InMemoryRecorder for tests, and DatabaseRecorder, which reuses the existing DatabaseManager tables until the Execution store (review candidate 03) replaces them. """ from __future__ import annotations import asyncio import json import uuid from collections import defaultdict from collections.abc import Mapping, Sequence from typing import Any, Protocol from app.states.ledger import LedgerEvent SESSION_AGENT_NAME = "solution-architect" class ExecutionRecorder(Protocol): async def record_events( self, execution_id: str, events: Sequence[LedgerEvent] ) -> None: ... async def record_submission( self, execution_id: str, kind: str, content: str, attachments: Mapping[str, str], ) -> None: ... async def record_status( self, execution_id: str, *, session_id: str, workflow_request: str, status: str, current_phase: str, details: Mapping[str, Any], ) -> None: ... async def record_lesson_candidates( self, execution_id: str, record: Mapping[str, Any] ) -> None: ... class InMemoryRecorder: def __init__(self) -> None: self.events: dict[str, list[LedgerEvent]] = defaultdict(list) self.submissions: dict[str, list[dict[str, Any]]] = defaultdict(list) self.statuses: dict[str, list[dict[str, Any]]] = defaultdict(list) self.lessons: dict[str, dict[str, Any]] = {} async def record_lesson_candidates( self, execution_id: str, record: Mapping[str, Any] ) -> None: self.lessons[execution_id] = dict(record) async def record_events( self, execution_id: str, events: Sequence[LedgerEvent] ) -> None: self.events[execution_id].extend(events) async def record_submission( self, execution_id: str, kind: str, content: str, attachments: Mapping[str, str], ) -> None: self.submissions[execution_id].append( {"kind": kind, "content": content, "attachments": dict(attachments)} ) async def record_status( self, execution_id: str, *, session_id: str, workflow_request: str, status: str, current_phase: str, details: Mapping[str, Any], ) -> None: self.statuses[execution_id].append( { "session_id": session_id, "workflow_request": workflow_request, "status": status, "current_phase": current_phase, "details": dict(details), } ) class DatabaseRecorder: """Writes to DatabaseManager (blocking) off the event loop.""" def __init__(self, db_manager: Any = None) -> None: if db_manager is None: from app.database import get_db_manager db_manager = get_db_manager() self._db = db_manager async def record_events( self, execution_id: str, events: Sequence[LedgerEvent] ) -> None: for event in events: await asyncio.to_thread( self._db.record_orchestrator_log, log_id=str(uuid.uuid4()), execution_id=execution_id, iteration=event.sequence, review_status=event.type, reviewer_agent=event.actor, feedback=f"{event.subject}: {event.detail}".rstrip(": "), ) async def record_submission( self, execution_id: str, kind: str, content: str, attachments: Mapping[str, str], ) -> None: files = {f"deliverables/{kind}.md": content, **attachments} for file_path, file_content in files.items(): await asyncio.to_thread( self._db.save_artifact, artifact_id=str(uuid.uuid4()), execution_id=execution_id, artifact_type=kind, file_path=file_path, content=file_content, ) async def record_status( self, execution_id: str, *, session_id: str, workflow_request: str, status: str, current_phase: str, details: Mapping[str, Any], ) -> None: await asyncio.to_thread( self._db.save_workflow_execution, execution_id=execution_id, session_id=session_id, status=status, current_phase=current_phase, loop_count=int(details.get("revisions", 0)), request_summary=workflow_request, results=dict(details), ) await asyncio.to_thread( self._db.save_session, session_id=session_id, agent_name=SESSION_AGENT_NAME, state_data={"latest_execution_id": execution_id, "status": status}, ) async def record_lesson_candidates( self, execution_id: str, record: Mapping[str, Any] ) -> None: await asyncio.to_thread( self._db.save_artifact, artifact_id=str(uuid.uuid4()), execution_id=execution_id, artifact_type="lesson_candidates", file_path="lesson-candidates.json", content=json.dumps(dict(record), ensure_ascii=False), )