"""Sequential access rules for the detailed character workflow. The gradual workflow is intentionally readable as a whole, while mutations are limited to the current step. Progress is derived from persisted workflow/node state so older databases do not need a schema migration. """ from __future__ import annotations from dataclasses import dataclass from typing import Any, Iterable from backend.dto.common import ApiError, ErrorCode from backend.dto.workflow_dto import ProfileWorkflow, WorkflowNode from engines.character_flow import canonical_gradual_node_key CHARACTER_GRADUAL_PROGRESSION_VERSION = "character_gradual_sequential_v1" PROGRESSION_COMPLETED_NODE_STATUSES = frozenset({"selected", "skipped"}) @dataclass(frozen=True) class CharacterGradualProgression: workflow_id: str branch_name: str import_confirmed: bool nodes: tuple[WorkflowNode, ...] current_node: WorkflowNode | None completed_node_ids: tuple[str, ...] @property def all_completed(self) -> bool: return self.import_confirmed and bool(self.nodes) and self.current_node is None def is_accessible(self, node: WorkflowNode) -> bool: """Return whether an operation may target ``node``. Completed ancestors remain reviewable/readable. Future nodes are never made writable by stale ``current_node_id`` or old prompt preparation; recovery must happen at the derived current node. """ if node.workflow_id != self.workflow_id or node.branch_name != self.branch_name: return False if node.node_id in self.completed_node_ids: return True if self.current_node is not None and node.node_id == self.current_node.node_id: return True return False def to_dict(self) -> dict[str, Any]: current = self.current_node return { "version": CHARACTER_GRADUAL_PROGRESSION_VERSION, "mode": "sequential", "import_confirmed": self.import_confirmed, "branch_name": self.branch_name, "current_node_id": current.node_id if current else None, "current_node_key": current.node_key if current else None, "completed_node_ids": list(self.completed_node_ids), "all_completed": self.all_completed, } def character_gradual_progression( workflow: ProfileWorkflow, nodes: Iterable[WorkflowNode], *, branch_name: str | None = None, ) -> CharacterGradualProgression | None: if workflow.workflow_type != "character_gradual": return None selected_branch = str(branch_name or workflow.current_branch or "main") ordered = tuple( sorted( (node for node in nodes if node.branch_name == selected_branch), key=lambda item: (item.sort_order, item.created_at, item.node_id), ) ) import_confirmed = _is_import_confirmed(workflow) completed_prefix: list[str] = [] current_node: WorkflowNode | None = None if import_confirmed: allow_legacy_planning_metadata = _allows_legacy_planning_metadata_completion(workflow) for node in ordered: if is_character_gradual_node_completed( node, allow_legacy_planning_metadata=allow_legacy_planning_metadata, ): completed_prefix.append(node.node_id) continue current_node = node break return CharacterGradualProgression( workflow_id=workflow.workflow_id, branch_name=selected_branch, import_confirmed=import_confirmed, nodes=ordered, current_node=current_node, completed_node_ids=tuple(completed_prefix), ) def ensure_character_gradual_node_access( workflow: ProfileWorkflow, nodes: Iterable[WorkflowNode], node: WorkflowNode, *, operation: str, ) -> CharacterGradualProgression | None: progression = character_gradual_progression(workflow, nodes, branch_name=node.branch_name) if progression is None: return progression normalized_operation = str(operation or "update").strip().lower() if ( node.node_id in progression.completed_node_ids and normalized_operation in {"update", "generate", "retry", "complete"} ): raise ApiError( ErrorCode.VALIDATION_FAILED, "completed character workflow node is locked", { "reason": "character_gradual_node_already_completed", "operation": normalized_operation, "workflow_id": workflow.workflow_id, "node_id": node.node_id, "node_key": node.node_key, "branch_name": node.branch_name, "required_action": "create_branch", "progression_version": CHARACTER_GRADUAL_PROGRESSION_VERSION, }, ) if progression.is_accessible(node): return progression current = progression.current_node details: dict[str, Any] = { "reason": "character_gradual_progression_locked", "operation": str(operation or "update"), "workflow_id": workflow.workflow_id, "workflow_type": workflow.workflow_type, "node_id": node.node_id, "node_key": node.node_key, "branch_name": node.branch_name, "progression_version": CHARACTER_GRADUAL_PROGRESSION_VERSION, "import_confirmed": progression.import_confirmed, "current_node_id": current.node_id if current else None, "current_node_key": current.node_key if current else None, "required_previous_node_id": current.node_id if current else None, "required_previous_node_key": current.node_key if current else None, } if not progression.import_confirmed: details.update( { "required_action": "execute_character_workflow", "required_previous_node_key": "profile_import", "message": "confirm the imported character brief before using workflow nodes", } ) else: details.update( { "required_action": "complete_current_node", "message": "complete or confirm the current node before using a later node", } ) raise ApiError( ErrorCode.VALIDATION_FAILED, "character workflow node is locked by sequential progression", details, ) def is_character_gradual_node_completed( node: WorkflowNode, *, allow_legacy_planning_metadata: bool = False, ) -> bool: if node.status in PROGRESSION_COMPLETED_NODE_STATUSES: return True metadata = node.metadata if isinstance(node.metadata, dict) else {} if node.status == "completed" and ( node.node_type in {"planning", "reference_binding"} or canonical_gradual_node_key(node.node_key) == "profile_card" ): return True # Older standalone UI versions persisted these planning steps without # changing the node status. Only workflows without the sequential-v1 # marker receive that compatibility rule; new workflows require the # explicit confirm/complete action after saving a draft. if allow_legacy_planning_metadata: if node.node_key == "prompt_plan": return "prompt_plan" in metadata and metadata.get("prompt_plan") is not None if node.node_key == "material_bind": # Presence (not truthiness) is intentional because selecting no # references is a valid legacy decision. return "material_bindings" in metadata and metadata.get("material_bindings") is not None return False def character_execution_metadata( workflow: ProfileWorkflow, progression: CharacterGradualProgression, *, existing: dict[str, Any] | None = None, ) -> dict[str, Any]: """Build the server-owned progression portion of character_execution.""" return { **(existing or {}), "executor": "character_workflow", "workflow_type": workflow.workflow_type, "import_confirmed": True, "progression_version": CHARACTER_GRADUAL_PROGRESSION_VERSION, "completed_node_ids": list(progression.completed_node_ids), "current_node_id": progression.current_node.node_id if progression.current_node else None, "current_node_key": progression.current_node.node_key if progression.current_node else None, "all_completed": progression.all_completed, } def _is_import_confirmed(workflow: ProfileWorkflow) -> bool: metadata = workflow.metadata if isinstance(workflow.metadata, dict) else {} execution = metadata.get("character_execution") if not isinstance(execution, dict): return False # Older plugin versions already wrote character_execution without the # explicit flag. Treat that persisted execution as an imported brief. if execution.get("import_confirmed") is False: return False return bool(execution.get("import_confirmed") or execution.get("executor") == "character_workflow") def _allows_legacy_planning_metadata_completion(workflow: ProfileWorkflow) -> bool: metadata = workflow.metadata if isinstance(workflow.metadata, dict) else {} execution = metadata.get("character_execution") if not isinstance(execution, dict): return False return execution.get("progression_version") != CHARACTER_GRADUAL_PROGRESSION_VERSION