"""Workflow history and image adoption service.""" from __future__ import annotations from typing import Any from uuid import uuid4 from backend.dto.common import ApiError, ErrorCode from backend.dto.workflow_dto import WorkflowHistoryEntry from backend.dto.workflow_dto import ProfileWorkflow, WorkflowNode from backend.services.image_service import ImageService from backend.services.workflow_service import WorkflowService from core.audit_service import AuditService from core.identity import RequestContext from database.repositories.workflow_repository import WorkflowRepository from core.text_utils import optional_text as _optional_text class HistoryService: def __init__( self, workflow_repository: WorkflowRepository, workflow_service: WorkflowService, image_service: ImageService, audit_service: AuditService, ): self.workflow_repository = workflow_repository self.workflow_service = workflow_service self.image_service = image_service self.audit_service = audit_service def adopt_node_image( self, node_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> WorkflowHistoryEntry: node = self.workflow_service.get_node(node_id) workflow = self.workflow_service.get_workflow(node.workflow_id).workflow payload_metadata = _mapping(payload.get("metadata")) image_id = str(payload.get("image_id") or "").strip() if not image_id: raise ApiError(ErrorCode.VALIDATION_FAILED, "image_id is required", {"field": "image_id"}) next_node = self._resolve_handoff_next_node(workflow, payload_metadata) image = self.image_service.get_image(image_id) if image.node_id != node_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "image does not belong to this node", {"image_id": image_id, "node_id": node_id}, ) if image.is_archived: raise ApiError(ErrorCode.VALIDATION_FAILED, "archived image cannot be adopted", {"image_id": image_id}) updated_node = self.workflow_service.update_node( node_id, {"status": "selected", "selected_image_id": image.image_id}, ctx, allow_locked_adoption=True, ) selected = self.image_service.image_repository.select_exclusive(image) if not image.is_selected else image if selected is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "image not found", {"image_id": image_id}) history = self.workflow_repository.create_history( { "history_id": payload.get("history_id") or new_history_id(), "profile_id": workflow.profile_id, "workflow_id": workflow.workflow_id, "node_id": node_id, "image_id": selected.image_id, "branch_name": updated_node.branch_name, "action": "adopt_image", "title": payload.get("title") or updated_node.title, "prompt": selected.positive_prompt or updated_node.prompt, "metadata": { "image_uri": selected.image_uri, "thumbnail_uri": selected.thumbnail_uri, "source": "node_adoption", **payload_metadata, }, } ) self._persist_stage_handoff( workflow, updated_node, selected, history, payload_metadata, next_node, ctx, ) self.audit_service.record( ctx=ctx, action="adopt_image", target_type="workflow_history", target_id=history.history_id, after_snapshot=history.to_dict(), ) return history def _resolve_handoff_next_node( self, workflow: ProfileWorkflow, metadata: dict[str, Any], ) -> WorkflowNode | None: next_node_id = _optional_text(metadata.get("next_backend_node_id")) if not next_node_id: return None next_node = self.workflow_service.get_node(next_node_id) if next_node.workflow_id != workflow.workflow_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "next_backend_node_id does not belong to this workflow", {"workflow_id": workflow.workflow_id, "next_backend_node_id": next_node_id}, ) if next_node.branch_name != workflow.current_branch: raise ApiError( ErrorCode.VALIDATION_FAILED, "next_backend_node_id does not belong to the current branch", { "workflow_id": workflow.workflow_id, "current_branch": workflow.current_branch, "next_backend_node_id": next_node_id, "next_branch_name": next_node.branch_name, }, ) return next_node def _persist_stage_handoff( self, workflow: ProfileWorkflow, source_node: WorkflowNode, selected, history: WorkflowHistoryEntry, metadata: dict[str, Any], next_node: WorkflowNode | None, ctx: RequestContext, ) -> None: if next_node is None: return # The source adoption advances the authoritative progression first. # Only the newly-derived current node may receive the handoff; a # client-supplied later node cannot skip intermediate stages. self.workflow_service.ensure_node_action_allowed( next_node.node_id, "handoff", node=next_node, ) existing_metadata = dict(workflow.metadata or {}) existing_stage_inputs = existing_metadata.get("stage_inputs") stage_inputs = dict(existing_stage_inputs) if isinstance(existing_stage_inputs, dict) else {} handoff_record = { "schema_version": STAGE_INPUT_SCHEMA_VERSION, "image_id": selected.image_id, "image_uri": selected.image_uri, "thumbnail_uri": selected.thumbnail_uri, "from_node_id": source_node.node_id, "from_node_key": source_node.node_key, "from_review_node_id": metadata.get("ui_review_node_id"), "source_ui_node_id": metadata.get("source_ui_node_id"), "next_ui_node_id": metadata.get("next_ui_node_id"), "history_id": history.history_id, "role": metadata.get("handoff_role") or "next_stage_input", "handoff_bucket": metadata.get("handoff_bucket"), "branch_name": source_node.branch_name, "model_route": selected.model_route, "model_used": selected.model_used, "positive_prompt": selected.positive_prompt or source_node.prompt, "negative_prompt": selected.negative_prompt or source_node.negative_prompt, "locked_source_node": True, "confirmed_at": history.created_at, } stage_inputs[next_node.node_id] = handoff_record handoff_log = existing_metadata.get("stage_review_handoffs") if not isinstance(handoff_log, list): handoff_log = [] handoff_log = [ *handoff_log, { "history_id": history.history_id, "from_node_id": source_node.node_id, "to_node_id": next_node.node_id, "image_id": selected.image_id, "role": handoff_record["role"], "confirmed_at": history.created_at, }, ][-20:] self.workflow_service.update_workflow( workflow.workflow_id, { "current_node_id": next_node.node_id, "metadata": { **existing_metadata, "stage_input_schema_version": STAGE_INPUT_SCHEMA_VERSION, "stage_inputs": stage_inputs, "stage_review_handoffs": handoff_log, "last_stage_review_confirmed_at": history.created_at, "last_stage_review_node_id": metadata.get("ui_review_node_id"), "last_stage_review_image_id": selected.image_id, "current_stage_input_image_id": selected.image_id, }, }, ctx, ) def list_workflow_history( self, workflow_id: str, node_id: str | None = None, ) -> list[WorkflowHistoryEntry]: self.workflow_service.get_workflow(workflow_id) if node_id: node = self.workflow_service.get_node(node_id) if node.workflow_id != workflow_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "node does not belong to this workflow", {"workflow_id": workflow_id, "node_id": node_id}, ) return self.workflow_repository.list_history(workflow_id, node_id=node_id) def save_workflow_snapshot( self, workflow_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> WorkflowHistoryEntry: detail = self.workflow_service.get_workflow(workflow_id) workflow = detail.workflow node_id = _optional_text(payload.get("node_id")) node = None if node_id: node = self.workflow_service.get_node(node_id) if node.workflow_id != workflow_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "node does not belong to this workflow", {"workflow_id": workflow_id, "node_id": node_id}, ) image_id = _optional_text(payload.get("image_id")) if image_id: image = self.image_service.get_image(image_id) if image.workflow_id != workflow_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "image does not belong to this workflow", { "workflow_id": workflow_id, "image_id": image_id, "image_workflow_id": image.workflow_id, }, ) if image.node_id: image_node = self.workflow_service.get_node(image.node_id) if image_node.workflow_id != workflow_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "image node does not belong to this workflow", { "workflow_id": workflow_id, "image_id": image_id, "image_node_id": image.node_id, "image_node_workflow_id": image_node.workflow_id, }, ) if node_id and image.node_id != node_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "image does not belong to this node", {"workflow_id": workflow_id, "node_id": node_id, "image_id": image_id}, ) history = self.workflow_repository.create_history( { "history_id": payload.get("history_id") or new_history_id(), "profile_id": workflow.profile_id, "workflow_id": workflow.workflow_id, "node_id": node_id, "image_id": image_id, "branch_name": payload.get("branch_name") or workflow.current_branch or "main", "action": payload.get("action") or "save_version", "title": payload.get("title") or workflow.display_name, "prompt": payload.get("prompt") or (node.prompt if node else None), "metadata": { "source": "workflow_snapshot", "workflow": workflow.to_dict(), "nodes": [item.to_dict() for item in detail.nodes] if payload.get("include_nodes", True) else [], **(payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {}), }, } ) self.audit_service.record( ctx=ctx, action="save_workflow_snapshot", target_type="workflow_history", target_id=history.history_id, after_snapshot=history.to_dict(), ) return history def new_history_id() -> str: return f"hist_{uuid4().hex}" STAGE_INPUT_SCHEMA_VERSION = "2026-07-09.stage-input-bucket.v1" def _mapping(value: Any) -> dict[str, Any]: return value if isinstance(value, dict) else {}