"""Profile workflow and workflow node 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 ProfileWorkflow, WorkflowBranch, WorkflowDetail, WorkflowNode from backend.services.branch_lineage_service import ( BranchLineageResolver, activate_branch_state, branch_state_for, branch_state_patch, remap_branch_state_node_ids, with_branch_state, ) from backend.services.material_binding_schema_service import ( MATERIAL_BINDING_SCHEMA_VERSION, normalize_material_bindings, ) from backend.services.prompt_plan_schema_service import ( PROMPT_PLAN_SCHEMA_VERSION, normalize_prompt_plan, ) from backend.services.queue_service import QueueService from backend.services.workflow_progression_service import ( character_execution_metadata, character_gradual_progression, ensure_character_gradual_node_access, is_character_gradual_node_completed, ) from core.audit_service import AuditService from core.event_bus import EventBus from core.fsm import node_transition, workflow_transition from core.identity import RequestContext from database.repositories.profile_repository import ProfileRepository from database.repositories.workflow_repository import WorkflowRepository from engines.character_flow import ( CHARACTER_GRADUAL_STEPS, CHARACTER_GRADUAL_TEMPLATE_VERSION, canonical_gradual_node_key, gradual_node_templates, ) from engines.fast_character_flow import fast_character_node_templates from engines.quick_profile_flow import quick_profile_node_templates WORKFLOW_TYPES = {"single_image", "character_gradual", "character_fast", "quick_profile"} WORKFLOW_STATUSES = {"draft", "active", "running", "completed", "failed", "archived", "cancelled"} BRANCH_STATUSES = {"active", "archived"} NODE_STATUSES = { "draft", "queued", "running", "completed", "selected", "failed", "cancelled", "skipped", "discarded", } LOCKED_NODE_STATUSES = {"completed", "selected"} QUICK_CHARACTER_IMMUTABLE_METADATA_KEYS = { "quick_character_identity_managed", "quick_character_batch_id", "identity_lock_hash", "identity_lock", "quick_character_route_snapshot", "quick_character_target", "quick_character_targets", } class WorkflowService: def __init__( self, workflow_repository: WorkflowRepository, profile_repository: ProfileRepository, audit_service: AuditService, event_bus: EventBus | None = None, ): self.workflow_repository = workflow_repository self.profile_repository = profile_repository self.audit_service = audit_service self.event_bus = event_bus def create_workflow( self, profile_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> WorkflowDetail: self._ensure_profile_exists(profile_id) workflow_type = str(payload.get("workflow_type") or "").strip() if workflow_type not in WORKFLOW_TYPES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported workflow type", {"field": "workflow_type", "allowed": sorted(WORKFLOW_TYPES)}, ) display_name = str(payload.get("display_name") or "").strip() if not display_name: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow display_name is required", {"field": "display_name"}, ) status = payload.get("status", "draft") self._validate_workflow_status(status) workflow_id = payload.get("workflow_id") or new_workflow_id() node_payloads = self._initial_node_payloads(workflow_id, workflow_type, payload) workflow, nodes = self.workflow_repository.create_workflow_with_nodes( { "workflow_id": workflow_id, "profile_id": profile_id, "workflow_type": workflow_type, "display_name": display_name, "mode": payload.get("mode"), "status": status, "current_node_id": node_payloads[0]["node_id"] if node_payloads else None, "current_branch": payload.get("current_branch", "main"), "session_key": payload.get("session_key") or ctx.session_key, "metadata": payload.get("metadata") or {}, }, node_payloads, ) self.audit_service.record( ctx=ctx, action="create_workflow", target_type="profile_workflow", target_id=workflow.workflow_id, after_snapshot=workflow.to_dict(), ) self._publish( "workflow.created", { "workflow_id": workflow.workflow_id, "profile_id": workflow.profile_id, "workflow_type": workflow.workflow_type, "node_ids": [node.node_id for node in nodes], }, ) return WorkflowDetail(workflow=workflow, nodes=nodes) def list_workflows(self, profile_id: str) -> list[ProfileWorkflow]: self._ensure_profile_exists(profile_id) return self.workflow_repository.list_workflows(profile_id) def get_workflow(self, workflow_id: str) -> WorkflowDetail: workflow = self.workflow_repository.get_workflow(workflow_id) if workflow is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": workflow_id}, ) nodes = self.workflow_repository.list_nodes(workflow_id) if workflow.workflow_type == "character_gradual" and workflow.status != "archived": nodes = self._ensure_character_gradual_catalog(workflow, nodes) refreshed = self.workflow_repository.get_workflow(workflow_id) if refreshed is not None: workflow = refreshed return WorkflowDetail(workflow=workflow, nodes=nodes) def _ensure_character_gradual_catalog( self, workflow: ProfileWorkflow, nodes: list[WorkflowNode], ) -> list[WorkflowNode]: """Idempotently add canonical stages that did not exist in v1 data. Legacy keys stay untouched so persisted ids, images and history remain valid. The only normal v1 gap is ``lower_body``; the generic loop also repairs partially-created workflows without rebuilding them. """ branches = sorted({node.branch_name for node in nodes} or {"main"}) created_any = False for branch_name in branches: branch_nodes = [node for node in nodes if node.branch_name == branch_name] canonical_keys = {canonical_gradual_node_key(node.node_key) for node in branch_nodes} for template in CHARACTER_GRADUAL_STEPS: node_key = str(template["node_key"]) if node_key in canonical_keys: continue # Existing v1 workflows are structurally complete except for # lower_body. Do not manufacture unrelated missing stages in # a branch that was intentionally copied without all nodes. if node_key != "lower_body" and branch_nodes: continue sort_order = _compatible_stage_sort_order(node_key, template, branch_nodes) status = _compatible_stage_status(sort_order, branch_nodes) created = self.workflow_repository.create_node( { "node_id": new_node_id(), "workflow_id": workflow.workflow_id, "node_key": node_key, "title": template["title"], "description": template.get("description"), "step_name": template.get("step_name"), "node_type": template.get("node_type", "generation"), "status": status, "branch_name": branch_name, "sort_order": sort_order, "metadata": { "template": CHARACTER_GRADUAL_TEMPLATE_VERSION, "canonical_node_key": node_key, "stage_code": template.get("stage_code"), "compatibility_added": True, "compatibility_source": "character_gradual_v1", }, } ) nodes.append(created) branch_nodes.append(created) canonical_keys.add(node_key) created_any = True if created_any: metadata = dict(workflow.metadata or {}) metadata["character_catalog_version"] = CHARACTER_GRADUAL_TEMPLATE_VERSION metadata["character_catalog_migrated"] = True self.workflow_repository.update_workflow(workflow.workflow_id, {"metadata": metadata}) return sorted(nodes, key=lambda item: (item.branch_name, item.sort_order, item.created_at, item.node_id)) def update_workflow( self, workflow_id: str, payload: dict[str, Any], ctx: RequestContext, *, allow_character_execution_update: bool = False, ) -> ProfileWorkflow: before = self.get_workflow(workflow_id).workflow self._ensure_workflow_mutable(before, "update_workflow") if before.workflow_type == "character_gradual" and payload.get("status") == "completed": progression = character_gradual_progression( before, self.workflow_repository.list_nodes( before.workflow_id, branch_name=before.current_branch, ), branch_name=before.current_branch, ) if progression is not None and not progression.all_completed: raise ApiError( ErrorCode.VALIDATION_FAILED, "gradual workflow cannot be completed before every node is confirmed", { "reason": "character_gradual_workflow_incomplete", "workflow_id": before.workflow_id, "current_node_id": ( progression.current_node.node_id if progression.current_node else None ), }, ) if "status" in payload: self._validate_workflow_status_transition(before.status, str(payload["status"])) if "display_name" in payload and not str(payload["display_name"]).strip(): raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow display_name is required", {"field": "display_name"}, ) update_payload = dict(payload) if "display_name" in update_payload: update_payload["display_name"] = str(update_payload["display_name"]).strip() if "metadata" in update_payload: if isinstance(update_payload["metadata"], dict): update_payload["metadata"] = self._normalize_workflow_metadata( before, update_payload["metadata"], allow_character_execution_update=allow_character_execution_update, branch_name=str(update_payload.get("current_branch") or before.current_branch), ) elif before.workflow_type == "character_gradual" and not allow_character_execution_update: update_payload["metadata"] = dict(before.metadata or {}) after = self.workflow_repository.update_workflow(workflow_id, update_payload) if after is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": workflow_id}) self.audit_service.record( ctx=ctx, action="update_workflow", target_type="profile_workflow", target_id=workflow_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) if before.status != after.status: self._publish( "workflow.status_changed", { "workflow_id": workflow_id, "profile_id": after.profile_id, "before_status": before.status, "after_status": after.status, }, ) self._publish("workflow.updated", {"workflow_id": workflow_id, "profile_id": after.profile_id}) return after def cancel_workflow( self, workflow_id: str, ctx: RequestContext, queue_service: QueueService, ) -> ProfileWorkflow: """Cancel a workflow and CAS-cancel its active tasks and nodes.""" while True: before = self.get_workflow(workflow_id).workflow self._ensure_workflow_mutable(before, "cancel_workflow") if before.status == "cancelled": after = before break self._validate_workflow_status_transition(before.status, "cancelled") after = self.workflow_repository.update_workflow_if_status( workflow_id, {before.status}, {"status": "cancelled"}, ) if after is not None: self.audit_service.record( ctx=ctx, action="cancel_workflow", target_type="profile_workflow", target_id=workflow_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) self._publish( "workflow.status_changed", { "workflow_id": workflow_id, "profile_id": after.profile_id, "before_status": before.status, "after_status": after.status, }, ) self._publish("workflow.updated", {"workflow_id": workflow_id, "profile_id": after.profile_id}) break queue_service.cancel_workflow_jobs(workflow_id, ctx, reason="workflow cancelled") for node in self.workflow_repository.list_nodes(workflow_id): if node.status not in {"queued", "running"}: continue node_metadata = node.metadata if isinstance(node.metadata, dict) else {} last_task_id = str(node_metadata.get("last_task_id") or "").strip() if last_task_id: try: last_task = queue_service.get_job(last_task_id) except ApiError as exc: if exc.error_code != ErrorCode.RESOURCE_NOT_FOUND: raise else: # A task that committed before workflow cancellation owns # its terminal node update. Tasks still active were CAS- # cancelled above and their nodes are cancelled here. if last_task.status in {"completed", "succeeded"}: continue cancelled_node = self.workflow_repository.update_node_if_status( node.node_id, {node.status}, { "status": "cancelled", "metadata": { **node_metadata, "workflow_cancellation": { "workflow_id": workflow_id, "requested_by": ctx.actor_id or "system", }, }, }, ) if cancelled_node is None: continue self.audit_service.record( ctx=ctx, action="cancel_node", target_type="workflow_node", target_id=node.node_id, before_snapshot=node.to_dict(), after_snapshot=cancelled_node.to_dict(), metadata={"source": "workflow.cancel"}, ) self._publish( "workflow.node_status_changed", { "workflow_id": workflow_id, "node_id": node.node_id, "before_status": node.status, "after_status": cancelled_node.status, }, ) self._publish("workflow.node_updated", {"workflow_id": workflow_id, "node_id": node.node_id}) return after def create_branch( self, workflow_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> WorkflowBranch: workflow = self._ensure_workflow_exists(workflow_id) self._ensure_workflow_mutable(workflow, "create_branch") branch_name = str(payload.get("branch_name") or "").strip() if not branch_name: raise ApiError(ErrorCode.VALIDATION_FAILED, "branch_name is required", {"field": "branch_name"}) if branch_name == "main": raise ApiError( ErrorCode.VALIDATION_FAILED, "main is a reserved workflow branch", {"reason": "workflow_branch_main_reserved", "workflow_id": workflow_id}, ) if self.workflow_repository.get_branch(workflow_id, branch_name): raise ApiError( ErrorCode.VALIDATION_FAILED, "branch already exists", {"workflow_id": workflow_id, "branch_name": branch_name}, ) base_branch_name = str(payload.get("base_branch_name") or workflow.current_branch or "main").strip() base_node_id = payload.get("base_node_id") or workflow.current_node_id status = str(payload.get("status") or "active").strip().lower() if status not in BRANCH_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported workflow branch status", {"field": "status", "allowed": sorted(BRANCH_STATUSES), "status": status}, ) if base_branch_name == branch_name: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow branch cannot be its own parent", { "reason": "workflow_branch_self_parent", "workflow_id": workflow_id, "branch_name": branch_name, }, ) self._validate_branch_parent_chain(workflow_id, base_branch_name, branch_name) source_nodes, base_sort_order = self._resolve_branch_copy_base( workflow_id, base_branch_name, base_node_id, ) base_node = next((node for node in source_nodes if node.node_id == base_node_id), None) if base_node is None or base_node.status not in LOCKED_NODE_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow branches can only start from a completed node", { "reason": "workflow_branch_base_not_completed", "workflow_id": workflow_id, "branch_name": branch_name, "base_branch_name": base_branch_name, "base_node_id": base_node_id, "base_node_status": base_node.status if base_node else None, "allowed_statuses": sorted(LOCKED_NODE_STATUSES), }, ) copy_nodes = payload.get("copy_nodes", True) is not False node_payloads = ( self._branch_node_payloads( workflow_id, source_nodes, to_branch=branch_name, base_sort_order=base_sort_order, ) if copy_nodes else [] ) branch_metadata = { **(payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {}), "lineage_version": "workflow_branch_lineage_v1", "parent_branch": base_branch_name, "base_sort_order": base_sort_order, } branch, copied_nodes = self.workflow_repository.create_branch_with_nodes( { "branch_id": payload.get("branch_id") or new_branch_id(), "workflow_id": workflow_id, "branch_name": branch_name, "base_branch_name": base_branch_name, "base_node_id": base_node_id, "status": status, "metadata": branch_metadata, }, node_payloads, ) if copied_nodes: node_id_map = { str(node.metadata.get("copied_from_node_id")): node.node_id for node in copied_nodes if isinstance(node.metadata, dict) and node.metadata.get("copied_from_node_id") } inherited_state = remap_branch_state_node_ids( branch_state_for(workflow.metadata, base_branch_name), node_id_map, ) updated_metadata = with_branch_state( workflow.metadata, branch_name, inherited_state if isinstance(inherited_state, dict) else {}, activate=False, ) self.workflow_repository.update_workflow(workflow_id, {"metadata": updated_metadata}) self.audit_service.record( ctx=ctx, action="create_branch", target_type="workflow_branch", target_id=branch.branch_id, after_snapshot={**branch.to_dict(), "copied_node_ids": [node.node_id for node in copied_nodes]}, ) self._publish( "workflow.branch_created", { "workflow_id": workflow_id, "branch_name": branch.branch_name, "copied_node_ids": [node.node_id for node in copied_nodes], }, ) return branch def list_branches(self, workflow_id: str) -> list[WorkflowBranch]: self._ensure_workflow_exists(workflow_id) branches = self.workflow_repository.list_branches(workflow_id) persisted_main = next((branch for branch in branches if branch.branch_name == "main"), None) main = persisted_main or WorkflowBranch( branch_id="branch_virtual_main", workflow_id=workflow_id, branch_name="main", base_branch_name=None, base_node_id=None, status="active", metadata={"virtual": True}, created_at="", updated_at="", ) return [main, *(branch for branch in branches if branch.branch_name != "main")] def switch_branch(self, workflow_id: str, branch_name: str, ctx: RequestContext) -> ProfileWorkflow: before = self._ensure_workflow_exists(workflow_id) self._ensure_workflow_mutable(before, "switch_branch") branch = self.workflow_repository.get_branch(workflow_id, branch_name) if branch_name != "main" else None if branch_name != "main" and branch is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "branch not found", {"workflow_id": workflow_id, "branch_name": branch_name}) if branch is not None and branch.status != "active": raise ApiError( ErrorCode.VALIDATION_FAILED, "archived workflow branch cannot become active", { "reason": "workflow_branch_archived", "workflow_id": workflow_id, "branch_name": branch_name, "status": branch.status, }, ) branch_nodes = self.workflow_repository.list_nodes(workflow_id, branch_name=branch_name) current_node_id = branch_nodes[0].node_id if branch_nodes else before.current_node_id progression = character_gradual_progression( before, branch_nodes, branch_name=branch_name, ) if progression is not None and progression.import_confirmed: if progression.current_node is not None: current_node_id = progression.current_node.node_id elif branch_nodes: current_node_id = branch_nodes[-1].node_id after = self.update_workflow( workflow_id, { "current_branch": branch_name, "current_node_id": current_node_id, "metadata": activate_branch_state(before.metadata, branch_name), }, ctx, allow_character_execution_update=True, ) self.audit_service.record( ctx=ctx, action="switch_branch", target_type="profile_workflow", target_id=workflow_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) return after def create_node( self, workflow_id: str, payload: dict[str, Any], ctx: RequestContext, *, audit: bool = True, ) -> WorkflowNode: workflow = self._ensure_workflow_exists(workflow_id) self._ensure_workflow_mutable(workflow, "create_node") node_key = str(payload.get("node_key") or "").strip() title = str(payload.get("title") or "").strip() if not node_key: raise ApiError(ErrorCode.VALIDATION_FAILED, "node_key is required", {"field": "node_key"}) if not title: raise ApiError(ErrorCode.VALIDATION_FAILED, "node title is required", {"field": "title"}) status = payload.get("status", "draft") if status not in NODE_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported node status", {"field": "status", "allowed": sorted(NODE_STATUSES)}, ) node = self.workflow_repository.create_node( { "node_id": payload.get("node_id") or new_node_id(), "workflow_id": workflow_id, "node_key": node_key, "title": title, "description": payload.get("description"), "step_name": payload.get("step_name"), "node_type": payload.get("node_type", "generation"), "status": status, "branch_name": payload.get("branch_name", "main"), "prompt": payload.get("prompt"), "negative_prompt": payload.get("negative_prompt"), "model_route": payload.get("model_route"), "selected_image_id": payload.get("selected_image_id"), "sort_order": payload.get("sort_order", 0), "metadata": payload.get("metadata") or {}, } ) if audit: self.audit_service.record( ctx=ctx, action="create_node", target_type="workflow_node", target_id=node.node_id, after_snapshot=node.to_dict(), ) self._publish( "workflow.node_created", {"workflow_id": workflow_id, "node_id": node.node_id, "node_key": node.node_key}, ) return node def list_nodes(self, workflow_id: str) -> list[WorkflowNode]: self._ensure_workflow_exists(workflow_id) return self.workflow_repository.list_nodes(workflow_id) def get_node(self, node_id: str) -> WorkflowNode: node = self.workflow_repository.get_node(node_id) if node is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "node not found", {"node_id": node_id}) return node def ensure_node_action_allowed( self, node_id: str, operation: str, *, node: WorkflowNode | None = None, ) -> WorkflowNode: """Enforce mutation/review access without hiding readable nodes.""" target = node or self.get_node(node_id) workflow = self._ensure_workflow_exists(target.workflow_id) if workflow.status == "archived" and str(operation or "").strip().lower() not in { "read", "review", "inspect", "dependency", }: raise self._archived_workflow_error(workflow, operation, node_id=target.node_id) branch_nodes = self.workflow_repository.list_nodes( target.workflow_id, branch_name=target.branch_name, ) ensure_character_gradual_node_access( workflow, branch_nodes, target, operation=operation, ) return target def update_node( self, node_id: str, payload: dict[str, Any], ctx: RequestContext, *, allow_locked_adoption: bool = False, ) -> WorkflowNode: before = self.get_node(node_id) self.ensure_node_action_allowed(node_id, "update", node=before) workflow = self._ensure_workflow_exists(before.workflow_id) if workflow.workflow_type == "character_gradual": structural_changes = { key: payload[key] for key in ("branch_name", "sort_order") if key in payload and ( str(payload[key]) != before.branch_name if key == "branch_name" else _int_or_original(payload[key]) != before.sort_order ) } if structural_changes: raise ApiError( ErrorCode.VALIDATION_FAILED, "gradual workflow node order and branch are immutable", { "reason": "character_gradual_structure_locked", "node_id": before.node_id, "workflow_id": before.workflow_id, "fields": sorted(structural_changes), }, ) if before.status in LOCKED_NODE_STATUSES and _node_payload_changes(before, payload): if not (allow_locked_adoption and _is_locked_image_adoption(before, payload)): raise locked_node_edit_error(before) if "status" in payload: self._validate_node_status_transition(before.status, str(payload["status"])) if "title" in payload and not str(payload["title"]).strip(): raise ApiError(ErrorCode.VALIDATION_FAILED, "node title is required", {"field": "title"}) update_payload = dict(payload) if "title" in update_payload: update_payload["title"] = str(update_payload["title"]).strip() after = self.workflow_repository.update_node(node_id, update_payload) if after is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "node not found", {"node_id": node_id}) self._sync_material_bindings_from_node(after) self._sync_prompt_plan_from_node(after) self.audit_service.record( ctx=ctx, action="update_node", target_type="workflow_node", target_id=node_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) if before.status != after.status: self._publish( "workflow.node_status_changed", { "workflow_id": after.workflow_id, "node_id": node_id, "before_status": before.status, "after_status": after.status, }, ) if ( is_character_gradual_node_completed(after) and not is_character_gradual_node_completed(before) ): self._advance_character_gradual_progression(after, ctx) self._publish("workflow.node_updated", {"workflow_id": after.workflow_id, "node_id": node_id}) return after def _advance_character_gradual_progression( self, completed_node: WorkflowNode, ctx: RequestContext, ) -> None: workflow = self.workflow_repository.get_workflow(completed_node.workflow_id) if workflow is None or workflow.workflow_type != "character_gradual": return branch_nodes = self.workflow_repository.list_nodes( workflow.workflow_id, branch_name=completed_node.branch_name, ) progression = character_gradual_progression( workflow, branch_nodes, branch_name=completed_node.branch_name, ) if progression is None or not progression.import_confirmed: return existing_execution = ( workflow.metadata.get("character_execution") if isinstance(workflow.metadata, dict) and isinstance(workflow.metadata.get("character_execution"), dict) else {} ) target_node_id = ( progression.current_node.node_id if progression.current_node is not None else completed_node.node_id ) update_payload: dict[str, Any] = { "current_node_id": target_node_id, "metadata": { **(workflow.metadata or {}), "character_execution": character_execution_metadata( workflow, progression, existing=existing_execution, ), }, } if progression.all_completed and workflow.status in {"draft", "active", "running"}: update_payload["status"] = "completed" self.update_workflow( workflow.workflow_id, update_payload, ctx, allow_character_execution_update=True, ) def _initial_node_payloads( self, workflow_id: str, workflow_type: str, payload: dict[str, Any], ) -> list[dict[str, Any]]: if payload.get("auto_create_nodes", True) is False: return [] nodes: list[dict[str, Any]] = [] for template in _initial_node_templates(workflow_type): node_key = str(template.get("node_key") or "").strip() title = str(template.get("title") or "").strip() status = str(template.get("status") or "draft") if not node_key or not title or status not in NODE_STATUSES: raise RuntimeError(f"invalid initial node template for {workflow_type}") nodes.append( { "node_id": template.get("node_id") or new_node_id(), "workflow_id": workflow_id, "node_key": node_key, "title": title, "description": template.get("description"), "step_name": template.get("step_name"), "node_type": template.get("node_type", "generation"), "status": status, "branch_name": template.get("branch_name", "main"), "prompt": template.get("prompt"), "negative_prompt": template.get("negative_prompt"), "model_route": template.get("model_route"), "selected_image_id": template.get("selected_image_id"), "sort_order": template.get("sort_order", 0), "metadata": template.get("metadata") or {}, } ) return nodes def _branch_node_payloads( self, workflow_id: str, source_nodes: list[WorkflowNode], *, to_branch: str, base_sort_order: int | None, ) -> list[dict[str, Any]]: return [ { "node_id": new_node_id(), "workflow_id": workflow_id, "node_key": node.node_key, "title": node.title, "description": node.description, "step_name": node.step_name, "node_type": node.node_type, "status": _branch_copy_status(node, base_sort_order), "branch_name": to_branch, "prompt": node.prompt, "negative_prompt": node.negative_prompt, "model_route": node.model_route, "selected_image_id": _branch_copy_selected_image_id(node, base_sort_order), "sort_order": node.sort_order, "metadata": _branch_copy_metadata(node, base_sort_order), } for node in source_nodes ] def _resolve_branch_copy_base( self, workflow_id: str, from_branch: str, base_node_id: str | None = None, ) -> tuple[list[WorkflowNode], int | None]: source_nodes = self.workflow_repository.list_nodes(workflow_id, branch_name=from_branch) if not source_nodes: raise ApiError( ErrorCode.VALIDATION_FAILED, "source workflow branch has no nodes", { "reason": "workflow_branch_source_empty", "workflow_id": workflow_id, "branch_name": from_branch, }, ) base_node = None if base_node_id: base_node = next((node for node in source_nodes if node.node_id == base_node_id), None) if base_node is None: raise ApiError( ErrorCode.VALIDATION_FAILED, "base_node_id does not belong to the source branch", {"workflow_id": workflow_id, "branch_name": from_branch, "base_node_id": base_node_id}, ) return source_nodes, base_node.sort_order if base_node else None def _validate_branch_parent_chain( self, workflow_id: str, base_branch_name: str, new_branch_name: str, ) -> None: if base_branch_name == "main": return parent = self.workflow_repository.get_branch(workflow_id, base_branch_name) if parent is None: raise ApiError( ErrorCode.VALIDATION_FAILED, "base workflow branch does not exist", { "reason": "workflow_branch_parent_missing", "workflow_id": workflow_id, "branch_name": new_branch_name, "base_branch_name": base_branch_name, }, ) chain = BranchLineageResolver(self.workflow_repository).branch_chain(workflow_id, base_branch_name) if new_branch_name in chain: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow branch parent cycle detected", { "reason": "workflow_branch_parent_cycle", "workflow_id": workflow_id, "branch_name": new_branch_name, "base_branch_name": base_branch_name, "lineage": list(chain), }, ) def _ensure_workflow_mutable(self, workflow: ProfileWorkflow, operation: str) -> None: if workflow.status == "archived": raise self._archived_workflow_error(workflow, operation) @staticmethod def _archived_workflow_error( workflow: ProfileWorkflow, operation: str, *, node_id: str | None = None, ) -> ApiError: return ApiError( ErrorCode.VALIDATION_FAILED, "archived workflow is read-only", { "reason": "workflow_archived_read_only", "workflow_id": workflow.workflow_id, "status": workflow.status, "operation": str(operation or "write"), **({"node_id": node_id} if node_id else {}), }, ) def _ensure_profile_exists(self, profile_id: str) -> None: profile = self.profile_repository.get(profile_id) if profile is None or profile.status == "deleted": raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id}, ) def _ensure_workflow_exists(self, workflow_id: str) -> ProfileWorkflow: workflow = self.workflow_repository.get_workflow(workflow_id) if workflow is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": workflow_id}, ) return workflow def _validate_workflow_status_transition(self, current: str, target: str) -> None: self._validate_workflow_status(target) transition = workflow_transition(current, target) if not transition.allowed: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow status transition is not allowed", {"current": current, "target": target, "reason": transition.reason}, ) def _validate_workflow_status(self, status: Any) -> None: if not isinstance(status, str) or status not in WORKFLOW_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported workflow status", {"field": "status", "allowed": sorted(WORKFLOW_STATUSES)}, ) def _validate_node_status_transition(self, current: str, target: str) -> None: if target not in NODE_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported node status", {"field": "status", "allowed": sorted(NODE_STATUSES)}, ) transition = node_transition(current, target) if not transition.allowed: raise ApiError( ErrorCode.VALIDATION_FAILED, "node status transition is not allowed", {"current": current, "target": target, "reason": transition.reason}, ) def _publish(self, event_type: str, payload: dict[str, Any]) -> None: if self.event_bus: self.event_bus.publish(event_type, payload) def _normalize_workflow_metadata( self, workflow: ProfileWorkflow, metadata: dict[str, Any], *, allow_character_execution_update: bool = False, branch_name: str | None = None, ) -> dict[str, Any]: normalized = dict(metadata) current_metadata = workflow.metadata if isinstance(workflow.metadata, dict) else {} selected_branch = str(branch_name or workflow.current_branch or "main") if workflow.workflow_type == "character_gradual" and not allow_character_execution_update: if "character_execution" in current_metadata: normalized["character_execution"] = current_metadata["character_execution"] else: normalized.pop("character_execution", None) if ( workflow.workflow_type == "character_fast" and current_metadata.get("quick_character_identity_managed") == "generation_service_v1" ): # Browser clients may PUT a stale whole metadata object after the # four requests finish. Preserve server-owned batch identity and # route fields once initialized so clients cannot clear or mutate # the lock accidentally (or deliberately). for key in QUICK_CHARACTER_IMMUTABLE_METADATA_KEYS: if key in current_metadata: normalized[key] = current_metadata[key] material_bindings = normalized.get("material_bindings") prompt_plan = normalized.get("prompt_plan") or normalized.get("prompt_matrix") nodes = ( self.workflow_repository.list_nodes(workflow.workflow_id, branch_name=selected_branch) if material_bindings is not None or prompt_plan is not None else [] ) if material_bindings is not None: normalized["material_binding_schema_version"] = MATERIAL_BINDING_SCHEMA_VERSION normalized["material_bindings"] = normalize_material_bindings(material_bindings, nodes) if prompt_plan is not None: normalized["prompt_plan_schema_version"] = PROMPT_PLAN_SCHEMA_VERSION normalized["prompt_plan"] = normalize_prompt_plan(prompt_plan, nodes) normalized.pop("prompt_matrix", None) if workflow.workflow_type == "character_gradual": if isinstance(current_metadata.get("branch_state"), dict): # Clients edit only the active projection. Sibling branch # snapshots are server-owned and must survive stale PUTs. normalized["branch_state"] = current_metadata["branch_state"] normalized = with_branch_state( normalized, selected_branch, branch_state_patch(normalized), activate=True, ) return normalized def _sync_material_bindings_from_node(self, node: WorkflowNode) -> None: if node.node_key != "material_bind" or not isinstance(node.metadata, dict): return raw_bindings = node.metadata.get("material_bindings") if raw_bindings is None: return workflow = self.workflow_repository.get_workflow(node.workflow_id) if workflow is None: return nodes = self.workflow_repository.list_nodes(node.workflow_id, branch_name=node.branch_name) normalized = normalize_material_bindings(raw_bindings, nodes) metadata = with_branch_state( workflow.metadata, node.branch_name, { "material_binding_schema_version": MATERIAL_BINDING_SCHEMA_VERSION, "material_binding_source_node_id": node.node_id, "material_binding_updated_at": node.updated_at, "material_bindings": normalized, }, activate=workflow.current_branch == node.branch_name, ) self.workflow_repository.update_workflow( workflow.workflow_id, {"metadata": metadata}, ) def _sync_prompt_plan_from_node(self, node: WorkflowNode) -> None: if node.node_key != "prompt_plan" or not isinstance(node.metadata, dict): return raw_plan = node.metadata.get("prompt_plan") or node.metadata.get("prompt_matrix") if raw_plan is None: return workflow = self.workflow_repository.get_workflow(node.workflow_id) if workflow is None: return nodes = self.workflow_repository.list_nodes(node.workflow_id, branch_name=node.branch_name) normalized = normalize_prompt_plan(raw_plan, nodes) metadata = with_branch_state( workflow.metadata, node.branch_name, { "prompt_plan_schema_version": PROMPT_PLAN_SCHEMA_VERSION, "prompt_plan_source_node_id": node.node_id, "prompt_plan_updated_at": node.updated_at, "prompt_plan": normalized, }, activate=workflow.current_branch == node.branch_name, ) self.workflow_repository.update_workflow( workflow.workflow_id, {"metadata": metadata}, ) def new_workflow_id() -> str: return f"workflow_{uuid4().hex}" def new_node_id() -> str: return f"node_{uuid4().hex}" def new_branch_id() -> str: return f"branch_{uuid4().hex}" def locked_node_edit_error(node: WorkflowNode) -> ApiError: return ApiError( ErrorCode.VALIDATION_FAILED, "completed node is locked; create a workflow branch before editing", { "node_id": node.node_id, "workflow_id": node.workflow_id, "branch_name": node.branch_name, "status": node.status, "suggested_action": "create_branch", "base_node_id": node.node_id, }, ) def is_repeatable_single_image_node(node: WorkflowNode) -> bool: return bool( node.node_key == "virtual_single_image" or node.node_type == "virtual_single_image" or (isinstance(node.metadata, dict) and node.metadata.get("virtual") is True) ) def _node_payload_changes(node: WorkflowNode, payload: dict[str, Any]) -> bool: comparable = { "title": node.title, "description": node.description, "step_name": node.step_name, "node_type": node.node_type, "status": node.status, "branch_name": node.branch_name, "prompt": node.prompt, "negative_prompt": node.negative_prompt, "model_route": node.model_route, "selected_image_id": node.selected_image_id, "sort_order": node.sort_order, "metadata": node.metadata, } for key, value in payload.items(): if key not in comparable: continue current = comparable[key] if key == "sort_order": try: value = int(value) except (TypeError, ValueError): return True if key == "title" and value is not None: value = str(value).strip() if value != current: return True return False def _int_or_original(value: Any) -> Any: try: return int(value) except (TypeError, ValueError): return value def _is_locked_image_adoption(node: WorkflowNode, payload: dict[str, Any]) -> bool: allowed_keys = {"status", "selected_image_id"} if any(key not in allowed_keys for key in payload): return False selected_image_id = payload.get("selected_image_id") if not selected_image_id: return False target_status = payload.get("status", node.status) if target_status != "selected": return False if node.status == "completed": return True return node.status == "selected" and node.selected_image_id == selected_image_id def _branch_copy_status(node: WorkflowNode, base_sort_order: int | None) -> str: if base_sort_order is None: return "draft" if node.sort_order < base_sort_order: return node.status return "draft" def _branch_copy_selected_image_id(node: WorkflowNode, base_sort_order: int | None) -> str | None: if base_sort_order is not None and node.sort_order < base_sort_order: return node.selected_image_id return None def _branch_copy_metadata(node: WorkflowNode, base_sort_order: int | None) -> dict[str, Any]: metadata = { **node.metadata, "copied_from_node_id": node.node_id, } if base_sort_order is None: return metadata locked_ancestor = node.sort_order < base_sort_order and node.status in LOCKED_NODE_STATUSES metadata.update( { "branch_cut_base_sort_order": base_sort_order, "branch_reset_from_status": node.status, "branch_locked_ancestor": locked_ancestor, "branch_editable_from_cut": node.sort_order >= base_sort_order, } ) return metadata def _compatible_stage_sort_order( node_key: str, template: dict[str, Any], branch_nodes: list[WorkflowNode], ) -> int: if node_key != "lower_body": return int(template.get("sort_order") or 0) upper = next( (node for node in branch_nodes if canonical_gradual_node_key(node.node_key) == "upper_body"), None, ) full = next( (node for node in branch_nodes if canonical_gradual_node_key(node.node_key) == "full_body"), None, ) if upper is not None and full is not None and full.sort_order - upper.sort_order > 1: return upper.sort_order + ((full.sort_order - upper.sort_order) // 2) desired = int(template.get("sort_order") or 60) occupied = {node.sort_order for node in branch_nodes} while desired in occupied: desired += 1 return desired def _compatible_stage_status(sort_order: int, branch_nodes: list[WorkflowNode]) -> str: later_nodes = [node for node in branch_nodes if node.sort_order > sort_order] if any(is_character_gradual_node_completed(node, allow_legacy_planning_metadata=True) for node in later_nodes): return "skipped" return "draft" def _initial_node_templates(workflow_type: str) -> list[dict[str, Any]]: if workflow_type == "single_image": return [ { "node_key": "virtual_single_image", "title": "Single image", "description": "Backend virtual node for the single image flow.", "node_type": "virtual_single_image", "sort_order": 0, "metadata": {"virtual": True, "template": "single_image_v1"}, } ] if workflow_type == "character_gradual": return gradual_node_templates() if workflow_type == "character_fast": return fast_character_node_templates() if workflow_type == "quick_profile": return quick_profile_node_templates() return []