"""Deterministic execution helpers for character workflows.""" from __future__ import annotations from typing import Any from backend.dto.common import ApiError, ErrorCode from backend.dto.profile_dto import CharacterProfile from backend.dto.workflow_dto import ProfileWorkflow, WorkflowNode from backend.services.workflow_service import WorkflowService from backend.services.workflow_progression_service import ( CHARACTER_GRADUAL_PROGRESSION_VERSION, character_execution_metadata, character_gradual_progression, ) from core.identity import RequestContext from engines.character_flow import canonical_gradual_node_key CHARACTER_WORKFLOW_TYPES = {"character_fast", "character_gradual", "quick_profile"} class CharacterWorkflowService: def __init__(self, workflow_service: WorkflowService): self.workflow_service = workflow_service def execute_workflow(self, workflow_id: str, ctx: RequestContext) -> dict[str, Any]: detail = self.workflow_service.get_workflow(workflow_id) workflow = detail.workflow if workflow.workflow_type not in CHARACTER_WORKFLOW_TYPES: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow is not a character workflow", {"workflow_id": workflow_id, "workflow_type": workflow.workflow_type}, ) profile = self.workflow_service.profile_repository.get(workflow.profile_id) if profile is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": workflow.profile_id}) active_nodes = [ node for node in sorted(detail.nodes, key=lambda item: item.sort_order) if node.branch_name == workflow.current_branch ] if not active_nodes: raise ApiError(ErrorCode.VALIDATION_FAILED, "workflow has no executable nodes", {"workflow_id": workflow_id}) if workflow.status == "completed": return { "workflow": workflow.to_dict(), "nodes": [node.to_dict() for node in active_nodes], "completed_node_ids": [ node.node_id for node in active_nodes if node.status in {"completed", "selected"} ], "queued_node_ids": [node.node_id for node in active_nodes if node.status == "queued"], "prepared_node_ids": [], "idempotent_replay": True, } if workflow.workflow_type != "character_gradual": return self._execute_unsequenced(workflow, active_nodes, profile, ctx) previous_execution = workflow.metadata.get("character_execution") if isinstance(previous_execution, dict): # execute-character is the confirmation of the synthetic import # entry. Replaying it must not prepare or unlock another node. progression = character_gradual_progression( workflow, active_nodes, branch_name=workflow.current_branch, ) if progression is not None and progression.import_confirmed: return _execution_result( workflow, active_nodes, progression=progression, idempotent_replay=True, ) # Persist the import confirmation before touching profile_brief. The # central progression guard then makes that first backend node (and # only that node) writable. initial_execution = { **(previous_execution if isinstance(previous_execution, dict) else {}), "executor": "character_workflow", "workflow_type": workflow.workflow_type, "import_confirmed": True, "progression_version": CHARACTER_GRADUAL_PROGRESSION_VERSION, } running_workflow = self.workflow_service.update_workflow( workflow_id, { "status": "running" if workflow.status != "running" else workflow.status, "current_node_id": active_nodes[0].node_id, "metadata": { **workflow.metadata, "character_execution": initial_execution, }, }, ctx, allow_character_execution_update=True, ) progression = character_gradual_progression( running_workflow, active_nodes, branch_name=running_workflow.current_branch, ) if progression is None: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow does not support gradual progression", {"workflow_id": workflow_id, "workflow_type": workflow.workflow_type}, ) prepared_nodes = list(active_nodes) current = progression.current_node if current is not None: prompt_context = [ node.prompt or "" for node in active_nodes if node.node_id in progression.completed_node_ids and node.prompt ] prepared = self.workflow_service.update_node( current.node_id, { "status": current.status, "prompt": _node_prompt(profile, current, running_workflow, prompt_context), "negative_prompt": _negative_prompt(profile, current), "metadata": { **current.metadata, "execution": { "executor": "character_workflow", "workflow_type": workflow.workflow_type, "context_prompts": len(prompt_context), "prepared_only": current.status == "draft", "progression_version": CHARACTER_GRADUAL_PROGRESSION_VERSION, }, }, }, ctx, ) prepared_nodes = [prepared if node.node_id == prepared.node_id else node for node in active_nodes] progression = character_gradual_progression( running_workflow, prepared_nodes, branch_name=running_workflow.current_branch, ) or progression current_node_id = progression.current_node.node_id if progression.current_node else prepared_nodes[-1].node_id execution = character_execution_metadata( running_workflow, progression, existing=initial_execution, ) execution["queued_node_ids"] = [node.node_id for node in prepared_nodes if node.status == "queued"] execution["prepared_node_ids"] = [current_node_id] if progression.current_node is not None else [] updated_workflow = self.workflow_service.update_workflow( workflow_id, { "status": "completed" if progression.all_completed else "running", "current_node_id": current_node_id, "metadata": { **running_workflow.metadata, "character_execution": execution, }, }, ctx, allow_character_execution_update=True, ) return _execution_result(updated_workflow, prepared_nodes, progression=progression) def _execute_unsequenced( self, workflow: ProfileWorkflow, active_nodes: list[WorkflowNode], profile: CharacterProfile, ctx: RequestContext, ) -> dict[str, Any]: previous_execution = workflow.metadata.get("character_execution") if workflow.status == "running" and isinstance(previous_execution, dict): return { "workflow": workflow.to_dict(), "nodes": [node.to_dict() for node in active_nodes], "completed_node_ids": [ node.node_id for node in active_nodes if node.status in {"completed", "selected"} ], "queued_node_ids": [node.node_id for node in active_nodes if node.status == "queued"], "prepared_node_ids": [node.node_id for node in active_nodes if node.status == "draft"], "idempotent_replay": True, } running_workflow = workflow if workflow.status != "running": running_workflow = self.workflow_service.update_workflow( workflow.workflow_id, {"status": "running"}, ctx, ) prepared_nodes: list[WorkflowNode] = [] prompt_context: list[str] = [] for node in active_nodes: prepared = self.workflow_service.update_node( node.node_id, { "status": node.status, "prompt": _node_prompt(profile, node, running_workflow, prompt_context), "negative_prompt": _negative_prompt(profile, node), "metadata": { **node.metadata, "execution": { "executor": "character_workflow", "workflow_type": workflow.workflow_type, "context_prompts": len(prompt_context), "prepared_only": node.status == "draft", }, }, }, ctx, ) prepared_nodes.append(prepared) if prepared.prompt: prompt_context.append(prepared.prompt) queued_nodes = [node for node in prepared_nodes if node.status == "queued"] completed_nodes = [node for node in prepared_nodes if node.status in {"completed", "selected"}] editable_nodes = [node for node in prepared_nodes if node.status == "draft"] next_node = next( (node for node in prepared_nodes if node.status not in {"completed", "selected", "skipped"}), prepared_nodes[-1], ) updated_workflow = self.workflow_service.update_workflow( workflow.workflow_id, { "status": "running" if editable_nodes or queued_nodes else "completed", "current_node_id": next_node.node_id, "metadata": { **running_workflow.metadata, "character_execution": { "executor": "character_workflow", "workflow_type": workflow.workflow_type, "completed_node_ids": [node.node_id for node in completed_nodes], "queued_node_ids": [node.node_id for node in queued_nodes], "prepared_node_ids": [node.node_id for node in editable_nodes], }, }, }, ctx, ) return { "workflow": updated_workflow.to_dict(), "nodes": [node.to_dict() for node in prepared_nodes], "completed_node_ids": [node.node_id for node in completed_nodes], "queued_node_ids": [node.node_id for node in queued_nodes], "prepared_node_ids": [node.node_id for node in editable_nodes], } def _node_prompt( profile: CharacterProfile, node: WorkflowNode, workflow: ProfileWorkflow, prompt_context: list[str], ) -> str: parts = [ profile.name, profile.base_prompt, profile.appearance_prompt, profile.style_prompt, _step_instruction(workflow.workflow_type, node.node_key), node.prompt, ] if prompt_context: parts.append(f"consistency reference: {prompt_context[-1]}") return ", ".join(_unique_text(parts)) def _negative_prompt(profile: CharacterProfile, node: WorkflowNode) -> str: return ", ".join(_unique_text([profile.negative_prompt, node.negative_prompt, "low quality, blurry"])) def _step_instruction(workflow_type: str, node_key: str) -> str: quick_profile = { "questionnaire": "normalized questionnaire and quick profile archive input", "preview": "saved quick profile prompts ready for structured setting split", } fast = { "quick_avatar": "square avatar, face, hair, eyes, expression, keep identity consistent", "quick_bust": "half-body character reference, clothing, posture, keep identity consistent", "quick_stand": "full-body standing character illustration, complete outfit and proportions", "quick_sheet": "character design sheet, multiple views, outfit details and material callouts", } gradual = { "profile_brief": "core identity and visual anchors", "prompt_plan": "prompt matrix and inheritance rules for every image stage", "material_bind": "reference material binding rules for style, composition, clothing, shoes, and accessories", "headshot": "headshot, face, hair, eyes, expression", "upper_body": "upper body, outfit, posture, silhouette, preserve the confirmed face identity", "lower_body": "lower body, waist, hips, legs, footwear and consistent body proportions", "full_body": "full body, complete outfit and proportions", "turnaround": "front, side and back turnaround views with identical identity and costume structure", "design_sheet": "design sheet with expressions, poses, hands, accessories and reusable callouts", "style_lock": "high-resolution restoration, identity consistency and final rendering rules", "profile_card": "validate accepted assets and seal the immutable character profile card", } tables = { "character_fast": fast, "character_gradual": gradual, "quick_profile": quick_profile, } table = tables.get(workflow_type, {}) resolved_key = canonical_gradual_node_key(node_key) if workflow_type == "character_gradual" else node_key return table.get(resolved_key, resolved_key.replace("_", " ")) def _unique_text(values: list[Any]) -> list[str]: result: list[str] = [] seen: set[str] = set() for value in values: text = str(value or "").strip() if text and text not in seen: result.append(text) seen.add(text) return result def _execution_result( workflow: ProfileWorkflow, nodes: list[WorkflowNode], *, progression, idempotent_replay: bool = False, ) -> dict[str, Any]: current_node_id = progression.current_node.node_id if progression.current_node else None result = { "workflow": workflow.to_dict(), "nodes": [node.to_dict() for node in nodes], "completed_node_ids": list(progression.completed_node_ids), "queued_node_ids": [node.node_id for node in nodes if node.status == "queued"], "prepared_node_ids": [current_node_id] if current_node_id else [], "locked_node_ids": [ node.node_id for node in nodes if not progression.is_accessible(node) ], "progression": progression.to_dict(), } if idempotent_replay: result["idempotent_replay"] = True return result