diff --git a/.gitignore b/.gitignore index 9c8e9a65f..bd4eee8f3 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,9 @@ besser/utilities/web_modeling_editor/backend/output besser/utilities/web_modeling_editor/backend/feedback_data output_backend/ +# BAF logger output (written by tests and local agent runs) +application.log + # pylint .pylintrc @@ -56,6 +59,10 @@ node_modules/ reviews/ .vscode/ +/output/ + +# Local transfer artifacts (never commit) +*.bundle # Corporate proxy CA certs for building behind TLS inspection (site-internal, do not commit) ca-certs-extra/*.crt diff --git a/CLAUDE.md b/CLAUDE.md index 1c134c411..8d5e88e1f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -122,6 +122,10 @@ variables are documented in `docs/source/web_editor_backend.rst`. Backend facts declared on the app itself: `GET /health` (no prefix) and `GET /besser_api/`. OpenAPI UI is at `/docs`, not `/besser_api/docs`. - Unhandled exceptions are deliberately flattened to a generic HTTP 500; the traceback is in the server log. +- UML diagrams travel in the v4 React Flow shape (`{version: "4.x", nodes, edges}`); the converters read only + that. A v3 model (`elements` / `relationships`) is refused with HTTP 400 (`services/validators/legacy_format.py`), + never converted to an empty model. GUI and quantum models keep their own formats. The per-type wire contract + is `docs/source/migrations/uml-v4-shape.md`; update it with any converter field change. - No per-client rate limiting; the only throughput control is `BESSER_LLM_MAX_CONCURRENT_RUNS` on spec-driven runs (429 when full, 409 when that run id is already active). diff --git a/besser/generators/nn/nn_code_generator.py b/besser/generators/nn/nn_code_generator.py index d3b312e70..a2f1dfba4 100644 --- a/besser/generators/nn/nn_code_generator.py +++ b/besser/generators/nn/nn_code_generator.py @@ -322,7 +322,10 @@ def _apply_sequential_constraints(self, lambda_wrap_types): # Update prev_out_var with current module's output if module_details: - if module_name.endswith('_op'): + if isinstance(module_details, dict): + # A sub-NN: its details are a dict of its layers. + prev_out_var = module_details.get("in_out_variable") + elif module_name.endswith('_op'): module_obj = ( module_details[2] if len(module_details) > 2 else None diff --git a/besser/generators/registry.py b/besser/generators/registry.py index 162dcb6ca..acc8a9983 100644 --- a/besser/generators/registry.py +++ b/besser/generators/registry.py @@ -466,7 +466,8 @@ def load_class(self) -> type: output_type="file", file_extension=".bpmn", requires_class_diagram=False, - required_diagram_type="BPMNDiagram", + # Project bucket key ("BPMN"); the model inside has type "BPMNDiagram". + required_diagram_type="BPMN", download_filename="bpmn_diagram.bpmn", agent_tool=AgentTool( name="generate_bpmn", diff --git a/besser/utilities/buml_code_builder/agent_model_builder.py b/besser/utilities/buml_code_builder/agent_model_builder.py index 614b505da..4151b929b 100644 --- a/besser/utilities/buml_code_builder/agent_model_builder.py +++ b/besser/utilities/buml_code_builder/agent_model_builder.py @@ -199,26 +199,27 @@ def _write_body(f, state_var: str, state_name: str, body: Body, fallback: bool) suffix = "_fallback" if fallback else "" body_var = f"{state_var}{suffix}_body" body_name = f"{_escape_python_string(state_name)}{suffix}_body" - custom_action = next((a for a in body.actions if isinstance(a, CustomCodeAction)), None) - if custom_action is not None: - # CustomCodeAction is always a singleton in a custom body; its function is - # emitted before the Body is created. - f.write(f"{custom_action.to_code()}\n") - function_match = search(r'def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(', custom_action.code) - function_name = ( - function_match.group(1) if function_match - else f"custom_action_{safe_var_name(custom_action.name)}" - ) - action_var = f"CustomCodeAction_{state_var}{suffix}" - f.write(f"{action_var} = CustomCodeAction(callable={function_name})\n") - f.write(f"{body_var} = Body('{body_name}')\n") - f.write(f"{body_var}.add_action({action_var})\n") - else: - f.write(f"{body_var} = Body('{body_name}')\n") - for action in body.actions: + # Code actions' functions and action objects come before the Body; the + # actions are then added in their order, mixed with the other replies. + action_exprs = [] + for index, action in enumerate(body.actions): + if isinstance(action, CustomCodeAction): + f.write(f"{action.to_code()}\n") + function_match = search(r'def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(', action.code) + function_name = ( + function_match.group(1) if function_match + else f"custom_action_{safe_var_name(action.name)}" + ) + action_var = f"CustomCodeAction_{state_var}{suffix}" + (f"_{index}" if index else "") + f.write(f"{action_var} = CustomCodeAction(callable={function_name})\n") + action_exprs.append(action_var) + else: expr = _action_expr(action) if expr is not None: - f.write(f"{body_var}.add_action({expr})\n") + action_exprs.append(expr) + f.write(f"{body_var} = Body('{body_name}')\n") + for expr in action_exprs: + f.write(f"{body_var}.add_action({expr})\n") f.write("\n") setter = "set_fallback_body" if fallback else "set_body" f.write(f"{state_var}.{setter}({body_var})\n") @@ -652,4 +653,11 @@ def condition_var(name): f.write("\n") + # The web editor's a2a: tags, parsed (see a2a_tags.annotate_agent_with_a2a); + # the Docker Compose generator reads them from the agent. + a2a = getattr(model, "_a2a", None) + if a2a: + f.write("# A2A WIRING\n") + f.write(f"{model_var_name}._a2a = {a2a!r}\n\n") + logger.info("Agent model saved to %s", file_path) diff --git a/besser/utilities/buml_code_builder/project_builder.py b/besser/utilities/buml_code_builder/project_builder.py index 1a0c4c50d..092752e40 100644 --- a/besser/utilities/buml_code_builder/project_builder.py +++ b/besser/utilities/buml_code_builder/project_builder.py @@ -4,8 +4,10 @@ This module generates Python code for complete BUML projects including all models. """ +import json import logging import os +import re import tempfile import uuid import shutil @@ -87,6 +89,44 @@ def _suffixed_name(base_name: str, index: int, total: int) -> str: return f"{base_name}_{index}" +# The fixed "# MODEL #" banner a model builder writes, with its borders. +_BUILDER_BANNER = re.compile(r"^#+\n# [A-Z ]+ MODEL #\n#+\n", re.MULTILINE) + + +def _editor_id_lines(project: Project) -> list: + """``# diagram-id`` / ``# diagram-title`` / ``# diagram-references`` / + ``# class-ids`` comment lines for the web editor. + + ``json_to_buml_project`` records the diagram each model came from; the + importer restores those ids, titles and object diagram references (in + section order per diagram type) and the class node ids, which + cross-diagram references (object ``classId``, component ``realizes`` / + ``processModelRefs``, ...) point at. + """ + diagram_ids = getattr(project, "_diagram_ids", None) or {} + diagram_references = getattr(project, "_diagram_references", None) or {} + lines = [] + class_ids = {} + for model in project.models: + entry = diagram_ids.get(id(model)) + if entry is None: + continue + diagram_type, diagram_id, title = entry + lines.append(f"# diagram-id {diagram_type}: {json.dumps(diagram_id)}") + # One per id, empty when untitled, so the titles line up with the ids. + title = title if isinstance(title, str) else "" + lines.append(f"# diagram-title {diagram_type}: {json.dumps(title)}") + if diagram_type == "ObjectDiagram": + references = diagram_references.get(id(model)) or {} + lines.append(f"# diagram-references {diagram_type}: {json.dumps(references, sort_keys=True)}") + index = getattr(model, "_wme_class_index", None) + if diagram_type == "ClassDiagram" and index: + class_ids[diagram_id] = {cls.name: wid for wid, cls in index.items()} + if class_ids: + lines.append(f"# class-ids {json.dumps(class_ids, sort_keys=True)}") + return lines + + def _section_titles(models: Sequence, titles_by_id: Dict[int, str]) -> List[str]: """Return the title each model's section banner carries, in order. @@ -111,6 +151,9 @@ def _write_temp_to_output(temp_path: str, out_file, section_header: str = ""): # One version header per file: the project writes its own at the top. content = content.removeprefix(buml_header()) if section_header: + # The numbered header replaces the builder's banner: with both, the + # importer reads each model as two sections. + content = _BUILDER_BANNER.sub("", content, count=1) out_file.write(section_header) out_file.write(content) out_file.write("\n\n") @@ -618,6 +661,13 @@ def project_to_code(project: Project, file_path: str, sm: str = "", emit_ids: bo f.write("######################\n\n") f.write("from besser.BUML.metamodel.project import Project\n") f.write("from besser.BUML.metamodel.structural.structural import Metadata\n\n") + id_lines = _editor_id_lines(project) + display_name = getattr(project, "_display_name", None) + if display_name: + id_lines.insert(0, f"# project-name {json.dumps(display_name)}") + if id_lines: + f.write("# Web editor ids, read back on import\n") + f.write("\n".join(id_lines) + "\n\n") # Write metadata and project f.write(f'metadata = Metadata(description="{_escape_python_string(project.metadata.description)}")\n') diff --git a/besser/utilities/kg_llm_to_buml.py b/besser/utilities/kg_llm_to_buml.py index 554b81eaf..6afd35d2e 100644 --- a/besser/utilities/kg_llm_to_buml.py +++ b/besser/utilities/kg_llm_to_buml.py @@ -107,14 +107,14 @@ def clean_plantuml_response(response: str) -> str: def convert_spec_json_to_buml(system_spec, title="KG Imported Diagram"): """ Convert class specifications from GPT-generated JSON to the web editor's - class-diagram JSON (``{"title", "model": {"elements", "relationships"}}``). + class-diagram JSON (``{"title", "model": {"nodes", "edges"}}``). :func:`kg_to_buml` does not go through this JSON: it builds the model with :func:`spec_to_domain_model`. Kept for callers of the released API. """ - elements = {} - relationships = {} + nodes = [] + edges = [] # ID generation helpers def make_id(prefix, counter): @@ -132,11 +132,11 @@ def make_id(prefix, counter): class_map[cls["className"]] = class_id class_counter += 1 - # Create class element - class_element = { - "id": class_id, - "type": "Class", + # Create class node (v4 shape); attribute/method rows carry the + # "+ name: type" signature, parsed by the class diagram processor. + class_data = { "name": cls["className"], + "stereotype": None, "attributes": [], "methods": [] } @@ -154,15 +154,7 @@ def make_id(prefix, counter): ) name_str = f"{visibility_symbol} {attr['name']}: {attr['type']}" - attr_element = { - "id": attr_id, - "type": "ClassAttribute", - "owner": class_id, - "name": name_str - } - - class_element["attributes"].append(attr_id) - elements[attr_id] = attr_element + class_data["attributes"].append({"id": attr_id, "name": name_str}) # --- Methods --- for method in cls.get("methods", []): @@ -185,17 +177,14 @@ def make_id(prefix, counter): name_str = f"{visibility_symbol} {method['name']}({param_str}): {return_type}" - method_element = { - "id": method_id, - "type": "ClassMethod", - "owner": class_id, - "name": name_str - } - - class_element["methods"].append(method_id) - elements[method_id] = method_element + class_data["methods"].append({"id": method_id, "name": name_str}) - elements[class_id] = class_element + nodes.append({ + "id": class_id, + "type": "class", + "position": {"x": 0, "y": 0}, + "data": class_data + }) # === Relationships === for rel in system_spec.get("relationships", []): @@ -218,34 +207,30 @@ def make_id(prefix, counter): if not source_class_id or not target_class_id: continue # skip invalid relationships - relationship_obj = { + edges.append({ "id": rel_id, "type": converted_type, - "source": { - "element": source_class_id, - "multiplicity": rel.get("sourceMultiplicity", "1"), - "role": rel.get("sourceRole", "") - }, - "target": { - "element": target_class_id, - "multiplicity": rel.get("targetMultiplicity", "1"), - "role": rel.get("name", "") - }, - "name": rel.get("name", "") - } - - relationships[rel_id] = relationship_obj + "source": source_class_id, + "target": target_class_id, + "data": { + "name": rel.get("name", ""), + "sourceMultiplicity": rel.get("sourceMultiplicity", "1"), + "sourceRole": rel.get("sourceRole", ""), + "targetMultiplicity": rel.get("targetMultiplicity", "1"), + "targetRole": rel.get("name", "") + } + }) # === Final structure === - apollon_buml_json = { + besser_buml_json = { "title": title.replace(" ", "_"), "model": { - "elements": elements, - "relationships": relationships + "nodes": nodes, + "edges": edges } } - return apollon_buml_json + return besser_buml_json _VISIBILITIES = {"public", "private", "protected", "package"} diff --git a/besser/utilities/web_modeling_editor/backend/constants/constants.py b/besser/utilities/web_modeling_editor/backend/constants/constants.py index 92752e421..08268074a 100644 --- a/besser/utilities/web_modeling_editor/backend/constants/constants.py +++ b/besser/utilities/web_modeling_editor/backend/constants/constants.py @@ -158,14 +158,34 @@ # BPMN — WME ↔ B-UML BPMN metamodel constants # Single source of truth for the BPMN converter pair (json_to_buml / # buml_to_json). Diagram-type discriminator: "BPMNDiagram" (uniform with -# "ClassDiagram", "StateMachineDiagram", …). +# "ClassDiagram", "StateMachineDiagram", …) — the value of +# ``UMLDiagramType.BPMN`` in ``packages/library/lib/types/DiagramType.ts``. # --------------------------------------------------------------------------- BPMN_DIAGRAM_TYPE = "BPMNDiagram" -BPMN_RELATIONSHIP_TYPE = "BPMNFlow" +# Both spellings accepted on read: "BPMN" was the canonical v4 value for a while +# (and is the project-envelope key, ``project.diagrams.BPMN``). +BPMN_DIAGRAM_TYPES = ("BPMNDiagram", "BPMN") +# Key of the BPMN bucket in the project envelope (``project.diagrams.BPMN``, +# ``SupportedDiagramType`` in the webapp) — NOT the model ``type`` above. +BPMN_PROJECT_DIAGRAM_KEY = "BPMN" # UML Deployment diagram type (the Docker Compose generator's input). DEPLOYMENT_DIAGRAM_TYPE = "DeploymentDiagram" +# v4 required-interface edge types per diagram. The socket variants differ only +# in how much of the socket is drawn; all read as InterfaceRequired, and the +# converters keep the drawn variant in the relationship layout. +COMPONENT_REQUIRED_INTERFACE_EDGE_TYPES = frozenset({ + "ComponentRequiredInterface", + "ComponentRequiredQuarterInterface", + "ComponentRequiredThreeQuarterInterface", +}) +DEPLOYMENT_REQUIRED_INTERFACE_EDGE_TYPES = frozenset({ + "DeploymentRequiredInterface", + "DeploymentRequiredQuarterInterface", + "DeploymentRequiredThreeQuarterInterface", +}) + # Knowledge Graph diagram type (the KG editor's model, see ``routers/kg_router.py``). KG_DIAGRAM_TYPE = "KnowledgeGraphDiagram" diff --git a/besser/utilities/web_modeling_editor/backend/constants/default_config.json b/besser/utilities/web_modeling_editor/backend/constants/default_config.json index ae7737331..d0a449a72 100644 --- a/besser/utilities/web_modeling_editor/backend/constants/default_config.json +++ b/besser/utilities/web_modeling_editor/backend/constants/default_config.json @@ -10,7 +10,7 @@ "font": "sans", "lineSpacing": 1.5, "alignment": "left", - "color": "var(--apollon-primary-contrast)", + "color": "var(--besser-primary-contrast)", "contrast": "medium" }, "voiceStyle": { diff --git a/besser/utilities/web_modeling_editor/backend/models/diagram.py b/besser/utilities/web_modeling_editor/backend/models/diagram.py index af7a7de8a..5214fb9ad 100644 --- a/besser/utilities/web_modeling_editor/backend/models/diagram.py +++ b/besser/utilities/web_modeling_editor/backend/models/diagram.py @@ -1,6 +1,6 @@ from typing import Dict, Any, Literal, Optional from datetime import datetime -from pydantic import BaseModel +from pydantic import BaseModel, model_validator class DjangoConfig(BaseModel): project_name: str @@ -25,6 +25,24 @@ class DiagramInput(BaseModel): referenceDiagramData: Optional[Dict[str, Any]] = None references: Optional[Dict[str, str]] = None # Per-diagram cross-references by ID (e.g. {"ClassDiagram": "uuid-..."}) + @model_validator(mode="after") + def reject_legacy_v3_model(self) -> "DiagramInput": + """Reject a UML model saved in the legacy v3 editor format. + + Raises ``LegacyDiagramFormatError`` (a ``ConversionError``) rather + than ``ValueError`` on purpose: pydantic lets non-``ValueError`` + exceptions propagate, so the app-level ``ConversionError`` handler + answers HTTP 400 with this message instead of a generic 422. It also + fires for diagrams nested in a ``ProjectInput``. + """ + # Lazy import: importing the services package at module load would + # cycle back here (services.deployment -> routers -> models). + from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_diagram_not_legacy, + ) + ensure_diagram_not_legacy(self.model, title=self.title, reference=self.referenceDiagramData) + return self + class FeedbackSubmission(BaseModel): """Model for user feedback submissions.""" diff --git a/besser/utilities/web_modeling_editor/backend/models/project.py b/besser/utilities/web_modeling_editor/backend/models/project.py index 644228929..0d3c0ba1c 100644 --- a/besser/utilities/web_modeling_editor/backend/models/project.py +++ b/besser/utilities/web_modeling_editor/backend/models/project.py @@ -34,6 +34,12 @@ def normalize_diagrams(cls, data: Any) -> Any: else: normalized[key] = value data["diagrams"] = normalized + # Lazy import, as in DiagramInput. The bucket key decides which + # models are UML, so this catches what the per-diagram check cannot. + from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_project_not_legacy, + ) + ensure_project_not_legacy(normalized) return data def get_active_diagram(self, diagram_type: str) -> Optional[DiagramInput]: diff --git a/besser/utilities/web_modeling_editor/backend/models/simulation.py b/besser/utilities/web_modeling_editor/backend/models/simulation.py index e890549d7..129f3d6df 100644 --- a/besser/utilities/web_modeling_editor/backend/models/simulation.py +++ b/besser/utilities/web_modeling_editor/backend/models/simulation.py @@ -1,7 +1,7 @@ """Request models for the live agent simulation endpoints (/besser_api/simulation/*).""" from typing import Any, Dict, Optional -from pydantic import BaseModel +from pydantic import BaseModel, model_validator class SimulationSessionInput(BaseModel): @@ -13,3 +13,12 @@ class SimulationSessionInput(BaseModel): # Optional LLM provider keys forwarded to the sandboxed agent as env vars: # openAiApiKey, huggingFaceToken, replicateApiKey. credentials: Optional[Dict[str, str]] = None + + @model_validator(mode="after") + def reject_legacy_v3_model(self) -> "SimulationSessionInput": + """Reject a legacy v3 agent diagram with HTTP 400 (see ``DiagramInput``).""" + from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_not_legacy_model, + ) + ensure_not_legacy_model(self.model, "AgentDiagram", self.title) + return self diff --git a/besser/utilities/web_modeling_editor/backend/routers/agent_simulator_router.py b/besser/utilities/web_modeling_editor/backend/routers/agent_simulator_router.py index a5149af57..c8d4b6462 100644 --- a/besser/utilities/web_modeling_editor/backend/routers/agent_simulator_router.py +++ b/besser/utilities/web_modeling_editor/backend/routers/agent_simulator_router.py @@ -73,6 +73,9 @@ from besser.utilities.web_modeling_editor.backend.routers.auth import require_github_session from besser.utilities.web_modeling_editor.backend.routers.error_handler import handle_endpoint_errors from besser.utilities.web_modeling_editor.backend.services.converters import process_agent_diagram +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.agent_diagram_processor import ( + STATE_ACTION_ROW_KEYS, +) from besser.utilities.web_modeling_editor.backend.services.exceptions import ( ConversionError, GenerationError, @@ -151,8 +154,23 @@ def _simulator_client(settings: BackendSettings, timeout: float) -> httpx.AsyncC def _model_has_custom_code_action(model: Dict[str, Any]) -> bool: - """Return True if any element in the diagram model is a custom Python code action.""" - for element in (model.get("elements") or {}).values(): + """Return True if any action row of the diagram model is a custom Python code action. + + Action rows are inline on ``AgentState`` nodes, under every key the + converter reads (``STATE_ACTION_ROW_KEYS``). + """ + candidates = [] + for node in model.get("nodes") or []: + if not isinstance(node, dict) or node.get("type") != "AgentState": + continue + data = node.get("data") or {} + if not isinstance(data, dict): + continue + for key in STATE_ACTION_ROW_KEYS: + rows = data.get(key) + if isinstance(rows, list): + candidates.extend(rows) + for element in candidates: if not isinstance(element, dict): continue if element.get("actionType") == "CustomCodeAction" or element.get("replyType") == "code": diff --git a/besser/utilities/web_modeling_editor/backend/routers/conversion_router.py b/besser/utilities/web_modeling_editor/backend/routers/conversion_router.py index ddffde3fc..c6e96bf02 100644 --- a/besser/utilities/web_modeling_editor/backend/routers/conversion_router.py +++ b/besser/utilities/web_modeling_editor/backend/routers/conversion_router.py @@ -55,11 +55,12 @@ from besser.utilities.web_modeling_editor.backend.services.converters import ( # JSON to BUML converters process_class_diagram, + process_bpmn_diagram, process_state_machine, process_agent_diagram, + annotate_agent_with_a2a, process_object_diagram, process_nn_diagram, - process_bpmn_diagram, process_component_diagram, process_deployment_diagram, json_to_buml_project, @@ -67,17 +68,18 @@ # BUML to JSON converters class_buml_to_json, parse_buml_content, + bpmn_buml_to_json, state_machine_to_json, agent_buml_to_json, gui_buml_to_json, project_to_json, nn_buml_to_json, - bpmn_buml_to_json, kg_buml_to_json, component_buml_to_json, deployment_buml_to_json, ) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import adopt_element_ids +from besser.utilities.web_modeling_editor.backend.services.converters.layout_adoption import adopt_existing_layout # Backend services - Other services from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import ( @@ -113,7 +115,9 @@ AGENT_TEMP_DIR_PREFIX, CSV_TEMP_DIR_PREFIX, OUTPUT_DIR_NAME, + BPMN_DIAGRAM_TYPES, BPMN_DIAGRAM_TYPE, + BPMN_PROJECT_DIAGRAM_KEY, DEPLOYMENT_DIAGRAM_TYPE, KG_DIAGRAM_TYPE, MAX_CSV_SIZE, @@ -139,6 +143,9 @@ from besser.utilities.web_modeling_editor.backend.routers.error_handler import ( handle_endpoint_errors, ) +from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_not_legacy_payload, +) logger = logging.getLogger(__name__) @@ -278,6 +285,7 @@ async def export_buml(input_data: DiagramInput, settings: SettingsDep): elif elements_data.get("type") == "AgentDiagram": # An export keeps a transition the agent could not run, with a logged warning. agent_model = process_agent_diagram(json_data, warnings=[]) + annotate_agent_with_a2a(agent_model, json_data) output_file_path = os.path.join(temp_dir, "agent_buml.py") agent_model_to_code(agent_model, output_file_path) file_content = await read_file_async(output_file_path, "rb") @@ -289,7 +297,7 @@ async def export_buml(input_data: DiagramInput, settings: SettingsDep): }, ) - elif elements_data.get("type") == BPMN_DIAGRAM_TYPE: + elif elements_data.get("type") in BPMN_DIAGRAM_TYPES: try: bpmn_model = process_bpmn_diagram(json_data) except (KeyError, TypeError, AttributeError) as exc: @@ -382,10 +390,15 @@ async def export_buml(input_data: DiagramInput, settings: SettingsDep): ) -def _import_repair_warnings(repairs: list[str], trace_warnings: list[str] = ()) -> list[dict] | None: - """What the import changed or left out to load a BUML file, in the response's warning shape.""" - return ([{"code": "buml-import-repaired", "message": message} for message in repairs] - + [{"code": "trace-not-imported", "message": message} for message in trace_warnings]) or None +def _import_repair_warnings( + repairs: list[str], unread: list[str] | None = None, trace_warnings: list[str] = (), +) -> list[dict] | None: + """What the import changed, could not read or left out in a BUML file, in the response's warning shape.""" + return ( + [{"code": "buml-import-repaired", "message": message} for message in repairs] + + [{"code": "buml-import-partial", "message": message} for message in unread or []] + + [{"code": "trace-not-imported", "message": message} for message in trace_warnings] + ) or None @router.post("/get-project-json-model", response_model=ProjectExportResponse) @@ -400,7 +413,7 @@ def convert(): repairs: list[str] = [] parsed_project = project_to_json(buml_content, repairs) trace, trace_warnings = import_project_trace(buml_content, parsed_project) - return parsed_project, trace, _import_repair_warnings(repairs, trace_warnings) + return parsed_project, trace, _import_repair_warnings(repairs, trace_warnings=trace_warnings) # Loading a project and its trace is CPU work: off the event loop. parsed_project, trace, warnings = await asyncio.to_thread(convert) @@ -414,10 +427,16 @@ def convert(): @router.post("/get-json-model", response_model=DiagramExportResponse) @handle_endpoint_errors("get_single_json_model") -async def get_single_json_model(buml_file: UploadFile = File(...)): +async def get_single_json_model(buml_file: UploadFile = File(...), existing_model: str = Form(None)): """ Convert a BUML Python file to JSON format for single diagram import. This endpoint handles both full project files and single diagram files. + + When `existing_model` is provided (as a stringified v4 diagram JSON of the + diagram the file updates), the imported diagram is laid out like it: + matched elements keep their id, position and size, new ones are placed + next to a neighbour. `warnings` then reports what was kept, added and not + in the file. Class, Agent and State Machine diagrams only. """ content = await buml_file.read() validate_upload(buml_file, max_size=MAX_BUML_SIZE, allowed_extensions=ALLOWED_BUML_EXTENSIONS, content=content) @@ -429,6 +448,7 @@ async def get_single_json_model(buml_file: UploadFile = File(...)): diagram_type = None parse_error = None repairs: list[str] = [] + unread: list[str] = [] safe_filename = os.path.basename(buml_file.filename) if buml_file.filename else "" diagram_title = safe_filename.rsplit('.', 1)[0] if safe_filename else "Imported Diagram" @@ -483,7 +503,8 @@ async def get_single_json_model(buml_file: UploadFile = File(...)): try: parsed_project = project_to_json(buml_content, repairs) - # project_to_json emits the schemaVersion=3 shape: + # project_to_json emits the schemaVersion=3 project envelope with + # v4 diagram models: # { diagrams: { ClassDiagram: [ {id,title,model,...}, ... ], ... }, # currentDiagramType: "...", # currentDiagramIndices: { ClassDiagram: 0, ... } } @@ -495,12 +516,13 @@ async def get_single_json_model(buml_file: UploadFile = File(...)): current_type = parsed_project.get("currentDiagramType") def _entry_is_populated(entry): + # v4 and Knowledge Graph models carry {nodes, edges}; GUI + # models keep their bespoke {pages} shape. model = (entry or {}).get("model") or {} return bool( - model.get("elements") - or model.get("relationships") + model.get("nodes") + or model.get("edges") or model.get("pages") - or model.get("nodes") # KnowledgeGraphDiagram ) def _pick_entry(dtype): @@ -519,7 +541,7 @@ def _pick_entry(dtype): for dtype in ( "ClassDiagram", "ObjectDiagram", "StateMachineDiagram", "AgentDiagram", "GUINoCodeDiagram", "NNDiagram", - "QuantumCircuitDiagram", BPMN_DIAGRAM_TYPE, + "QuantumCircuitDiagram", BPMN_PROJECT_DIAGRAM_KEY, KG_DIAGRAM_TYPE, "ComponentDiagram", DEPLOYMENT_DIAGRAM_TYPE, ): @@ -530,7 +552,9 @@ def _pick_entry(dtype): entry = _pick_entry(dtype) if entry is not None: diagram_data = entry - diagram_type = dtype + # The project bucket key is "BPMN"; the model type on + # the wire is BPMN_DIAGRAM_TYPE ("BPMNDiagram"). + diagram_type = BPMN_DIAGRAM_TYPE if dtype == BPMN_PROJECT_DIAGRAM_KEY else dtype break if diagram_data and diagram_data.get("title"): @@ -543,11 +567,15 @@ def _pick_entry(dtype): elif is_agent: try: logger.info("Detected Agent diagram, parsing...") - agent_json = agent_buml_to_json(buml_content) + agent_json = agent_buml_to_json(buml_content, unread) diagram_data = { "title": diagram_title, "model": agent_json } + # The editor keeps the default LLM on the diagram config envelope; + # model.config stays too, the processor reads it underneath. + if isinstance(agent_json.get("config"), dict): + diagram_data["config"] = dict(agent_json["config"]) diagram_type = "AgentDiagram" except Exception as agent_error: logger.error("Agent diagram parsing failed: %s", str(agent_error)) @@ -661,17 +689,20 @@ def _pick_entry(dtype): "KnowledgeGraphDiagram, ComponentDiagram, DeploymentDiagram, or Project." ) + model = {**diagram_data.get("model", {}), "type": diagram_type} + warnings = _import_repair_warnings(repairs, unread) or [] + if existing_model is not None: + model, layout_warnings = adopt_existing_layout(existing_model, model, diagram_type) + warnings.extend(layout_warnings) + # Return the diagram in the format expected by the frontend return { "title": diagram_title, - "model": { - **diagram_data.get("model", {}), - "type": diagram_type - }, + "model": model, "diagramType": diagram_type, "exportedAt": datetime.now(timezone.utc).isoformat(), "version": API_VERSION, - "warnings": _import_repair_warnings(repairs), + "warnings": warnings or None, } @router.post("/get-svg") @@ -681,7 +712,7 @@ async def get_svg(buml_file: UploadFile = File(...)): Convert a B-UML class-diagram file to an auto-laid-out SVG image. Pipeline: parse the B-UML to a DomainModel, convert it to the editor JSON - model, then delegate rendering to the WME Node server (Apollon, headless), + model, then delegate rendering to the WME Node server (headless editor), which runs ELK auto-layout and exports SVG. The Node server base URL is read from the WME_NODE_SERVER_URL env var (default http://localhost:8080). """ @@ -848,7 +879,8 @@ async def get_json_model_from_image( if existing_model: try: existing_json = json.loads(existing_model) - if existing_json.get("model", {}).get("elements") or existing_json.get("elements"): + ensure_not_legacy_payload(existing_json, "ClassDiagram", "existing_model") + if existing_json.get("model", {}).get("nodes") or existing_json.get("nodes"): payload = existing_json if "model" in existing_json else {"title": "Existing", "model": existing_json} existing_domain_model = process_class_diagram(payload) except (json.JSONDecodeError, ValueError): @@ -907,6 +939,7 @@ async def transform_agent_model_json(input_data: DiagramInput): logger.debug("[Agent transform] config: %s", json.dumps(sanitize_config(base_config), indent=2, default=str)) config = deepcopy(base_config) user_profile_payload = config.get("userProfileModel") if isinstance(config, dict) else None + ensure_not_legacy_payload(user_profile_payload, "UserDiagram", "config.userProfileModel") if isinstance(user_profile_payload, dict): config["userProfileModel"] = generate_user_profile_document(user_profile_payload) elif isinstance(config, dict) and "userProfileModel" in config: diff --git a/besser/utilities/web_modeling_editor/backend/routers/generation_router.py b/besser/utilities/web_modeling_editor/backend/routers/generation_router.py index 4cb712ad2..fc849aeca 100644 --- a/besser/utilities/web_modeling_editor/backend/routers/generation_router.py +++ b/besser/utilities/web_modeling_editor/backend/routers/generation_router.py @@ -71,6 +71,9 @@ GenerationError, ValidationError, ) +from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_not_legacy_payload, +) logger = logging.getLogger(__name__) @@ -107,6 +110,7 @@ async def recommend_agent_config_llm( user_profile_model = payload.get("userProfileModel") if not isinstance(user_profile_model, dict): raise ValidationError("userProfileModel is required and must be a JSON object") + ensure_not_legacy_payload(user_profile_model, "UserDiagram", "userProfileModel") user_profile_name = payload.get("userProfileName") if isinstance(payload.get("userProfileName"), str) else None current_config = payload.get("currentConfig") if isinstance(payload.get("currentConfig"), dict) else {} @@ -209,6 +213,7 @@ async def personalize_gui_page(payload: Dict[str, Any] = Body(...)): # gui_personalization_utils (mirroring agent_personalization). The router # only resolves the API key, delegates off the event loop, and shapes the # HTTP response; @handle_endpoint_errors maps ValidationError/GenerationError. + ensure_not_legacy_payload(payload.get("userProfileModel"), "UserDiagram", "userProfileModel") result = await asyncio.to_thread( run_gui_personalization, payload.get("guiPage"), @@ -277,6 +282,7 @@ async def recommend_agent_config_mapping( user_profile_model = payload.get("userProfileModel") if not isinstance(user_profile_model, dict): raise ValidationError("userProfileModel is required and must be a JSON object") + ensure_not_legacy_payload(user_profile_model, "UserDiagram", "userProfileModel") user_profile_name = payload.get("userProfileName") if isinstance(payload.get("userProfileName"), str) else None current_config = payload.get("currentConfig") if isinstance(payload.get("currentConfig"), dict) else {} diff --git a/besser/utilities/web_modeling_editor/backend/routers/github_deploy_api.py b/besser/utilities/web_modeling_editor/backend/routers/github_deploy_api.py index b8dc1911a..d93387933 100644 --- a/besser/utilities/web_modeling_editor/backend/routers/github_deploy_api.py +++ b/besser/utilities/web_modeling_editor/backend/routers/github_deploy_api.py @@ -49,6 +49,8 @@ from besser.utilities.provenance import write_generation_provenance from besser.utilities.web_modeling_editor.backend.services.generation.agents import has_agent_components from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import ( + agent_diagram_without_states, + agent_without_states_message, collect_agents_from_diagrams, extract_openai_api_key, normalize_personalization_mapping, @@ -57,9 +59,13 @@ generate_user_profile_document, ) from besser.utilities.web_modeling_editor.backend.services.exceptions import ( + ConversionError, GenerationError, ValidationError, ) +from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_project_not_legacy, +) from besser.utilities.web_modeling_editor.backend.models.responses import ( CommitStatus, DeployToGitHubResponse, @@ -140,6 +146,10 @@ async def deploy_webapp_to_github( detail="GitHub session expired. Please sign in again." ) + # Refuse legacy v3 diagrams before touching GitHub: the converters read + # only the v4 shape, so a v3 project would deploy an empty app. + ensure_project_not_legacy(body.get("diagrams") if isinstance(body, dict) else None) + # Create GitHub service github = create_github_service(access_token) @@ -194,7 +204,12 @@ def _get_all(diagram_type: str) -> list: ) agent_model_payload = agent_diagram_data.get("model") - if isinstance(agent_model_payload, dict) and not agent_model_payload.get("elements"): + if agent_diagram_without_states(agent_model_payload): + raise HTTPException( + status_code=400, + detail=agent_without_states_message(agent_diagram_data.get("title")), + ) + if isinstance(agent_model_payload, dict) and not agent_model_payload.get("nodes"): raise HTTPException( status_code=400, detail="AgentDiagram must contain at least one element for standalone chatbot deployment", @@ -567,8 +582,9 @@ def _get_all(diagram_type: str) -> list: except HTTPException: raise - except ValidationError as e: - # Service-layer validation failures map to HTTP 400 with the original message. + except (ValidationError, ConversionError) as e: + # Service-layer validation/conversion failures (including a legacy v3 + # diagram) map to HTTP 400 with the original message. raise HTTPException(status_code=400, detail=str(e)) from e except GenerationError as e: # Service-layer generation/deployment failures map to HTTP 500 with the diff --git a/besser/utilities/web_modeling_editor/backend/routers/validation_router.py b/besser/utilities/web_modeling_editor/backend/routers/validation_router.py index a83a0418b..84d9f8ba5 100644 --- a/besser/utilities/web_modeling_editor/backend/routers/validation_router.py +++ b/besser/utilities/web_modeling_editor/backend/routers/validation_router.py @@ -21,13 +21,18 @@ # Backend services - Converters from besser.utilities.web_modeling_editor.backend.services.converters import ( process_class_diagram, + process_bpmn_diagram, process_state_machine, process_agent_diagram, process_object_diagram, process_nn_diagram, process_component_diagram, process_deployment_diagram, - process_bpmn_diagram, +) +from besser.utilities.web_modeling_editor.backend.constants.constants import ( + BPMN_DIAGRAM_TYPES, + DEPLOYMENT_DIAGRAM_TYPE, + KG_DIAGRAM_TYPE, ) from besser.utilities.web_modeling_editor.backend.services.kg.payloads import parse_kg_diagram from besser.utilities.web_modeling_editor.backend.services.kg.validation import ( @@ -36,11 +41,6 @@ from besser.utilities.web_modeling_editor.backend.constants.user_buml_model import ( domain_model as user_reference_domain_model, ) -from besser.utilities.web_modeling_editor.backend.constants.constants import ( - BPMN_DIAGRAM_TYPE, - DEPLOYMENT_DIAGRAM_TYPE, - KG_DIAGRAM_TYPE, -) # Backend services - Validators from besser.utilities.web_modeling_editor.backend.services.validators import ( @@ -78,24 +78,25 @@ def _unnamed_users(model: dict) -> tuple[list[str], list[str]]: - """Return unnamed User ids and those needing a name attribute row.""" - elements = model.get("elements") or {} + """Return unnamed User node ids and those needing a ``name`` attribute row.""" unnamed, missing = [], [] - for element_id, user in elements.items(): - if not isinstance(user, dict) or user.get("type") != "UserModelName" or user.get("className") != "User": + for node in model.get("nodes") or []: + data = node.get("data") if isinstance(node, dict) else None + if not isinstance(data, dict) or node.get("type") != "UserModelName" or data.get("className") != "User": continue name_rows = [] - for attr_id in user.get("attributes") or []: - attr = elements.get(attr_id) - if not isinstance(attr, dict) or attr.get("type") != "UserModelAttribute": + for row in data.get("attributes") or []: + if not isinstance(row, dict): continue - parts = re.split(r"<=|>=|==|=|<|>", str(attr.get("name") or ""), maxsplit=1) + # A row has a bare name with its value in ``value``, or a legacy "name = value" name. + parts = re.split(r"<=|>=|==|=|<|>", str(row.get("name") or ""), maxsplit=1) if parts[0].strip() == "name": - name_rows.append(parts[1].strip() if len(parts) > 1 else "") + value = parts[1] if len(parts) > 1 else row.get("value", row.get("defaultValue")) + name_rows.append(str(value or "").strip()) if not name_rows or not any(name_rows): - unnamed.append(element_id) + unnamed.append(node.get("id")) if not name_rows: - missing.append(element_id) + missing.append(node.get("id")) return unnamed, missing @@ -150,12 +151,16 @@ async def validate_diagram(input_data: DiagramInput, kg_slots: KgConsistencySlot "message": "\u274c Validation failed" } - # Process the reference class diagram first + # Process the reference class diagram first. v4 models always + # carry ``title``; migrated ones may leave it empty. + reference_title = reference_data.get("title") + if not (reference_title or "").strip(): + reference_title = "Reference Classes" reference_json = { - "title": reference_data.get("title", "Reference Classes"), + "title": reference_title, "model": { - "elements": reference_data.get("elements", {}), - "relationships": reference_data.get("relationships", {}) + "nodes": reference_data.get("nodes", []), + "edges": reference_data.get("edges", []), } } buml_model = process_class_diagram(reference_json) @@ -241,15 +246,15 @@ async def validate_diagram(input_data: DiagramInput, kg_slots: KgConsistencySlot validation_errors.extend(nn_validation["errors"]) validation_warnings.extend(nn_validation["warnings"]) - elif diagram_type == BPMN_DIAGRAM_TYPE: + elif diagram_type in BPMN_DIAGRAM_TYPES: try: bpmn_model = process_bpmn_diagram(input_data.model_dump()) except (ConversionError, ValueError) as e: validation_errors.extend(str(e).splitlines()) else: bpmn_validation = bpmn_model.validate(raise_exception=False) - validation_errors.extend(bpmn_validation["errors"]) - validation_warnings.extend(bpmn_validation["warnings"]) + validation_errors.extend(bpmn_validation.get("errors", [])) + validation_warnings.extend(bpmn_validation.get("warnings", [])) elif diagram_type == "QuantumCircuitDiagram": return { diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/__init__.py b/besser/utilities/web_modeling_editor/backend/services/converters/__init__.py index da6198138..a731fe787 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/__init__.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/__init__.py @@ -4,6 +4,7 @@ from .json_to_buml import ( process_class_diagram, + process_bpmn_diagram, process_state_machine, process_agent_diagram, annotate_agent_with_a2a, @@ -12,7 +13,6 @@ process_gui_diagram, process_quantum_diagram, process_nn_diagram, - process_bpmn_diagram, process_kg_diagram, process_component_diagram, process_deployment_diagram, @@ -22,6 +22,8 @@ from .buml_to_json import ( class_buml_to_json, parse_buml_content, + bpmn_object_to_json, + bpmn_buml_to_json, state_machine_to_json, state_machine_object_to_json, agent_buml_to_json, @@ -34,8 +36,6 @@ empty_model, nn_model_to_json, nn_buml_to_json, - bpmn_object_to_json, - bpmn_buml_to_json, kg_to_json, kg_buml_to_json, component_object_to_json, @@ -48,6 +48,7 @@ __all__ = [ "process_class_diagram", + "process_bpmn_diagram", "process_state_machine", "process_agent_diagram", "annotate_agent_with_a2a", @@ -56,7 +57,6 @@ "process_gui_diagram", "process_quantum_diagram", "process_nn_diagram", - "process_bpmn_diagram", "process_kg_diagram", "process_component_diagram", "process_deployment_diagram", @@ -64,6 +64,8 @@ "process_trace", "class_buml_to_json", "parse_buml_content", + "bpmn_object_to_json", + "bpmn_buml_to_json", "state_machine_to_json", "state_machine_object_to_json", "agent_buml_to_json", @@ -76,8 +78,6 @@ "empty_model", "nn_model_to_json", "nn_buml_to_json", - "bpmn_object_to_json", - "bpmn_buml_to_json", "kg_to_json", "kg_buml_to_json", "component_object_to_json", diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/__init__.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/__init__.py index 3f771dcb4..8798db3e1 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/__init__.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/__init__.py @@ -3,6 +3,7 @@ """ from .class_diagram_converter import class_buml_to_json, parse_buml_content +from .bpmn_diagram_converter import bpmn_object_to_json, bpmn_buml_to_json from .state_machine_converter import state_machine_to_json, state_machine_object_to_json from .agent_diagram_converter import agent_buml_to_json, analyze_function_node from .object_diagram_converter import object_buml_to_json @@ -10,7 +11,6 @@ from .project_converter import project_to_json, project_trace_to_json, empty_model from .quantum_diagram_converter import quantum_circuit_to_json, quantum_circuit_to_editor_json, quantum_buml_to_json from .nn_diagram_converter import nn_model_to_json, nn_buml_to_json -from .bpmn_diagram_converter import bpmn_object_to_json, bpmn_buml_to_json from .kg_diagram_converter import kg_to_json, kg_buml_to_json from .component_diagram_converter import component_object_to_json, component_buml_to_json from .deployment_diagram_converter import deployment_object_to_json, deployment_buml_to_json @@ -19,6 +19,8 @@ __all__ = [ 'class_buml_to_json', 'parse_buml_content', + 'bpmn_object_to_json', + 'bpmn_buml_to_json', 'state_machine_to_json', 'state_machine_object_to_json', 'agent_buml_to_json', @@ -34,8 +36,6 @@ 'quantum_buml_to_json', 'nn_model_to_json', 'nn_buml_to_json', - 'bpmn_object_to_json', - 'bpmn_buml_to_json', 'kg_to_json', 'kg_buml_to_json', 'component_object_to_json', diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/_node_builders.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/_node_builders.py new file mode 100644 index 000000000..dda79ddec --- /dev/null +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/_node_builders.py @@ -0,0 +1,321 @@ +"""Helpers for emitting the v4 ``{nodes[], edges[]}`` wire shape. + +These helpers replace the v3 ``add_element`` / ``add_relationship`` +idioms used throughout the legacy converters with a tiny, consistent +node / edge builder API. Every v4 emitter in ``buml_to_json`` should +funnel through ``make_node`` and ``make_edge`` so the on-the-wire shape +stays consistent with the spec at +``docs/source/migrations/uml-v4-shape.md``. +""" + +from __future__ import annotations + +import math +import re +from typing import Any, Iterable, Optional + +# Default values applied when callers omit them. They mirror the spec +# defaults documented in uml-v4-shape.md. +_DEFAULT_NODE_WIDTH = 160 +_DEFAULT_NODE_HEIGHT = 100 + + +# v3 ``Direction`` -> v4 ``HandleId``; mirrors the frontend's +# ``convertV3HandleToV4`` (packages/library/lib/utils/versionConverter.ts). +_V3_HANDLE_TO_V4 = { + "Up": "top", "Right": "right", "Down": "bottom", "Left": "left", + "Upright": "right-top", "Upleft": "left-top", + "Downright": "right-bottom", "Downleft": "left-bottom", + "RightTop": "top-right", "RightBottom": "bottom-right", + "LeftTop": "top-left", "LeftBottom": "bottom-left", +} +_V3_CORNER_HANDLE = re.compile(r"^(top|bottom|left|right)(top|bottom|left|right)$", re.IGNORECASE) + + +def normalize_handle(handle: Optional[str]) -> Optional[str]: + """Return the v4 handle id (``right``, ``top-left``...) for a stored handle. + + Older exports carry v3 directions (``Right``, ``Up``, ``Topleft``); React + Flow cannot resolve those against the editor's lowercase handles and + drops the edge. + """ + if not handle: + return handle + if handle in _V3_HANDLE_TO_V4: + return _V3_HANDLE_TO_V4[handle] + corner = _V3_CORNER_HANDLE.match(handle) + if corner: + return f"{corner.group(1).lower()}-{corner.group(2).lower()}" + return handle.lower() + + +def snap_up(value: float, step: int = 10) -> int: + """Round up to the editor's 10px extension grid (``calculateMinWidth/Height``).""" + return int(math.ceil(value / step) * step) + + +def grid_layout( + nodes: Iterable[dict], + origin: tuple = (0, 0), + columns: int = 3, + gap_x: int = 140, + gap_y: int = 100, +) -> None: + """Place ``nodes`` row by row on a grid sized from their own width/height. + + Column width is the widest node in that column and row height the + tallest node in that row, so nodes never overlap whatever their size. + """ + nodes = list(nodes) + col_widths = [0] * columns + row_heights = [0] * (len(nodes) // columns + 1) + for i, node in enumerate(nodes): + col_widths[i % columns] = max(col_widths[i % columns], node["width"]) + row_heights[i // columns] = max(row_heights[i // columns], node["height"]) + for i, node in enumerate(nodes): + col, row = i % columns, i // columns + node["position"] = { + "x": origin[0] + sum(col_widths[:col]) + col * gap_x, + "y": origin[1] + sum(row_heights[:row]) + row * gap_y, + } + + +def points_from_layout(layout: dict) -> list: + """Absolute v4 edge points from an edge ``layout`` stash. + + v4 stashes keep ``points``; ``.py`` files exported before the v4 migration + carry the v3 ``path`` (relative to the edge ``bounds``) instead. + """ + if layout.get("points"): + return layout["points"] + path = layout.get("path") or [] + bounds = layout.get("bounds") or {} + return [ + {"x": p.get("x", 0) + bounds.get("x", 0), "y": p.get("y", 0) + bounds.get("y", 0)} + for p in path + ] + + +def make_positions_parent_relative(nodes: list, absolute_ids: set) -> None: + """Turn absolute positions into ``parentId``-relative ones, in place. + + Only nodes whose position and parent position are both absolute (ids in + ``absolute_ids``, typically the nodes placed from a stashed ``bounds``) are + shifted; fallback positions are already relative. + """ + absolute = {node["id"]: dict(node["position"]) for node in nodes} + for node in nodes: + parent_id = node.get("parentId") + if parent_id in absolute and node["id"] in absolute_ids and parent_id in absolute_ids: + node["position"] = { + "x": absolute[node["id"]]["x"] - absolute[parent_id]["x"], + "y": absolute[node["id"]]["y"] - absolute[parent_id]["y"], + } + + +def layout_unplaced_nodes(nodes: list, placed_ids: set, padding: int = 20, header: int = 40) -> None: + """Give every node not in ``placed_ids`` a non-overlapping position, in place. + + Children of a container are put in a row inside it (below a ``header`` + strip), and an unplaced container grows to enclose them; unplaced roots go + on a grid. Used when a model built in Python carries no editor layout. + """ + children: dict = {} + for node in nodes: + children.setdefault(node.get("parentId"), []).append(node) + + def fit(node: dict) -> None: + kids = children.get(node["id"], []) + for kid in kids: + fit(kid) + unplaced = [kid for kid in kids if kid["id"] not in placed_ids] + x = padding + for kid in unplaced: + kid["position"] = {"x": x, "y": header} + x += kid["width"] + padding + if node["id"] not in placed_ids and kids: + right = max(k["position"]["x"] + k["width"] for k in kids) + padding + bottom = max(k["position"]["y"] + k["height"] for k in kids) + padding + node["width"] = max(node["width"], right) + node["height"] = max(node["height"], bottom) + node["measured"] = {"width": node["width"], "height": node["height"]} + + roots = children.get(None, []) + for root in roots: + fit(root) + placed_roots = [root for root in roots if root["id"] in placed_ids] + origin_x = max((r["position"]["x"] + r["width"] for r in placed_roots), default=-140) + 140 + grid_layout([root for root in roots if root["id"] not in placed_ids], origin=(origin_x, 0)) + + +def envelope_size(nodes: list) -> dict: + """Bounding box of all top-level node bounds, with a sensible minimum.""" + max_x = 0 + max_y = 0 + for node in nodes: + if node.get("parentId"): + continue # child positions are relative to their parent + position = node.get("position") or {} + right = (position.get("x") or 0) + (node.get("width") or 0) + bottom = (position.get("y") or 0) + (node.get("height") or 0) + max_x = max(max_x, right) + max_y = max(max_y, bottom) + return {"width": max(int(max_x) + 40, 800), "height": max(int(max_y) + 40, 600)} + + +def make_node( + node_id: str, + type_: str, + data: dict, + position: dict, + parent_id: Optional[str] = None, + width: Optional[int] = None, + height: Optional[int] = None, + measured: Optional[dict] = None, + **extra: Any, +) -> dict: + """Build a v4 React-Flow node. + + ``position`` is a ``{x, y}`` dict. ``width`` / ``height`` default + to the v4 spec values when omitted. ``measured`` defaults to + ``{width, height}`` if not given. ``extra`` is merged onto the + top-level node dict for any one-off fields a caller needs. + """ + if not isinstance(position, dict) or "x" not in position or "y" not in position: + position = {"x": position.get("x", 0) if isinstance(position, dict) else 0, + "y": position.get("y", 0) if isinstance(position, dict) else 0} + w = width if width is not None else _DEFAULT_NODE_WIDTH + h = height if height is not None else _DEFAULT_NODE_HEIGHT + node: dict = { + "id": node_id, + "type": type_, + "position": {"x": position["x"], "y": position["y"]}, + "width": w, + "height": h, + "measured": measured if measured is not None else {"width": w, "height": h}, + "data": data or {}, + } + if parent_id: + node["parentId"] = parent_id + if extra: + # Allow callers to inject extra top-level fields without colliding + # with the canonical ones above. + for key, value in extra.items(): + if key in node: + continue + node[key] = value + return node + + +def make_edge( + edge_id: str, + source: str, + target: str, + type_: str, + data: Optional[dict] = None, + source_handle: str = "right", + target_handle: str = "left", + **extra: Any, +) -> dict: + """Build a v4 React-Flow edge. + + ``data`` is the per-edge payload (always normalised to include a + ``points`` list, even if empty). Handles are normalised to v4 ids, except + on ``ClassLinkRel``, whose edge-anchored ``Center`` / ``Up`` pair is canonical. + """ + if type_ != "ClassLinkRel": + source_handle = normalize_handle(source_handle) + target_handle = normalize_handle(target_handle) + edge_data: dict = dict(data or {}) + edge_data.setdefault("points", []) + edge: dict = { + "id": edge_id, + "source": source, + "target": target, + "type": type_, + "sourceHandle": source_handle, + "targetHandle": target_handle, + "data": edge_data, + } + if extra: + for key, value in extra.items(): + if key in edge: + continue + edge[key] = value + return edge + + +def empty_model(diagram_type: str, title: str = "") -> dict: + """Return an empty v4 model envelope of the given diagram type. + + Useful for converters that need to short-circuit when there's nothing + to emit. + """ + return { + "version": "4.0.0", + "type": diagram_type, + "title": title, + "size": {"width": 0, "height": 0}, + "nodes": [], + "edges": [], + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {}, + } + + +def parents_first(nodes: list) -> list: + """Order ``nodes`` so every parent precedes its children (React Flow requires it).""" + by_id = {node["id"]: node for node in nodes} + ordered: list = [] + seen: set = set() + + def visit(node: dict) -> None: + if node["id"] in seen: + return + seen.add(node["id"]) + parent = by_id.get(node.get("parentId")) + if parent is not None: + visit(parent) + ordered.append(node) + + for node in nodes: + visit(node) + return ordered + + +def node_from_layout(obj, node_id: str, node_type: str, data: dict, parent_id, default_size: tuple) -> dict: + """``make_node`` from the element's stashed absolute bounds (else ``default_size`` + at the origin) and stashed colours. Positions are made parent-relative later + (``make_positions_parent_relative``).""" + layout = obj.layout or {} + for style_key in ("fillColor", "strokeColor", "textColor", "highlight"): + if style_key in layout: + data[style_key] = layout[style_key] + width, height = default_size + bounds = layout.get("bounds") or {"x": 0, "y": 0, "width": width, "height": height} + return make_node( + node_id=node_id, type_=node_type, data=data, + position={"x": bounds.get("x", 0), "y": bounds.get("y", 0)}, + parent_id=parent_id, + width=bounds.get("width") or width, height=bounds.get("height") or height, + ) + + +def stereotyped_edge(rel, id_for, edge_type: str, stereotype: str) -> dict: + """``make_edge`` for a Component / Deployment relationship (``name``, ``label``, + optional ``stereotype``), routed from its layout stash.""" + layout = rel.layout or {} + data = { + "name": rel.name or "", + "label": rel.name or "", + "points": points_from_layout(layout), + "isManuallyLayouted": bool(layout.get("isManuallyLayouted", False)), + } + if stereotype: + data["stereotype"] = stereotype + return make_edge( + edge_id=id_for(rel), source=id_for(rel.source), target=id_for(rel.target), + type_=edge_type, data=data, + source_handle=layout.get("source_direction") or "right", + target_handle=layout.get("target_direction") or "left", + ) diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/agent_diagram_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/agent_diagram_converter.py index fe0317ea0..b4107059a 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/agent_diagram_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/agent_diagram_converter.py @@ -1,16 +1,25 @@ """ -Agent converter module for BUML to JSON conversion. -Handles agent diagram processing and function analysis. +Agent BUML -> v4 JSON converter. + +The agent code is parsed (``ast``) into a flat element index keyed by id +(states, their action rows, comments, components, transitions), which +``_flat_to_v4`` then turns into the v4 wire shape: canvas ``nodes`` / +``edges`` plus the off-canvas ``components`` map. ``AgentStateTransition`` +edges are emitted in the canonical form (``transitionType + +predefined|custom``); legacy variants are an *input* concern handled by the +agent processor's ``_normalise_agent_transitions``. """ import ast import logging import textwrap import uuid -from typing import Any, Dict, List +from typing import Any, Dict, List, Optional from besser.utilities.buml_code_builder.agent_model_builder import GUI_BUILDER_FUNCTION_PREFIX +from ..json_to_buml.a2a_tags import format_a2a_line from .gui_diagram_converter import gui_buml_to_json +from ._node_builders import make_edge, make_node from ...utils.layout_calculator import ( determine_connection_direction, calculate_connection_points, @@ -137,12 +146,19 @@ def analyze_function_node(node: ast.FunctionDef, source_code: str) -> Dict[str, } -def agent_buml_to_json(content: str) -> Dict[str, Any]: +def _note_unread(warnings: Optional[List[str]], what: str, error: Exception) -> None: + """Record that ``what`` was left out of the diagram because reading it failed.""" + if warnings is not None: + warnings.append(f"Left out {what} of the agent file that could not be read ({type(error).__name__}: {error}).") + + +def _agent_buml_to_flat_json(content: str, warnings: Optional[List[str]] = None) -> Dict[str, Any]: """ Convert an agent Python file content to JSON format matching the frontend structure. Args: content: Agent model Python code as string + warnings: Receives a message for every part of the file that could not be read Returns: Dictionary representing the agent diagram in JSON format @@ -193,7 +209,23 @@ def _add_action_elements_to_state(state_id: str, action_data: Any, fallback: boo continue action_type = action.get("type") - if action_type == "text": + if action_type == "code": + body_id = str(uuid.uuid4()) + elements[body_id] = { + "id": body_id, + "name": action.get("code") or "", + "type": element_type, + "owner": state_id, + "bounds": { + "x": elements[state_id]["bounds"]["x"], + "y": elements[state_id]["bounds"]["y"], + "width": 159, + "height": 30, + }, + "actionType": "CustomCodeAction", + } + elements[state_id][state_key].append(body_id) + elif action_type == "text": message = action.get("message") or "" body_id = str(uuid.uuid4()) elements[body_id] = { @@ -1076,7 +1108,22 @@ def _resolve_condition_source(condition_ref_name: str) -> str: action_var = node.value.args[0].id # e.g., 'CustomCodeAction_initial' if action_var in custom_code_actions: function_name = custom_code_actions[action_var] # e.g., 'action_name' - actions[body_var] = function_name # Store the resolved function name + actions.setdefault(body_var, []).append({ + "type": "code", + "function": function_name, + "code": functions.get(function_name, {}).get("source", ""), + }) + + # A body that is a single code action keeps its function name, the + # form the state-body pass analyzes; code mixed with other replies + # stays a row in the list. + for body_var, body_actions in actions.items(): + if ( + isinstance(body_actions, list) + and len(body_actions) == 1 + and body_actions[0].get("type") == "code" + ): + actions[body_var] = body_actions[0]["function"] # Create initial node initial_node_id = str(uuid.uuid4()) @@ -1363,6 +1410,8 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: }, "actions": [], "fallbackActions": [], + "bodies": [], + "fallbackBodies": [], } # Update position for next element @@ -1382,33 +1431,6 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: if kw.arg == "description": state_comments[state_var] = ast.literal_eval(kw.value) - # Also store by state name for body lookup - if state_name != var_name: - states[state_name] = state_obj - - # Create element for visualization - elements[state_id] = { - "id": state_id, - "name": state_name, - "type": "AgentState", - "stateType": "standard", - "owner": None, - "bounds": { - "x": states_x, - "y": states_y, - "width": 160, - "height": 100, - }, - "actions": [], - "fallbackActions": [], - } - - # Update position for next element - if states_x < 200: - states_x += 490 - else: - states_x = -280 - states_y += 220 # Find initial state and create initial transition initial_state = None @@ -1827,6 +1849,7 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: except Exception as e: logger.error("Error processing agent body: %s", e, exc_info=True) + _note_unread(warnings, "a state body", e) continue # Add handling for fallback bodies @@ -1969,9 +1992,11 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: elements[state["id"]]["fallbackBodies"].append(body_id) except Exception as e: logger.warning("Error processing agent fallback body: %s", e, exc_info=True) + _note_unread(warnings, "a fallback body", e) continue except Exception as e: logger.error("Error processing agent state machine: %s", e, exc_info=True) + _note_unread(warnings, "a statement", e) continue # Find initial state and create initial transition initial_state = None @@ -2172,8 +2197,13 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: result["config"] = {"default_llm_name": default_llm_name_value} return result - except Exception: + except Exception as e: logger.exception("Error converting agent BUML to JSON; returning partial diagram") + if warnings is not None: + warnings.append( + f"The agent file could be read only up to an unsupported statement ({type(e).__name__}: {e}); " + "the diagram holds what was read before it, the rest of the file is not imported." + ) # On error return partial results, also split into canvas / components _COMPONENT_TYPES_FALLBACK = { 'AgentIntent', 'AgentIntentBody', 'AgentRagElement', @@ -2196,3 +2226,231 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: "relationships": relationships, "assessments": {}, } + + +# --------------------------------------------------------------------------- +# v4 wire shape +# --------------------------------------------------------------------------- + +# Off-canvas agent component types: emitted in the top-level ``components`` +# map, never as canvas nodes (see uml-v4-shape.md, AgentDiagram -> Components). +AGENT_COMPONENT_TYPES = frozenset({ + "AgentIntent", "AgentIntentBody", "AgentRagElement", "AgentTool", + "AgentSkill", "AgentWorkspace", "AgentLLM", "AgentGUI", +}) + +# replyType (editor key) <-> actionType (metamodel class name). Body rows carry both. +REPLY_TYPE_TO_ACTION_TYPE = { + "text": "TextReplyAction", + "llm": "LLMReplyAction", + "llm_chat": "LLMChatAction", + "rag": "RAGReplyAction", + "db_reply": "DBAction", + "code": "CustomCodeAction", + "web_crawl_llm": "WebCrawlLLMAction", + "ws_markdown": "WebSocketReplyMarkdownAction", + "ws_html": "WebSocketReplyHTMLAction", + "ws_speech": "WebSocketReplySpeechAction", + "ws_options": "WebSocketReplyOptionsAction", + "ws_location": "WebSocketReplyLocationAction", + "ws_file": "WebSocketReplyFileAction", + "ws_image": "WebSocketReplyImageAction", + "ws_dataframe": "WebSocketReplyDataframeAction", + "ws_plotly": "WebSocketReplyPlotlyAction", + "gui_reply": "GUIReplyAction", +} +ACTION_TYPE_TO_REPLY_TYPE = {v: k for k, v in REPLY_TYPE_TO_ACTION_TYPE.items()} + +_ROW_DROP_KEYS = ("type", "owner", "bounds") +_COMPONENT_DROP_KEYS = ("bounds", "llm", "numPreviousMessages") + + +def _body_rows(elements: Dict[str, Any], ids: List[str]) -> List[Dict[str, Any]]: + """Inline the body elements referenced by ``ids`` as v4 ``data.bodies`` rows.""" + rows: List[Dict[str, Any]] = [] + seen = set() + for body_id in ids or []: + if body_id in seen: + continue + seen.add(body_id) + element = elements.get(body_id) + if not isinstance(element, dict): + continue + row = {k: v for k, v in element.items() if k not in _ROW_DROP_KEYS} + action_type = row.get("actionType") + reply_type = row.get("replyType") + if not reply_type: + reply_type = ACTION_TYPE_TO_REPLY_TYPE.get(action_type, "text") + row["replyType"] = reply_type + if not action_type: + row["actionType"] = REPLY_TYPE_TO_ACTION_TYPE.get(reply_type, reply_type) + if row["replyType"] == "code" and "code" not in row: + # v4 code rows carry the source on ``code`` (``name`` doubles as label). + row["code"] = row.get("name", "") + rows.append(row) + return rows + + +def _flat_to_v4(flat: Dict[str, Any]) -> Dict[str, Any]: + """Turn the flat element index built by the parser into the v4 wire shape.""" + elements: Dict[str, Any] = flat.get("elements") or {} + relationships: Dict[str, Any] = flat.get("relationships") or {} + components: Dict[str, Any] = dict(flat.get("components") or {}) + + # Component entries that ended up in ``elements`` (defensive) move out too. + for element_id, element in list(elements.items()): + if element.get("type") in AGENT_COMPONENT_TYPES: + components.setdefault(element_id, element) + components = { + cid: {k: v for k, v in comp.items() if k not in _COMPONENT_DROP_KEYS} + for cid, comp in components.items() + } + + initial_marker_ids = {eid for eid, el in elements.items() if el.get("type") == "StateInitialNode"} + initial_state_ids = set() + for rel in relationships.values(): + source_id = (rel.get("source") or {}).get("element") + if rel.get("type") == "AgentStateTransitionInit" or source_id in initial_marker_ids: + target_id = (rel.get("target") or {}).get("element") + if target_id: + initial_state_ids.add(target_id) + + nodes: List[Dict[str, Any]] = [] + for element_id, element in elements.items(): + element_type = element.get("type") + bounds = element.get("bounds") or {} + position = {"x": bounds.get("x", 0), "y": bounds.get("y", 0)} + if element_type == "AgentState": + data: Dict[str, Any] = { + "name": element.get("name", ""), + "initial": element_id in initial_state_ids, + "stateType": element.get("stateType") or "standard", + "bodies": _body_rows( + elements, list(element.get("actions") or []) + list(element.get("bodies") or []) + ), + "fallbackBodies": _body_rows( + elements, + list(element.get("fallbackActions") or []) + list(element.get("fallbackBodies") or []), + ), + } + if data["stateType"] == "reasoning": + data.update({ + "llm_name": element.get("llm_name") or "", + "max_steps": element.get("max_steps", 8), + "enable_task_planning": element.get("enable_task_planning", True), + "stream_steps": element.get("stream_steps", True), + "system_prompt": element.get("system_prompt") or "", + "fallback_message": element.get("fallback_message") or "", + }) + nodes.append(make_node( + node_id=element_id, type_="AgentState", data=data, position=position, + width=bounds.get("width", 160), height=bounds.get("height", 100), + )) + elif element_type == "Comments": + nodes.append(make_node( + node_id=element_id, type_="comment", data={"name": element.get("name", "")}, + position=position, width=bounds.get("width", 200), height=bounds.get("height", 100), + )) + + edges: List[Dict[str, Any]] = [] + for rel_id, rel in relationships.items(): + rel_type = rel.get("type") + source = rel.get("source") or {} + target = rel.get("target") or {} + source_id = source.get("element") + target_id = target.get("element") + handles = { + "source_handle": source.get("direction") or "right", + "target_handle": target.get("direction") or "left", + } + if rel_type == "AgentStateTransition" and source_id not in initial_marker_ids: + transition_type = rel.get("transitionType") or "predefined" + edge_data: Dict[str, Any] = {"name": rel.get("name") or "", "transitionType": transition_type} + if transition_type == "custom": + custom = dict(rel.get("custom") or {}) + custom.setdefault("event", "None") + custom.setdefault("condition", []) + edge_data["custom"] = custom + else: + predefined = { + k: v for k, v in (rel.get("predefined") or {}).items() + if not (k == "conditionValue" and v in (None, "")) + } + edge_data["predefined"] = predefined + edges.append(make_edge(rel_id, source_id, target_id, "AgentStateTransition", edge_data, **handles)) + elif rel_type == "Link": + edges.append(make_edge(rel_id, source_id, target_id, "CommentLink", {}, **handles)) + + result: Dict[str, Any] = { + "version": "4.0.0", + "type": "AgentDiagram", + "title": "", + "size": flat.get("size") or {"width": 1980, "height": 640}, + "nodes": nodes, + "edges": edges, + "components": components, + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {}, + } + if flat.get("config"): + result["config"] = flat["config"] + return result + + +def agent_buml_to_json(content: str, warnings: Optional[List[str]] = None) -> Dict[str, Any]: + """Convert agent B-UML Python code to the v4 AgentDiagram wire shape. + + Canvas: ``AgentState`` nodes (inline ``data.bodies`` / ``data.fallbackBodies`` + action rows, ``data.initial``, reasoning states as ``data.stateType == + 'reasoning'``), ``comment`` nodes, ``AgentStateTransition`` and + ``CommentLink`` edges. Off-canvas: intents (+ ``AgentIntentBody`` entries), + LLMs, RAG databases, tools, skills, workspaces and GUIs in the top-level + ``components`` map. + + ``warnings`` receives a message for every part of the file that could not + be read and is missing from the diagram (the parser recognises the forms + the B-UML exporter writes, not every way to build an agent). + """ + model = _flat_to_v4(_agent_buml_to_flat_json(content, warnings)) + _restore_a2a_tags(model, _read_a2a(content)) + return model + + +def _read_a2a(content: str) -> Dict[str, Any]: + """The ``._a2a = {...}`` literal ``agent_model_to_code`` writes, or {}.""" + for node in ast.parse(content).body: + if (isinstance(node, ast.Assign) and len(node.targets) == 1 + and isinstance(node.targets[0], ast.Attribute) and node.targets[0].attr == "_a2a"): + try: + value = ast.literal_eval(node.value) + except (ValueError, SyntaxError): + return {} + return value if isinstance(value, dict) else {} + return {} + + +def _restore_a2a_tags(model: Dict[str, Any], a2a: Dict[str, Any]) -> None: + """Put the a2a tags back where the editor keeps them: ``a2a:out`` lines on the + state's ``data.description``, ``a2a:in`` on the transition's ``data.name``.""" + states = {n["id"]: n["data"] for n in model["nodes"] if n["type"] == "AgentState"} + by_name = {data.get("name"): data for data in states.values()} + if not all(isinstance(a2a.get(key) or [], list) for key in ("outbound", "inbound")): + return + for edge in a2a.get("outbound") or []: + line = format_a2a_line(edge) + data = by_name.get(edge.get("state")) if line else None + if data is not None: + data["description"] = f"{data['description']}\n{line}" if data.get("description") else line + for edge in a2a.get("inbound") or []: + line = format_a2a_line(edge) + if not line: + continue + for transition in model["edges"]: + data = transition["data"] + if (transition["type"] == "AgentStateTransition" + and not str(data.get("name", "")).startswith("a2a:") + and (states.get(transition["source"]) or {}).get("name") == edge.get("source_state") + and (states.get(transition["target"]) or {}).get("name") == edge.get("target_state") + and (data.get("predefined") or {}).get("intentName", "") == edge.get("intent", "")): + data["name"] = line + break diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/bpmn_diagram_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/bpmn_diagram_converter.py index 9c228e2e5..4a08ff24d 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/bpmn_diagram_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/bpmn_diagram_converter.py @@ -1,5 +1,11 @@ """BPMN conversion from BUML to JSON format. +Emits the v4 wire shape (``{nodes, edges}``) directly — mirrors +``buml_to_json/class_diagram_converter.py`` (``make_node``/``make_edge`` from +``_node_builders``). The metamodel is walked pools -> lanes -> process +contents -> data stores -> flows; every node is emitted with its ``parentId`` +and each flow kind has its own edge ``type``. + Two entry points: * ``bpmn_object_to_json(model: BPMNModel) -> dict`` — converts a metamodel object @@ -18,7 +24,7 @@ side-channel. * **Layout fallback.** When ``layout`` is missing / partial (a freshly-built model, or one loaded from BUML code that didn't emit layout), a deterministic grid layout fills - the gaps; flow paths reuse ``services.utils.layout_calculator``. + the gaps. * **Deterministic walk.** Set members are walked in ``timestamp`` order via ``besser.utilities.sort_by_timestamp`` so the export is reproducible (BPMN names are not unique — sorting by name is not an option). @@ -64,95 +70,79 @@ Transaction, ) from besser.utilities.utils import sort_by_timestamp -from besser.utilities.web_modeling_editor.backend.constants.constants import ( - BPMN_DIAGRAM_TYPE, - BPMN_RELATIONSHIP_TYPE, -) +from besser.utilities.web_modeling_editor.backend.constants.constants import BPMN_DIAGRAM_TYPE from besser.utilities.web_modeling_editor.backend.services.converters.bpmn_event_mapping import ( serialise_event_type, ) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._node_builders import ( + envelope_size, make_edge, make_node, make_positions_parent_relative, points_from_layout, +) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import element_id_taker from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._safe_buml_loader import ( safe_load_buml, ) from besser.utilities.web_modeling_editor.backend.services.exceptions import ConversionError -from besser.utilities.web_modeling_editor.backend.services.utils import ( - calculate_connection_points, - calculate_path_points, - calculate_relationship_bounds, - determine_connection_direction, -) logger = logging.getLogger(__name__) -# --------------------------------------------------------------------------- -# WME element-type and default-bounds tables -# --------------------------------------------------------------------------- -# Reverse of the processor's dispatch — every concrete metamodel type that maps to a -# distinct WME ``elements[id]["type"]`` string. Lookup is by exact ``type(obj)`` (see -# ``_wme_type_for``), so entry order is irrelevant even for subclasses like Transaction -# (a SubProcess subclass); ``CallActivity`` is resolved separately in ``_wme_type_for``. +# Lookup is by exact ``type(obj)``, so the agentic subclasses need their own entries. _TYPE_FOR_CLASS = { - Task: "BPMNTask", - AgenticTask: "BPMNTask", - Transaction: "BPMNTransaction", - SubProcess: "BPMNSubprocess", - StartEvent: "BPMNStartEvent", - IntermediateEvent: "BPMNIntermediateEvent", - EndEvent: "BPMNEndEvent", - Gateway: "BPMNGateway", - AgenticGateway: "BPMNGateway", - DataObject: "BPMNDataObject", - DataStore: "BPMNDataStore", - TextAnnotation: "BPMNAnnotation", - Group: "BPMNGroup", - Lane: "BPMNSwimlane", - AgenticLane: "BPMNSwimlane", - Participant: "BPMNPool", + Task: "bpmnTask", + AgenticTask: "bpmnTask", + Transaction: "bpmnTransaction", + SubProcess: "bpmnSubprocess", + StartEvent: "bpmnStartEvent", + IntermediateEvent: "bpmnIntermediateEvent", + EndEvent: "bpmnEndEvent", + Gateway: "bpmnGateway", + AgenticGateway: "bpmnGateway", + DataObject: "bpmnDataObject", + DataStore: "bpmnDataStore", + TextAnnotation: "bpmnAnnotation", + Group: "bpmnGroup", + Lane: "bpmnSwimlane", + AgenticLane: "bpmnSwimlane", + Participant: "bpmnPool", } -# Default per-class bounds when ``layout["bounds"]`` is missing. -_DEFAULT_BOUNDS = { - "BPMNTask": {"width": 110, "height": 60}, - "BPMNSubprocess": {"width": 250, "height": 150}, - "BPMNTransaction": {"width": 250, "height": 150}, - "BPMNCallActivity": {"width": 110, "height": 60}, - "BPMNStartEvent": {"width": 40, "height": 40}, - "BPMNIntermediateEvent": {"width": 40, "height": 40}, - "BPMNEndEvent": {"width": 40, "height": 40}, - "BPMNGateway": {"width": 50, "height": 50}, - "BPMNDataObject": {"width": 40, "height": 50}, - "BPMNDataStore": {"width": 60, "height": 50}, - "BPMNAnnotation": {"width": 200, "height": 80}, - "BPMNGroup": {"width": 240, "height": 200}, - "BPMNSwimlane": {"width": 800, "height": 120}, - "BPMNPool": {"width": 800, "height": 240}, +_DEFAULT_SIZE = { + "bpmnTask": {"width": 110, "height": 60}, + "bpmnSubprocess": {"width": 250, "height": 150}, + "bpmnTransaction": {"width": 250, "height": 150}, + "bpmnCallActivity": {"width": 110, "height": 60}, + "bpmnStartEvent": {"width": 40, "height": 40}, + "bpmnIntermediateEvent": {"width": 40, "height": 40}, + "bpmnEndEvent": {"width": 40, "height": 40}, + "bpmnGateway": {"width": 50, "height": 50}, + "bpmnDataObject": {"width": 40, "height": 50}, + "bpmnDataStore": {"width": 60, "height": 50}, + "bpmnAnnotation": {"width": 200, "height": 80}, + "bpmnGroup": {"width": 240, "height": 200}, + "bpmnSwimlane": {"width": 800, "height": 120}, + "bpmnPool": {"width": 800, "height": 240}, } -_FLOW_TYPE_FOR_CLASS = { - SequenceFlow: "sequence", - MessageFlow: "message", - Association: "association", - DataAssociation: "data association", +_EDGE_TYPE_FOR_FLOW_CLASS = { + SequenceFlow: "BPMNSequenceFlow", + MessageFlow: "BPMNMessageFlow", + Association: "BPMNAssociationFlow", + DataAssociation: "BPMNDataAssociationFlow", } -# WME's BPMNTask / BPMNGateway / BPMNSwimlane always serialise these agentic -# fields with hard defaults when the element is not agentic. Mirror exactly so -# BESSER-emitted JSON matches WME's own JSON byte-for-byte on non-agentic -# elements. The values are taken from WME's `dev/bpmn` -# packages/editor/.../bpmn-{task,gateway,swimlane}.ts ``default*`` statics. -_WME_TASK_DEFAULTS = { +# Agentic fields emitted on every task / gateway / lane node, with these defaults +# when the element is not agentic (the editor's own defaults for the same fields). +_TASK_AGENTIC_DEFAULTS = { "isAgentic": False, "reflectionMode": "none", "trustScore": 0, } -_WME_GATEWAY_DEFAULTS = { +_GATEWAY_AGENTIC_DEFAULTS = { "isAgentic": False, "gatewayRole": "diverging", "trustScore": 0, } -_WME_LANE_DEFAULTS = { +_LANE_AGENTIC_DEFAULTS = { "isAgentic": False, "role": "solution", "trustScore": 0, @@ -161,29 +151,42 @@ def _wme_type_for(obj) -> str: - """Return the WME ``type`` string for a metamodel object.""" cls = type(obj) if cls.__name__ == "CallActivity": - return "BPMNCallActivity" + return "bpmnCallActivity" return _TYPE_FOR_CLASS.get(cls, "") -# --------------------------------------------------------------------------- -# bpmn_object_to_json -# --------------------------------------------------------------------------- +class _GridLayout: + """Deterministic per-class grid placement when layout['bounds'] is absent.""" -def bpmn_object_to_json(model: BPMNModel) -> dict: - """Convert a ``BPMNModel`` into a WME BPMN diagram JSON dict. + _ROW_FOR_TYPE = { + "bpmnPool": 0, "bpmnSwimlane": 1, + "bpmnStartEvent": 2, "bpmnTask": 2, "bpmnGateway": 2, + "bpmnCallActivity": 2, "bpmnIntermediateEvent": 2, "bpmnEndEvent": 2, + "bpmnSubprocess": 3, "bpmnTransaction": 3, + "bpmnDataObject": 4, "bpmnDataStore": 4, + "bpmnAnnotation": 5, "bpmnGroup": 5, + } - Args: - model: A ``BPMNModel`` metamodel instance. + def __init__(self): + self._x_for_row: dict = {} - Returns: - Dict in the standard Apollon BPMN envelope (``version``, ``type``, ``size``, - ``elements``, ``relationships``, ``interactive``, ``assessments``). - """ - elements: dict = {} - relationships: dict = {} + def next_bounds(self, wme_type: str) -> dict: + size = _DEFAULT_SIZE.get(wme_type, {"width": 100, "height": 60}) + row = self._ROW_FOR_TYPE.get(wme_type, 6) + x = self._x_for_row.get(row, 40) + y = 40 + row * 180 + self._x_for_row[row] = x + size["width"] + 40 + return {"x": x, "y": y, "width": size["width"], "height": size["height"]} + + +def bpmn_object_to_json(model: BPMNModel) -> dict: + """Convert a ``BPMNModel`` into a v4 WME BPMN diagram JSON dict + (``version``, ``type``, ``title``, ``size``, ``nodes``, ``edges``, + ``interactive``, ``assessments``).""" + nodes: list = [] + edges: list = [] # Per-call id map: stable round-trip ids (the element's id, else the layout stash); fresh uuids otherwise. id_map: dict = {} @@ -196,277 +199,203 @@ def id_for(obj) -> str: id_map[obj] = take_id(obj) return id_map[obj] - # --- 1. Pools (and their lanes) ---------------------------------------- if model.collaboration is not None: for participant in sort_by_timestamp(model.collaboration.participants): - _emit_pool(participant, elements, id_for, grid) + _emit_pool(participant, nodes, id_for, grid) - # --- 2. Pool-less Processes (no Participant) --------------------------- pooled_processes = ( {p.process for p in model.collaboration.participants if p.process is not None} - if model.collaboration is not None - else set() + if model.collaboration is not None else set() ) for process in sort_by_timestamp(model.processes): if process in pooled_processes: continue - _emit_process_contents( - process, owner_id=None, elements=elements, id_for=id_for, grid=grid, - ) + _emit_process_contents(process, parent_id=None, nodes=nodes, id_for=id_for, grid=grid) - # --- 3. Pool-ful Processes' contents ----------------------------------- if model.collaboration is not None: for participant in sort_by_timestamp(model.collaboration.participants): if participant.process is None: continue _emit_process_contents( - participant.process, - owner_id=id_for(participant), - elements=elements, - id_for=id_for, - grid=grid, + participant.process, parent_id=id_for(participant), + nodes=nodes, id_for=id_for, grid=grid, ) - # --- 4. Model-level data stores ---------------------------------------- for data_store in sort_by_timestamp(model.data_stores): - elements[id_for(data_store)] = _emit_node( - data_store, owner_id=None, id_for=id_for, grid=grid, - ) + node = _emit_node(data_store, parent_id=None, id_for=id_for, grid=grid) + if node: + nodes.append(node) + + # Stashed bounds are absolute; grid-fallback positions are already relative. + make_positions_parent_relative( + nodes, {node_id for obj, node_id in id_map.items() if (getattr(obj, "layout", None) or {}).get("bounds")}, + ) - # --- 5. Flows ---------------------------------------------------------- + emitted_ids = {node["id"] for node in nodes} for process in sort_by_timestamp(model.processes): for flow in sort_by_timestamp(process.sequence_flows): - _emit_flow(flow, relationships, elements, id_for) + _emit_flow(flow, edges, id_for, emitted_ids) for flow in sort_by_timestamp(process.associations): - _emit_flow(flow, relationships, elements, id_for) + _emit_flow(flow, edges, id_for, emitted_ids) for flow in sort_by_timestamp(process.data_associations): - _emit_flow(flow, relationships, elements, id_for) + _emit_flow(flow, edges, id_for, emitted_ids) # Sequence flows nested in SubProcesses for sub in _walk_subprocesses(model): for flow in sort_by_timestamp(sub.sequence_flows): - _emit_flow(flow, relationships, elements, id_for) + _emit_flow(flow, edges, id_for, emitted_ids) if model.collaboration is not None: for flow in sort_by_timestamp(model.collaboration.message_flows): - _emit_flow(flow, relationships, elements, id_for) - - # --- 6. Envelope ------------------------------------------------------- - size = _compute_envelope_size(elements) + _emit_flow(flow, edges, id_for, emitted_ids) return { - "version": "3.0.0", + "version": "4.0.0", "type": BPMN_DIAGRAM_TYPE, - "size": size, + "title": getattr(model, "name", "") or "", + "size": envelope_size(nodes), + "nodes": nodes, + "edges": edges, "interactive": {"elements": {}, "relationships": {}}, - "elements": elements, - "relationships": relationships, "assessments": {}, } -# --------------------------------------------------------------------------- -# Element emission helpers -# --------------------------------------------------------------------------- - - -def _emit_pool(participant: Participant, elements: dict, id_for, grid: "_GridLayout") -> None: - """Emit a pool (``BPMNPool``) and its lanes (``BPMNSwimlane``).""" - pool_id = id_for(participant) - elements[pool_id] = _emit_node(participant, owner_id=None, id_for=id_for, grid=grid) +def _emit_pool(participant: Participant, nodes: list, id_for, grid: "_GridLayout") -> None: + pool_node = _emit_node(participant, parent_id=None, id_for=id_for, grid=grid) + if pool_node: + nodes.append(pool_node) if participant.process is None: return + pool_id = id_for(participant) for lane in sort_by_timestamp(participant.process.lanes): - elements[id_for(lane)] = _emit_node( - lane, owner_id=pool_id, id_for=id_for, grid=grid, - ) - + lane_node = _emit_node(lane, parent_id=pool_id, id_for=id_for, grid=grid) + if lane_node: + nodes.append(lane_node) -def _emit_process_contents(process: Process, owner_id, elements: dict, - id_for, grid: "_GridLayout") -> None: - """Emit every child of ``process``: flow nodes (recursing into sub-processes), - artifacts, and data objects. - ``owner_id`` is the WME owner pointer for top-level children: the pool id when the - process is in a pool, ``None`` otherwise. Children inside a lane resolve their owner - to the lane id; children inside a sub-process resolve to the sub-process id. - """ +def _emit_process_contents(process: Process, parent_id, nodes: list, id_for, grid: "_GridLayout") -> None: for node in sort_by_timestamp(process.flow_nodes): - node_owner_id = id_for(node.lane) if node.lane is not None else owner_id - elements[id_for(node)] = _emit_node( - node, owner_id=node_owner_id, id_for=id_for, grid=grid, - ) + node_parent_id = id_for(node.lane) if node.lane is not None else parent_id + emitted = _emit_node(node, parent_id=node_parent_id, id_for=id_for, grid=grid) + if emitted: + nodes.append(emitted) if isinstance(node, SubProcess): - _emit_subprocess_children(node, elements, id_for, grid) + _emit_subprocess_children(node, nodes, id_for, grid) for artifact in sort_by_timestamp(process.artifacts): - elements[id_for(artifact)] = _emit_node( - artifact, owner_id=owner_id, id_for=id_for, grid=grid, - ) + emitted = _emit_node(artifact, parent_id=parent_id, id_for=id_for, grid=grid) + if emitted: + nodes.append(emitted) for data_object in sort_by_timestamp(process.data_objects): - elements[id_for(data_object)] = _emit_node( - data_object, owner_id=owner_id, id_for=id_for, grid=grid, - ) + emitted = _emit_node(data_object, parent_id=parent_id, id_for=id_for, grid=grid) + if emitted: + nodes.append(emitted) -def _emit_subprocess_children(sub: SubProcess, elements: dict, - id_for, grid: "_GridLayout") -> None: - """Recursively emit a sub-process's flow nodes (their owner is the sub-process).""" +def _emit_subprocess_children(sub: SubProcess, nodes: list, id_for, grid: "_GridLayout") -> None: sub_id = id_for(sub) for node in sort_by_timestamp(sub.flow_nodes): - elements[id_for(node)] = _emit_node( - node, owner_id=sub_id, id_for=id_for, grid=grid, - ) + emitted = _emit_node(node, parent_id=sub_id, id_for=id_for, grid=grid) + if emitted: + nodes.append(emitted) if isinstance(node, SubProcess): - _emit_subprocess_children(node, elements, id_for, grid) + _emit_subprocess_children(node, nodes, id_for, grid) -def _emit_node(obj, owner_id, id_for, grid: "_GridLayout") -> dict: - """Build one ``elements[id]`` entry for a metamodel object.""" +def _emit_node(obj, parent_id, id_for, grid: "_GridLayout"): wme_type = _wme_type_for(obj) if not wme_type: - # Should not happen — guard anyway. logger.warning("BPMN export: unknown metamodel class %s; skipping.", type(obj).__name__) - return {} + return None layout = obj.layout or {} bounds = layout.get("bounds") or grid.next_bounds(wme_type) - name = obj.name - if isinstance(obj, TextAnnotation): - # The metamodel keeps the body in `text` — WME stores it back in `name`. - name = obj.text - - entry: dict = { - "id": id_for(obj), - "name": name, - "type": wme_type, - "owner": owner_id, - "bounds": bounds, - } + name = obj.text if isinstance(obj, TextAnnotation) else obj.name + + data: dict = {"name": name} for style_key in ("fillColor", "strokeColor", "textColor", "highlight"): if style_key in layout: - entry[style_key] = layout[style_key] + data[style_key] = layout[style_key] - # Subtype attrs — only on the relevant types. if isinstance(obj, Task): - entry["taskType"] = obj.task_type.value + data["taskType"] = obj.task_type.value if isinstance(obj, Activity): - entry["marker"] = obj.loop_characteristics.value + data["marker"] = obj.loop_characteristics.value if isinstance(obj, Event): - entry["eventType"] = serialise_event_type(obj) + data["eventType"] = serialise_event_type(obj) if isinstance(obj, Gateway): - entry["gatewayType"] = obj.gateway_type.value + data["gatewayType"] = obj.gateway_type.value if isinstance(obj, Task): - entry.update(_WME_TASK_DEFAULTS) + data.update(_TASK_AGENTIC_DEFAULTS) if isinstance(obj, AgenticTask): - entry["isAgentic"] = True - entry["reflectionMode"] = obj.reflection_mode.value - entry["trustScore"] = obj.trust_score + data["isAgentic"] = True + data["reflectionMode"] = obj.reflection_mode.value + data["trustScore"] = obj.trust_score if obj.agent_diagram_ref is not None: - entry["agentDiagramRef"] = obj.agent_diagram_ref + data["agentDiagramRef"] = obj.agent_diagram_ref if obj.reflection_reviewer_lane_id is not None: - entry["reflectionReviewerLaneId"] = obj.reflection_reviewer_lane_id + data["reflectionReviewerLaneId"] = obj.reflection_reviewer_lane_id if isinstance(obj, Gateway): - entry.update(_WME_GATEWAY_DEFAULTS) + data.update(_GATEWAY_AGENTIC_DEFAULTS) if isinstance(obj, AgenticGateway): - entry["isAgentic"] = True - entry["gatewayRole"] = obj.gateway_role.value - entry["trustScore"] = obj.trust_score + data["isAgentic"] = True + data["gatewayRole"] = obj.gateway_role.value + data["trustScore"] = obj.trust_score if obj.governance_dsl is not None: - entry["governanceDsl"] = obj.governance_dsl + data["governanceDsl"] = obj.governance_dsl if isinstance(obj, Lane): - entry.update(_WME_LANE_DEFAULTS) + data.update(_LANE_AGENTIC_DEFAULTS) if isinstance(obj, AgenticLane): - entry["isAgentic"] = True - entry["role"] = obj.role.value - entry["trustScore"] = obj.trust_score - entry["multiplicity"] = obj.swarm_size + data["isAgentic"] = True + data["role"] = obj.role.value + data["trustScore"] = obj.trust_score + data["multiplicity"] = obj.swarm_size if obj.agent_diagram_ref is not None: - entry["agentDiagramRef"] = obj.agent_diagram_ref - - return entry + data["agentDiagramRef"] = obj.agent_diagram_ref -# --------------------------------------------------------------------------- -# Flow emission helpers -# --------------------------------------------------------------------------- + return make_node( + node_id=id_for(obj), type_=wme_type, data=data, + position={"x": bounds["x"], "y": bounds["y"]}, + parent_id=parent_id, width=bounds["width"], height=bounds["height"], + ) -def _emit_flow(flow: BPMNConnectingObject, relationships: dict, - elements: dict, id_for) -> None: - """Build one ``relationships[id]`` entry for a flow.""" - flow_type = _FLOW_TYPE_FOR_CLASS.get(type(flow)) - if flow_type is None: - logger.warning( - "BPMN export: unknown connecting object %s; skipping.", type(flow).__name__, - ) +def _emit_flow(flow: "BPMNConnectingObject", edges: list, id_for, emitted_ids: set) -> None: + edge_type = _EDGE_TYPE_FOR_FLOW_CLASS.get(type(flow)) + if edge_type is None: + logger.warning("BPMN export: unknown connecting object %s; skipping.", type(flow).__name__) return source_id = id_for(flow.source) target_id = id_for(flow.target) - source_entry = elements.get(source_id) - target_entry = elements.get(target_id) - if source_entry is None or target_entry is None: + if source_id not in emitted_ids or target_id not in emitted_ids: # Endpoint wasn't emitted (defensive — happens only on a malformed model). logger.warning( - "BPMN flow '%s' references an endpoint that was not emitted; skipping.", - flow.name, + "BPMN flow '%s' references an endpoint that was not emitted; skipping.", flow.name, ) return layout = flow.layout or {} - source_dir, target_dir = _resolve_directions(layout, source_entry, target_entry) - source_point = calculate_connection_points(source_entry["bounds"], source_dir) - target_point = calculate_connection_points(target_entry["bounds"], target_dir) - path = layout.get("path") or calculate_path_points( - source_point, target_point, source_dir, target_dir, - ) - bounds = layout.get("bounds") or calculate_relationship_bounds(path) - - entry: dict = { - "id": id_for(flow), + edge_data: dict = { "name": flow.name, - "type": BPMN_RELATIONSHIP_TYPE, - "owner": layout.get("owner"), - "bounds": bounds, - "path": path, - "source": { - "direction": source_dir, - "element": source_id, - "bounds": {"x": source_point["x"], "y": source_point["y"], "width": 0, "height": 0}, - }, - "target": { - "direction": target_dir, - "element": target_id, - "bounds": {"x": target_point["x"], "y": target_point["y"], "width": 0, "height": 0}, - }, + "label": flow.name, # BPMNDiagramEdge.tsx reads data.label + "points": points_from_layout(layout), "isManuallyLayouted": layout.get("isManuallyLayouted", False), - "flowType": flow_type, } - if isinstance(flow, SequenceFlow): - entry["isDefault"] = flow.is_default - - relationships[id_for(flow)] = entry - + if isinstance(flow, SequenceFlow) and flow.is_default: + edge_data["isDefault"] = True -def _resolve_directions(layout: dict, source_entry: dict, target_entry: dict): - """Pick connection directions for an emitted flow. - - Prefers the directions stashed in ``layout`` so a round-tripped flow keeps the same - connection sides; falls back to ``determine_connection_direction`` from the bounds. - """ - source_dir = layout.get("source_direction") - target_dir = layout.get("target_direction") - if source_dir and target_dir: - return source_dir, target_dir - return determine_connection_direction(source_entry["bounds"], target_entry["bounds"]) - -# --------------------------------------------------------------------------- -# Misc helpers -# --------------------------------------------------------------------------- + edges.append(make_edge( + edge_id=id_for(flow), source=source_id, target=target_id, + type_=edge_type, data=edge_data, + source_handle=layout.get("source_direction") or "right", + target_handle=layout.get("target_direction") or "left", + )) def _walk_subprocesses(model: BPMNModel): @@ -476,116 +405,31 @@ def _recurse(container): if isinstance(node, SubProcess): yield node yield from _recurse(node) - for process in model.processes: yield from _recurse(process) -def _compute_envelope_size(elements: dict) -> dict: - """Bounding box of all element bounds, with a sensible minimum.""" - if not elements: - return {"width": 800, "height": 600} - max_x = 0 - max_y = 0 - for entry in elements.values(): - bounds = entry.get("bounds") or {} - right = (bounds.get("x") or 0) + (bounds.get("width") or 0) - bottom = (bounds.get("y") or 0) + (bounds.get("height") or 0) - if right > max_x: - max_x = right - if bottom > max_y: - max_y = bottom - return {"width": max(int(max_x) + 40, 800), "height": max(int(max_y) + 40, 600)} - -# --------------------------------------------------------------------------- -# Grid layout (deterministic fallback when layout is missing) -# --------------------------------------------------------------------------- - - -class _GridLayout: - """Deterministic per-class grid placement used only when ``layout["bounds"]`` is - absent. Each WME type advances its own row so nodes of different sizes don't overlap. - """ - - _ROW_FOR_TYPE = { - "BPMNPool": 0, - "BPMNSwimlane": 1, - "BPMNStartEvent": 2, - "BPMNTask": 2, - "BPMNGateway": 2, - "BPMNCallActivity": 2, - "BPMNIntermediateEvent": 2, - "BPMNEndEvent": 2, - "BPMNSubprocess": 3, - "BPMNTransaction": 3, - "BPMNDataObject": 4, - "BPMNDataStore": 4, - "BPMNAnnotation": 5, - "BPMNGroup": 5, - } - - def __init__(self): - self._x_for_row: dict = {} - - def next_bounds(self, wme_type: str) -> dict: - size = _DEFAULT_BOUNDS.get(wme_type, {"width": 100, "height": 60}) - row = self._ROW_FOR_TYPE.get(wme_type, 6) - x = self._x_for_row.get(row, 40) - y = 40 + row * 180 - self._x_for_row[row] = x + size["width"] + 40 - return {"x": x, "y": y, "width": size["width"], "height": size["height"]} - -# --------------------------------------------------------------------------- -# bpmn_buml_to_json — BUML .py source string → WME JSON -# --------------------------------------------------------------------------- - - def bpmn_buml_to_json(content: str) -> dict: - """Convert a BPMN BUML ``.py`` source string into a WME BPMN diagram JSON dict. - - Loads ``content`` through ``safe_load_buml`` (AST allowlist), locates the resulting ``BPMNModel``, and - delegates to :func:`bpmn_object_to_json`. The ``.py`` files emitted by - ``besser.utilities.buml_code_builder.bpmn_model_builder.bpmn_model_to_code`` are - exactly what this wrapper expects. - - Args: - content: BPMN BUML Python source code as a string. + """Convert a BPMN BUML ``.py`` source string into a v4 WME BPMN diagram JSON dict. - Returns: - A WME BPMN diagram JSON dict (the standard Apollon envelope). + Loads ``content`` through ``safe_load_buml`` (AST allowlist — no raw ``exec``), + locates the resulting ``BPMNModel``, and delegates to :func:`bpmn_object_to_json`. Raises: ConversionError: if the source fails to parse / execute, or if no ``BPMNModel`` instance is produced. """ allowed_names = { - "BPMNModel": BPMNModel, - "Process": Process, - "Collaboration": Collaboration, - "Participant": Participant, - "Task": Task, - "TaskType": TaskType, - "LoopCharacteristics": LoopCharacteristics, - "SubProcess": SubProcess, - "Transaction": Transaction, - "CallActivity": CallActivity, - "StartEvent": StartEvent, - "IntermediateEvent": IntermediateEvent, - "EndEvent": EndEvent, - "EventDirection": EventDirection, - "EventDefinitionType": EventDefinitionType, - "Gateway": Gateway, - "GatewayType": GatewayType, - "SequenceFlow": SequenceFlow, - "MessageFlow": MessageFlow, - "Association": Association, - "DataAssociation": DataAssociation, - "DataObject": DataObject, - "DataStore": DataStore, - "Lane": Lane, - "Group": Group, - "TextAnnotation": TextAnnotation, - "set": set, + "BPMNModel": BPMNModel, "Process": Process, "Collaboration": Collaboration, + "Participant": Participant, "Task": Task, "TaskType": TaskType, + "LoopCharacteristics": LoopCharacteristics, "SubProcess": SubProcess, + "Transaction": Transaction, "CallActivity": CallActivity, "StartEvent": StartEvent, + "IntermediateEvent": IntermediateEvent, "EndEvent": EndEvent, + "EventDirection": EventDirection, "EventDefinitionType": EventDefinitionType, + "Gateway": Gateway, "GatewayType": GatewayType, "SequenceFlow": SequenceFlow, + "MessageFlow": MessageFlow, "Association": Association, "DataAssociation": DataAssociation, + "DataObject": DataObject, "DataStore": DataStore, "Lane": Lane, "Group": Group, + "TextAnnotation": TextAnnotation, "set": set, "Project": lambda *args, **kwargs: None, "AgenticTask": AgenticTask, "AgenticGateway": AgenticGateway, @@ -610,14 +454,13 @@ def bpmn_buml_to_json(content: str) -> dict: if model is None: raise ConversionError( "BPMN BUML file produced no BPMNModel — expected a top-level variable " - "(`bpmn_model = BPMNModel(...)` is the convention emitted by " - "`bpmn_model_to_code`)." + "(`bpmn_model = BPMNModel(...)` is the convention emitted by `bpmn_model_to_code`)." ) return bpmn_object_to_json(model) def _find_bpmn_model(namespace: dict): - """Return the ``BPMNModel`` from the exec'd namespace, preferring ``bpmn_model``.""" + """Return the ``BPMNModel`` from the loaded namespace, preferring ``bpmn_model``.""" candidate = namespace.get("bpmn_model") if isinstance(candidate, BPMNModel): return candidate diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/class_diagram_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/class_diagram_converter.py index e7fdab6a5..7799b39c0 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/class_diagram_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/class_diagram_converter.py @@ -1,31 +1,47 @@ """ Domain model conversion from BUML to JSON format. + +Emits the v4 wire shape (``{nodes, edges}``) directly — see +``docs/source/migrations/uml-v4-shape.md``. There is no v3-shape +intermediate; every node is built via ``make_node`` and every edge via +``make_edge``. """ import logging +import re import uuid from besser.BUML.metamodel.structural import ( Class, Property, Method, Parameter as StructuralParameter, DomainModel, PrimitiveDataType, Enumeration, EnumerationLiteral, BinaryAssociation, Generalization, Multiplicity, UNLIMITED_MAX_MULTIPLICITY, Constraint, AssociationClass, Metadata, - MethodImplementationType + MethodImplementationType, +) + +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._node_builders import ( + make_node, make_edge, grid_layout, snap_up, ) # Layout constants for auto-grid positioning LAYOUT_GRID_WIDTH = 1200 LAYOUT_GRID_HEIGHT = 800 -LAYOUT_X_SPACING = 300 -LAYOUT_Y_SPACING = 200 +LAYOUT_ORIGIN = (-600, -300) LAYOUT_MAX_COLUMNS = 3 +LAYOUT_GAP_Y = 100 + +# Mirrors the editor's class node metrics (``LAYOUT`` in the library's +# constants.ts and ``calculateMinWidth`` / ``calculateMinHeight``). +CLASS_HEADER_HEIGHT = 40 +CLASS_HEADER_HEIGHT_WITH_STEREOTYPE = 50 +CLASS_ROW_HEIGHT = 30 +CLASS_PADDING = 10 +CLASS_MIN_WIDTH = 160 +CHAR_WIDTH_PX = 9 # rough average glyph width of the editor's 16px Inter +_VISIBILITY_SYMBOLS = {"public": "+", "private": "-", "protected": "#", "package": "~"} logger = logging.getLogger(__name__) from besser.utilities.web_modeling_editor.backend.constants.constants import ( - VISIBILITY_MAP, RELATIONSHIP_TYPES -) -from besser.utilities.web_modeling_editor.backend.services.utils import ( - determine_connection_direction, calculate_connection_points, - calculate_path_points, calculate_relationship_bounds + RELATIONSHIP_TYPES, ) from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._safe_buml_loader import ( SAFE_DATETIME_MODULE, @@ -40,17 +56,16 @@ ) -def _set_timestamp(target: dict, element) -> dict: - """Record ``element.timestamp`` on a JSON dict as an ISO 8601 ``timestamp``. +def _set_timestamp(target: dict, element, key: str = "timestamp") -> dict: + """Record ``element.timestamp`` on ``target[key]`` as an ISO 8601 string. - Only an explicit timestamp is written (see ``Element.has_explicit_timestamp``); - one that defaulted to the creation time is left out, so converting the same - model twice gives the same JSON. ``json_to_buml`` falls back to the creation - time when the field is absent. + Only an explicit timestamp is written (see ``Element.has_explicit_timestamp``), + so converting the same model twice gives the same JSON. ``json_to_buml`` + falls back to the creation time when the field is absent. """ iso = explicit_timestamp_iso(element) if iso is not None: - target["timestamp"] = iso + target[key] = iso return target @@ -139,21 +154,25 @@ def parse_buml_content(content: str, warnings: list[str] | None = None) -> Domai if warnings is None: warnings = [] try: - # If caller already passed a DomainModel instance, return it directly. if isinstance(content, DomainModel): return content # Allowlist of names that may appear in the BUML source. Everything - # else is rejected by the safe loader. + # else is rejected by the safe AST-based loader (which also skips a + # trailing ``if __name__ == "__main__":`` block). allowed_names = { **structural_allowed_names(), "BinaryAssociation": _repairing_binary_association(warnings), } - # Ensure we have a string before preprocessing if not isinstance(content, str): raise TypeError(f"Expected B-UML content as str or DomainModel, got {type(content)!r}") + # A class named ``Project`` is bound by the script itself; the stub + # would make the loader treat it as a shared object it may not modify. + if re.search(r"^Project\s*(?::[^=\n]*)?=(?!=)", content, re.MULTILINE): + del allowed_names["Project"] + # A generator run or a print at the end of the file is skipped by the # loader (reported in ``warnings``); only the model is loaded. local_vars = safe_load_buml(content, allowed_names, warnings=warnings) @@ -181,11 +200,19 @@ def parse_buml_content(content: str, warnings: list[str] | None = None) -> Domai elements += [*built.types, *built.associations, *built.generalizations, *built.constraints] domain_model = DomainModel(domain_name, timestamp=domain_timestamp) + # Method pre/post contracts are Constraint variables too, but they + # belong to their method, not to the model's invariants. + method_contracts = { + id(c) + for element in elements if isinstance(element, Class) + for method in element.methods + for c in list(method.pre) + list(method.post) + } # First pass: Add all classes and enumerations for element in elements: if isinstance(element, (Class, Enumeration)): domain_model.types.add(element) - elif isinstance(element, Constraint): + elif isinstance(element, Constraint) and id(element) not in method_contracts: domain_model.constraints.add(element) # Second pass: Add associations and generalizations @@ -202,688 +229,459 @@ def parse_buml_content(content: str, warnings: list[str] | None = None) -> Domai raise ValueError(f"Failed to parse B-UML content: {str(e)}") -def class_buml_to_json(domain_model): - """Convert a B-UML DomainModel object to JSON format matching the frontend structure.""" - elements = {} - relationships = {} - # Retrieve method diagram reference mapping (populated by json_to_buml round-trip). - # Keyed by (class_name, method_name) -> {"stateMachineId": ..., "quantumCircuitId": ..., "neuralNetworkId": ...} - method_diagram_refs = getattr(domain_model, 'method_diagram_refs', {}) - # Retrieve saved layout positions for round-trip fidelity (populated by json_to_buml). - # Keyed by element name (classes/enums) or composite key (relationships). - layout_positions = getattr(domain_model, '_layout_positions', {}) - # Default diagram size - default_size = { - "width": LAYOUT_GRID_WIDTH, - "height": LAYOUT_GRID_HEIGHT, - } +def _multiplicity_str(prop: Property) -> str: + """Render a property's multiplicity as its UML association-end label.""" + return format_multiplicity_label(prop.multiplicity) + - # Grid layout configuration - grid_size = { - "x_spacing": LAYOUT_X_SPACING, - "y_spacing": LAYOUT_Y_SPACING, - "max_columns": LAYOUT_MAX_COLUMNS, +def _json_safe_default(value): + """Coerce a default value to a JSON-serialisable form. + + ``default_value`` may be an ``EnumerationLiteral`` (or other metamodel + object); use its ``name`` (else its string form) so the diagram JSON can + be serialised when sent to the render service. Primitives pass through. + """ + if isinstance(value, (str, int, float, bool)): + return value + return getattr(value, "name", None) or str(value) + + +def _attr_row(attr: Property, take_id) -> dict: + """Build a v4 ``ClassifierMember`` row for an attribute.""" + attr_type = attr.type.name if hasattr(attr.type, "name") else str(attr.type) + row = { + "id": take_id(attr), + "name": attr.name, + "attributeType": attr_type, + "visibility": attr.visibility, + "isOptional": attr.is_optional, + "isId": attr.is_id, + "isExternalId": attr.is_external_id, + "isDerived": attr.is_derived, } + if attr.default_value is not None: + row["defaultValue"] = _json_safe_default(attr.default_value) + return _set_timestamp(row, attr) + - # Track position - current_column = 0 - current_row = 0 +def _method_row(method: Method, type_obj: Class, method_diagram_refs: dict, take_id) -> dict: + """Build a v4 ``ClassifierMember`` row for a method. - # Track comments to create - comments_to_create = [] # [(comment_text, linked_class_id)] + Emits the canonical inspector-authored shape (``ClassNodeElement`` in + ``packages/library/lib/types/nodes/NodeProps.ts``): a *bare* ``name``, + structured ``parameters`` rows, and the return type on ``returnType`` + mirrored onto ``attributeType`` (``any`` when absent) — exactly what + the frontend's add-method inspector writes, so the canvas renderer + (``formatDisplayName``) never double-decorates a fused signature. + """ + return_type = None + if hasattr(method, "type") and method.type: + return_type = method.type.name if hasattr(method.type, "name") else str(method.type) + + structured_parameters: list = [] + for param in method.parameters: + param_type = param.type.name if hasattr(param.type, "name") else str(param.type) + param_row: dict = { + "id": str(uuid.uuid4()), + "name": param.name, + "parameterType": param_type, + } + if hasattr(param, "default_value") and param.default_value is not None: + param_row["defaultValue"] = _json_safe_default(param.default_value) + structured_parameters.append(param_row) + + row: dict = { + "id": take_id(method), + "name": method.name, + "visibility": method.visibility, + "attributeType": return_type or "any", + "returnType": return_type or "any", + "parameters": structured_parameters, + } + + if hasattr(method, "code") and method.code: + row["code"] = method.code + + if hasattr(method, "implementation_type") and method.implementation_type: + impl_type_map = { + MethodImplementationType.NONE: "none", + MethodImplementationType.CODE: "code", + MethodImplementationType.BAL: "bal", + MethodImplementationType.STATE_MACHINE: "state_machine", + MethodImplementationType.QUANTUM_CIRCUIT: "quantum_circuit", + MethodImplementationType.NEURAL_NETWORK: "neural_network", + } + impl_type = method.implementation_type + if isinstance(impl_type, str): + normalized_impl_type = impl_type.strip() + if normalized_impl_type.startswith("MethodImplementationType."): + normalized_impl_type = normalized_impl_type.split(".", maxsplit=1)[1] + mapped = normalized_impl_type.lower() + if mapped in {"none", "code", "bal", "state_machine", "quantum_circuit", "neural_network"}: + row["implementationType"] = mapped + else: + row["implementationType"] = "none" + else: + row["implementationType"] = impl_type_map.get(impl_type, "none") + + refs = method_diagram_refs.get((type_obj.name, method.name), {}) + state_machine_id = refs.get("stateMachineId") or None + if not state_machine_id and hasattr(method, "state_machine") and method.state_machine: + state_machine_id = method.state_machine.name + if state_machine_id: + row["stateMachineId"] = state_machine_id + quantum_circuit_id = refs.get("quantumCircuitId") or None + if not quantum_circuit_id and hasattr(method, "quantum_circuit") and method.quantum_circuit: + quantum_circuit_id = method.quantum_circuit.name + if quantum_circuit_id: + row["quantumCircuitId"] = quantum_circuit_id + neural_network_id = refs.get("neuralNetworkId") or None + if not neural_network_id and getattr(method, "neural_network", None): + # Without a saved diagram id, reference the network by name + # (``method_nn_linker`` resolves ids and titles alike). + neural_network_id = method.neural_network.name + if neural_network_id: + row["neuralNetworkId"] = neural_network_id + + if not row.get("implementationType"): + row.pop("implementationType", None) + if not row.get("stateMachineId"): + row.pop("stateMachineId", None) + if not row.get("quantumCircuitId"): + row.pop("quantumCircuitId", None) + if not row.get("neuralNetworkId"): + row.pop("neuralNetworkId", None) + return _set_timestamp(row, method) + + +def _member_label(row: dict, is_method: bool, stereotype) -> str: + """Approximate the canvas label of a member row (``formatDisplayName``).""" + if stereotype == "Enumeration": + return row.get("name", "") + vis = _VISIBILITY_SYMBOLS.get(row.get("visibility") or "public", "+") + if is_method: + params = ", ".join(f"{p['name']}: {p.get('parameterType', '')}" for p in row.get("parameters") or []) + return f"{vis} {row.get('name', '')}({params}): {row.get('returnType', '')}" + label = f"{vis} {row.get('name', '')}: {row.get('attributeType', '')}" + if row.get("defaultValue") not in (None, ""): + label += f" = {row['defaultValue']}" + if row.get("isId"): + label += " {id}" + return label + + +def _class_node_size(name: str, stereotype, attribute_rows: list, method_rows: list) -> tuple: + """Content-based (width, height) of a class node, as the editor sizes it.""" + header = CLASS_HEADER_HEIGHT_WITH_STEREOTYPE if stereotype else CLASS_HEADER_HEIGHT + labels = [name, f"\u00ab{stereotype}\u00bb" if stereotype else ""] + labels += [_member_label(r, False, stereotype) for r in attribute_rows] + labels += [_member_label(r, True, stereotype) for r in method_rows] + text_width = max(len(label) for label in labels) * CHAR_WIDTH_PX + width = max(CLASS_MIN_WIDTH, snap_up(text_width + 2 * CLASS_PADDING)) + height = snap_up(header + CLASS_ROW_HEIGHT * (len(attribute_rows) + len(method_rows))) + return width, height - def get_position(): - nonlocal current_column, current_row - x = -600 + (current_column * grid_size["x_spacing"]) - y = -300 + (current_row * grid_size["y_spacing"]) - # Move to next position - current_column += 1 - if current_column >= grid_size["max_columns"]: - current_column = 0 - current_row += 1 +def class_buml_to_json(domain_model): + """Convert a B-UML DomainModel to the v4 ``{nodes, edges}`` wire shape.""" + nodes: list = [] + edges: list = [] + method_diagram_refs = getattr(domain_model, 'method_diagram_refs', {}) + layout_positions = getattr(domain_model, '_layout_positions', {}) - return x, y + # Nodes without a saved position; placed on a size-aware grid at the end. + auto_placed: list = [] - # First pass: Create all class and enumeration elements - class_id_map = {} # Store mapping between Class objects and their IDs + class_id_map: dict = {} # type_obj -> node id + # Editor node ids of the classes (from the JSON or a project .py import), + # so cross-diagram references to them stay valid. + known_ids = {cls.name: wid for wid, cls in (getattr(domain_model, "_wme_class_index", None) or {}).items()} + # Element ids: the element's own id while valid and unused, else a fresh uuid. take_id = element_id_taker() - # Sort types/constraints by name for deterministic output across runs. + # Emit class / abstract / interface / enumeration nodes. for type_obj in sorted( - (t for t in domain_model.types | domain_model.constraints if isinstance(t, (Class, Enumeration, Constraint))), + (t for t in domain_model.types if isinstance(t, (Class, Enumeration))), key=lambda t: t.name, ): - # Reuse the element's id (from the editor JSON); mint one if absent. - element_id = take_id(type_obj) - class_id_map[type_obj] = element_id - - # Use saved layout position if available, otherwise fall back to grid layout - saved_bounds = layout_positions.get(type_layout_key(type_obj)) - if saved_bounds: - x = saved_bounds["x"] - y = saved_bounds["y"] - saved_width = saved_bounds.get("width", 160) - saved_height = saved_bounds.get("height", 100) - else: - x, y = get_position() - saved_width = None - saved_height = None - - # Initialize lists for attributes and methods IDs - attribute_ids = [] - method_ids = [] - - # Header height must mirror the editor's UMLClassifier renderer - # (stereotypeHeaderHeight=50, nonStereotypeHeaderHeight=40) so ELK - # auto-layout and the headless SVG renderer agree on box geometry. - # Enumerations and abstract classes carry a «stereotype» line, so - # their header is one row taller and members start lower. - is_stereotyped = isinstance(type_obj, Enumeration) or ( - isinstance(type_obj, Class) and getattr(type_obj, "is_abstract", False) - ) - header_height = 50 if is_stereotyped else 40 - - # Process attributes/literals - y_offset = y + header_height # Members start below the header - if isinstance(type_obj, Class): - for attr in sorted(type_obj.attributes, key=lambda a: a.name): - attr_id = take_id(attr) - attr_type = ( - attr.type.name if hasattr(attr.type, "name") else str(attr.type) - ) - - attr_element = { - "id": attr_id, - "name": attr.name, - "type": "ClassAttribute", - "owner": element_id, - "bounds": { - "x": x + 0.5, - "y": y_offset, - "width": 159, - "height": 30, - }, - "visibility": attr.visibility, - "attributeType": attr_type, - "isOptional": attr.is_optional, - "isId": attr.is_id, - "isExternalId": attr.is_external_id, - "isDerived": attr.is_derived, - } - if attr.default_value is not None: - # default_value may be an EnumerationLiteral (or other - # metamodel object); coerce it to a JSON-serialisable - # value — its name, else its string form — so the diagram - # JSON can be serialised when sent to the render service. - default_value = attr.default_value - if not isinstance(default_value, (str, int, float, bool)): - default_value = getattr(default_value, "name", None) or str(default_value) - attr_element["defaultValue"] = default_value - _set_timestamp(attr_element, attr) - elements[attr_id] = attr_element - attribute_ids.append(attr_id) - y_offset += 30 - - # Process methods - for method in sorted(type_obj.methods, key=lambda m: m.name): - method_id = take_id(method) - visibility_symbol = next( - k for k, v in VISIBILITY_MAP.items() if v == method.visibility - ) - - # Build method signature with parameters and return type - param_str = [] - for param in method.parameters: - param_type = ( - param.type.name - if hasattr(param.type, "name") - else str(param.type) - ) - param_signature = f"{param.name}: {param_type}" - if ( - hasattr(param, "default_value") - and param.default_value is not None - ): - param_signature += f" = {param.default_value}" - param_str.append(param_signature) - - # Build complete method signature - method_signature = ( - f"{visibility_symbol} {method.name}({', '.join(param_str)})" - ) - if hasattr(method, "type") and method.type: - return_type = ( - method.type.name - if hasattr(method.type, "name") - else str(method.type) - ) - method_signature += f": {return_type}" - - method_element = { - "id": method_id, - "name": method_signature, - "type": "ClassMethod", - "owner": element_id, - "bounds": { - "x": x + 0.5, - "y": y_offset, - "width": 159, - "height": 30, - }, - } - - # Add code attribute if it exists and is not empty - if hasattr(method, "code") and method.code: - method_element["code"] = method.code - - # Add implementation type and diagram references - if hasattr(method, "implementation_type") and method.implementation_type: - impl_type_map = { - MethodImplementationType.NONE: "none", - MethodImplementationType.CODE: "code", - MethodImplementationType.BAL: "bal", - MethodImplementationType.STATE_MACHINE: "state_machine", - MethodImplementationType.QUANTUM_CIRCUIT: "quantum_circuit", - MethodImplementationType.NEURAL_NETWORK: "neural_network", - } - impl_type_str_map = { - "none": "none", - "code": "code", - "bal": "bal", - "state_machine": "state_machine", - "quantum_circuit": "quantum_circuit", - "neural_network": "neural_network", - } - impl_type = method.implementation_type - if isinstance(impl_type, str): - normalized_impl_type = impl_type.strip() - if normalized_impl_type.startswith("MethodImplementationType."): - normalized_impl_type = normalized_impl_type.split(".", maxsplit=1)[1] - method_element["implementationType"] = impl_type_str_map.get( - normalized_impl_type.lower(), "none" - ) - else: - method_element["implementationType"] = impl_type_map.get(impl_type, "none") - - # Add state machine reference if present. - # First check the method_diagram_refs mapping (populated during - # json_to_buml conversion), then fall back to actual object references. - refs = method_diagram_refs.get((type_obj.name, method.name), {}) - state_machine_id = refs.get("stateMachineId") or None - if not state_machine_id and hasattr(method, "state_machine") and method.state_machine: - # If we have an actual state machine object, use its name as ID - state_machine_id = method.state_machine.name - if state_machine_id: - method_element["stateMachineId"] = state_machine_id - - quantum_circuit_id = refs.get("quantumCircuitId") or None - if not quantum_circuit_id and hasattr(method, "quantum_circuit") and method.quantum_circuit: - # If we have an actual quantum circuit object, use its name as ID - quantum_circuit_id = method.quantum_circuit.name - if quantum_circuit_id: - method_element["quantumCircuitId"] = quantum_circuit_id - - neural_network_id = refs.get("neuralNetworkId") or None - if not neural_network_id and getattr(method, "neural_network", None): - # If we have an actual neural network object, use its name as ID - neural_network_id = method.neural_network.name - if neural_network_id: - method_element["neuralNetworkId"] = neural_network_id - - _set_timestamp(method_element, method) - elements[method_id] = method_element - method_ids.append(method_id) - y_offset += 30 - - elif isinstance(type_obj, Enumeration): - # Use preserved insertion order if available (from JSON round-trip), - # otherwise fall back to alphabetical sort for deterministic output. - ordered_literals = getattr(type_obj, '_ordered_literals', None) - if ordered_literals is not None: - literals_iter = ordered_literals - else: - literals_iter = sorted(type_obj.literals, key=lambda lit: lit.name) - for literal in literals_iter: - literal_id = take_id(literal) - elements[literal_id] = _set_timestamp({ - "id": literal_id, - "name": literal.name, - "type": "ClassAttribute", # We use ClassAttribute type for literals - "owner": element_id, - "bounds": { - "x": x + 0.5, - "y": y_offset, - "width": 159, - "height": 30, - }, - }, literal) - attribute_ids.append(literal_id) - y_offset += 30 - - # Create the element. Box height mirrors the renderer: header plus - # one 30px row per attribute/method (see UMLClassifier.render). OCL - # constraint boxes are not classifiers, so keep their legacy sizing. - member_count = len(attribute_ids) + len(method_ids) - if isinstance(type_obj, Constraint): - computed_height = max(100, 30 * (member_count + 1)) + node_id = ( + take_id(type_obj) if getattr(type_obj, "id", None) + else known_ids.get(type_obj.name) or take_id(type_obj) + ) + class_id_map[type_obj] = node_id + + saved_bounds = layout_positions.get(type_layout_key(type_obj)) + + attribute_rows: list = [] + method_rows: list = [] + + if isinstance(type_obj, Class): + # The frontend compares stereotypes case-sensitively against + # the capitalized canonical forms ('Abstract' / 'Interface' / + # 'Enumeration'); the processor lowercases on read, so the + # capitalized emit is backward-safe. + stereotype = "Abstract" if type_obj.is_abstract else None + for attr in sorted(type_obj.attributes, key=lambda a: a.name): + attribute_rows.append(_attr_row(attr, take_id)) + for method in sorted(type_obj.methods, key=lambda m: m.name): + method_rows.append(_method_row(method, type_obj, method_diagram_refs, take_id)) + else: + stereotype = "Enumeration" + ordered_literals = getattr(type_obj, '_ordered_literals', None) + if ordered_literals is not None: + literals_iter = ordered_literals else: - computed_height = header_height + 30 * member_count - element_data = { - "id": element_id, - "name": type_obj.name, - "type": ( - "Enumeration" - if isinstance(type_obj, Enumeration) - else ( - "ClassOCLConstraint" - if isinstance(type_obj, Constraint) - else "AbstractClass" if type_obj.is_abstract else "Class" - ) - ), - "owner": None, - "bounds": { - "x": x, - "y": y, - "width": saved_width if saved_width is not None else 160, - "height": saved_height if saved_height is not None else computed_height, - }, - **( - { - "attributes": attribute_ids, - "methods": method_ids, - "stereotype": ( - "enumeration" if isinstance(type_obj, Enumeration) else None - ), - } - if not isinstance(type_obj, Constraint) - # Class-level constraints are always invariants and their - # ``expression`` field already carries the full canonical - # ``context X inv name: body`` text (set at JSON-to-BUML - # parse time). Emit it verbatim — no reconstruction - # needed. - else { - "constraint": type_obj.expression, - } - ), - } + literals_iter = sorted(type_obj.literals, key=lambda lit: lit.name) + for literal in literals_iter: + attribute_rows.append(_set_timestamp({ + "id": take_id(literal), + "name": literal.name, + "attributeType": "str", + "visibility": "public", + }, literal)) + + data: dict = {"name": type_obj.name, "stereotype": stereotype} + data["attributes"] = attribute_rows + data["methods"] = method_rows + + if isinstance(type_obj, Class) and getattr(type_obj, 'metadata', None): + md = type_obj.metadata + # Only where the class inspector reads it: a linked comment as + # well would merge into the description again on re-import. + if md.description: + data["description"] = md.description + if md.uri: + data["uri"] = md.uri + if md.icon: + data["icon"] = md.icon + _set_timestamp(data, type_obj) + + width, height = _class_node_size(type_obj.name, stereotype, attribute_rows, method_rows) + if saved_bounds: + position = {"x": saved_bounds["x"], "y": saved_bounds["y"]} + width = saved_bounds.get("width", width) + height = saved_bounds.get("height", height) + for style_key in ("fillColor", "strokeColor", "textColor", "highlight"): + if style_key in saved_bounds: + data[style_key] = saved_bounds[style_key] + else: + position = {"x": 0, "y": 0} + node = make_node( + node_id=node_id, + type_="class", + data=data, + position=position, + width=width, + height=height, + ) + nodes.append(node) + if not saved_bounds: + auto_placed.append(node) + + # OCL constraints — every constraint is emitted as its own + # ``ClassOCLConstraint`` node (the sticky-note shape the frontend + # renders and edits via ``ClassOCLConstraintEditPanel``), tethered to + # its anchoring class by a visual ``ClassOCLLink`` edge when one + # resolves. Mirrors the develop baseline, where constraints are always + # visible boxes; the canonical full ``context ...`` text rides on + # ``data.expression`` so the ingest side re-derives the context class + # from the text itself (the link is purely visual). + def _emit_constraint_node(c, anchor_class) -> None: + node_id = take_id(c) + data = { + "name": c.name, + "expression": c.expression, + } + if getattr(c, "description", None): + data["description"] = c.description + _set_timestamp(data, c) + node = make_node( + node_id=node_id, + type_="ClassOCLConstraint", + data=data, + position={"x": 0, "y": 0}, + width=210, + height=90, + ) + nodes.append(node) + auto_placed.append(node) + if anchor_class is not None and anchor_class in class_id_map: + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=node_id, + target=class_id_map[anchor_class], + type_="ClassOCLLink", + data={"points": []}, + )) + + # Class-level invariants (and ownerless free-standing constraints). + for c in sorted(domain_model.constraints, key=lambda c: c.name): + anchor = c.context if isinstance(c, Constraint) else None + _emit_constraint_node(c, anchor) + + # Method-level pre/post conditions, anchored on the owning class. + # These live on ``Method.pre`` / ``Method.post`` (not in + # ``domain_model.constraints``), so they need their own pass. + for type_obj in sorted( + (t for t in domain_model.types if isinstance(t, Class)), + key=lambda t: t.name, + ): + for method in sorted(type_obj.methods, key=lambda m: m.name): + for constraints in (getattr(method, "pre", []) or [], + getattr(method, "post", []) or []): + for c in constraints: + _emit_constraint_node(c, type_obj) - # Surface natural-language constraint descriptions for the editor - if isinstance(type_obj, Constraint) and getattr(type_obj, 'description', None): - element_data["description"] = type_obj.description - - # Add metadata fields for classes if they exist - if isinstance(type_obj, Class) and hasattr(type_obj, 'metadata') and type_obj.metadata: - if type_obj.metadata.description: - element_data["description"] = type_obj.metadata.description - # Also create a comment element linked to this class - comments_to_create.append((type_obj.metadata.description, element_id)) - if type_obj.metadata.uri: - element_data["uri"] = type_obj.metadata.uri - if type_obj.metadata.icon: - element_data["icon"] = type_obj.metadata.icon - - _set_timestamp(element_data, type_obj) - elements[element_id] = element_data - - # Second pass: Create relationships + # Associations. for association in sorted(domain_model.associations, key=lambda a: a.name): try: - rel_id = take_id(association) - name = association.name if association.name else "" + name = association.name or "" # Declaration order is the drawn orientation: the JSON -> BUML processor creates # the source end first and an exported script recreates the ends in that order. ends = sort_by_timestamp(association.ends) - if len(ends) == 2: - source_prop, target_prop = ends - saved_rel = layout_positions.get(f"rel_{name}") - - # Keep the orientation the diagram was drawn with (recorded by - # the JSON -> BUML processor), so the saved endpoint layout is - # applied to the right classes. Navigability does not affect the - # orientation: it is emitted explicitly per end below. - if saved_rel and saved_rel.get("source_role") == target_prop.name: - source_prop, target_prop = target_prop, source_prop - - # The composite (whole) end of a composition is always the target. - if source_prop.is_composite and not target_prop.is_composite: - source_prop, target_prop = target_prop, source_prop - - source_class = source_prop.type - target_class = target_prop.type - - if source_class in class_id_map and target_class in class_id_map: - # Determine relationship type. Plain associations are always - # emitted as ClassBidirectional; which ends are navigable is - # carried by the explicit per-end "navigable" flags. - # NOTE: ClassAggregation cannot be reconstructed here because the - # B-UML metamodel does not carry an aggregation flag on Property. - # Aggregation associations are round-tripped as ClassBidirectional. - rel_type = ( - RELATIONSHIP_TYPES["composition"] - if target_prop.is_composite - else RELATIONSHIP_TYPES["bidirectional"] - ) + if len(ends) != 2: + continue + source_prop, target_prop = ends + saved_rel = layout_positions.get(f"rel_{name}") or {} + + # Keep the orientation the diagram was drawn with (recorded by + # the JSON -> BUML processor as ``source_role``), so the saved + # handles / points are applied to the right classes. Navigability + # does not affect orientation: it is emitted explicitly per end. + if saved_rel.get("source_role") == target_prop.name: + source_prop, target_prop = target_prop, source_prop + + # The composite (whole) end of a composition is always the target. + if source_prop.is_composite and not target_prop.is_composite: + source_prop, target_prop = target_prop, source_prop + + source_class = source_prop.type + target_class = target_prop.type + if source_class not in class_id_map or target_class not in class_id_map: + continue + + # Plain associations are always emitted as ClassBidirectional; + # which ends are navigable rides on the explicit per-end + # ``sourceNavigable`` / ``targetNavigable`` flags. (The metamodel + # has no aggregation flag, so aggregations round-trip as + # ClassBidirectional too.) + rel_type = ( + RELATIONSHIP_TYPES["composition"] + if target_prop.is_composite + else RELATIONSHIP_TYPES["bidirectional"] + ) - # Restore saved layout positions from a previous round-trip - # ("source_role" alone is orientation, not layout). - if saved_rel and any(key != "source_role" for key in saved_rel): - # Restore saved layout - rel_bounds = saved_rel.get("bounds", {"x": 0, "y": 0, "width": 0, "height": 0}) - path_points = saved_rel.get("path", [{"x": 0, "y": 0}, {"x": 0, "y": 0}]) - is_manually_layouted = saved_rel.get("isManuallyLayouted", False) - source_bounds = saved_rel.get("source_bounds", {"x": 0, "y": 0, "width": 0, "height": 0}) - source_dir = saved_rel.get("source_direction", "Right") - target_bounds = saved_rel.get("target_bounds", {"x": 0, "y": 0, "width": 0, "height": 0}) - target_dir = saved_rel.get("target_direction", "Left") - else: - # Fall back to computing layout from element positions - source_element = elements[class_id_map[source_class]] - target_element = elements[class_id_map[target_class]] - - source_dir, target_dir = determine_connection_direction( - source_element["bounds"], target_element["bounds"] - ) - source_point = calculate_connection_points( - source_element["bounds"], source_dir - ) - target_point = calculate_connection_points( - target_element["bounds"], target_dir - ) - path_points = calculate_path_points( - source_point, target_point, source_dir, target_dir - ) - rel_bounds = calculate_relationship_bounds(path_points) - is_manually_layouted = False - source_bounds = { - "x": source_point["x"], - "y": source_point["y"], - "width": 0, - "height": 0, - } - target_bounds = { - "x": target_point["x"], - "y": target_point["y"], - "width": 0, - "height": 0, - } - - relationships[rel_id] = _set_timestamp({ - "id": rel_id, - "name": name, - "type": rel_type, - "source": _set_timestamp({ - "element": class_id_map[source_class], - "multiplicity": format_multiplicity_label(source_prop.multiplicity), - "role": source_prop.name, - "navigable": source_prop.is_navigable, - "direction": source_dir, - "bounds": source_bounds, - }, source_prop), - "target": _set_timestamp({ - "element": class_id_map[target_class], - "multiplicity": format_multiplicity_label(target_prop.multiplicity), - "role": target_prop.name, - "navigable": target_prop.is_navigable, - "direction": target_dir, - "bounds": target_bounds, - }, target_prop), - "bounds": rel_bounds, - "path": path_points, - "isManuallyLayouted": is_manually_layouted, - }, association) + edge_data: dict = { + "name": name, + "sourceRole": source_prop.name, + "sourceMultiplicity": _multiplicity_str(source_prop), + "sourceNavigable": bool(source_prop.is_navigable), + "targetRole": target_prop.name, + "targetMultiplicity": _multiplicity_str(target_prop), + "targetNavigable": bool(target_prop.is_navigable), + "points": saved_rel.get("path", []), + } + if "isManuallyLayouted" in saved_rel: + edge_data["isManuallyLayouted"] = saved_rel["isManuallyLayouted"] + _set_timestamp(edge_data, association) + _set_timestamp(edge_data, source_prop, "sourceTimestamp") + _set_timestamp(edge_data, target_prop, "targetTimestamp") + + edge = make_edge( + edge_id=take_id(association), + source=class_id_map[source_class], + target=class_id_map[target_class], + type_=rel_type, + data=edge_data, + source_handle=saved_rel.get("source_direction", "right"), + target_handle=saved_rel.get("target_direction", "left"), + ) + edges.append(edge) except Exception as e: logger.error("Error converting relationship to JSON: %s", e, exc_info=True) continue - # Handle generalizations - for generalization in sorted(domain_model.generalizations, key=lambda g: (g.specific.name, g.general.name)): - rel_id = take_id(generalization) + # Generalizations. + for generalization in sorted( + domain_model.generalizations, + key=lambda g: (g.specific.name, g.general.name), + ): if ( - generalization.general in class_id_map - and generalization.specific in class_id_map + generalization.general not in class_id_map + or generalization.specific not in class_id_map ): - # Check for saved layout positions from a previous round-trip - gen_key = generalization_layout_key(generalization.specific, generalization.general) - saved_gen = layout_positions.get(gen_key) - if saved_gen: - gen_path = saved_gen.get("path", [ - {"x": 0, "y": 0}, {"x": 50, "y": 0}, - {"x": 50, "y": 50}, {"x": 100, "y": 50}, - ]) - gen_source_bounds = saved_gen.get("source_bounds", {"x": 0, "y": 0, "width": 0, "height": 0}) - gen_target_bounds = saved_gen.get("target_bounds", {"x": 0, "y": 0, "width": 0, "height": 0}) - else: - gen_path = [ - {"x": 0, "y": 0}, {"x": 50, "y": 0}, - {"x": 50, "y": 50}, {"x": 100, "y": 50}, - ] - gen_source_bounds = {"x": 0, "y": 0, "width": 0, "height": 0} - gen_target_bounds = {"x": 0, "y": 0, "width": 0, "height": 0} - - relationships[rel_id] = _set_timestamp({ - "id": rel_id, - "type": "ClassInheritance", - "source": { - "element": class_id_map[generalization.specific], - "bounds": gen_source_bounds, - }, - "target": { - "element": class_id_map[generalization.general], - "bounds": gen_target_bounds, - }, - "path": gen_path, - }, generalization) - - # Handle association classes + continue + gen_key = generalization_layout_key(generalization.specific, generalization.general) + saved_gen = layout_positions.get(gen_key) or {} + edge = make_edge( + edge_id=take_id(generalization), + source=class_id_map[generalization.specific], + target=class_id_map[generalization.general], + type_="ClassInheritance", + data=_set_timestamp({"points": saved_gen.get("path", [])}, generalization), + source_handle=saved_gen.get("source_direction", "right"), + target_handle=saved_gen.get("target_direction", "left"), + ) + edges.append(edge) + + # Association classes -> ClassLinkRel edges. + # Note: the AssociationClass has an embedded ``association``; find the + # association edge we just emitted whose name matches and link it. + edge_by_name: dict = {} + for edge in edges: + edge_data = edge.get("data") or {} + if edge.get("type") in ( + RELATIONSHIP_TYPES["bidirectional"], + RELATIONSHIP_TYPES["unidirectional"], + RELATIONSHIP_TYPES["composition"], + ) and edge_data.get("name"): + edge_by_name[edge_data["name"]] = edge["id"] for type_obj in sorted(domain_model.types, key=lambda t: t.name): if isinstance(type_obj, AssociationClass) and type_obj in class_id_map: - # Track associations by name for easier lookup - association_by_name = {} - for rel_id, rel in relationships.items(): - if rel.get("type") in [ - "ClassBidirectional", - "ClassUnidirectional", - "ClassComposition", - ]: - association_by_name[rel.get("name", "")] = rel_id - - # Find the association relationship ID by name - association_rel_id = association_by_name.get(type_obj.association.name) - if association_rel_id: - # Create a ClassLinkRel relationship - rel_id = str(uuid.uuid4()) - - relationships[rel_id] = { - "id": rel_id, - "name": "", - "type": "ClassLinkRel", - "owner": None, - "source": {"element": association_rel_id, "direction": "Center"}, - "target": {"element": class_id_map[type_obj], "direction": "Up"}, - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}, - "path": [{"x": 0, "y": 0}, {"x": 0, "y": 0}], - "isManuallyLayouted": False, - } - - # Handle OCL constraint links (visual-only relationships). - # NOTE: The constraint DATA is stored in ClassOCLConstraint elements (created above - # from domain_model.constraints). The ClassOCLLink relationships created here are - # purely for the frontend to draw a visual link between the constraint box and the - # class it applies to. On the json_to_buml side, ClassOCLLink relationships are - # intentionally skipped (the context class is derived from the OCL expression text). - # Both are needed: the element for data, the link for visual layout. - for type_obj in sorted(domain_model.constraints, key=lambda c: c.name): - if isinstance(type_obj, Constraint) and type_obj.context in class_id_map: - rel_id = str(uuid.uuid4()) - relationships[rel_id] = { - "id": rel_id, - "name": "", - "type": "ClassOCLLink", - "owner": None, - "source": { - "direction": "Left", - "element": class_id_map[type_obj], - "multiplicity": "", - "role": "", - }, - "target": { - "direction": "Right", - "element": class_id_map[type_obj.context], - "multiplicity": "", - "role": "", - }, - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}, - "path": [{"x": 0, "y": 0}, {"x": 0, "y": 0}], - "isManuallyLayouted": False, - } - - # Emit pre/post conditions anchored on Method.pre and Method.post. - # These are stored on the metamodel as first-class fields (not inside - # domain_model.constraints), so they need their own emission pass. - # Each constraint becomes its own ClassOCLConstraint element + a - # ClassOCLLink to the owning class. The textbox carries the full - # ``context X::method(params) pre|post: body`` form — same shape the - # ingest path now expects from a freshly-typed constraint. - for cls in sorted( - (t for t in domain_model.types if isinstance(t, Class)), - key=lambda c: c.name, - ): - if cls not in class_id_map: - continue - for method in sorted(cls.methods, key=lambda m: m.name): - for kind, constraints in (("precondition", getattr(method, "pre", []) or []), - ("postcondition", getattr(method, "post", []) or [])): - for constraint in constraints: - box_id = take_id(constraint) - elements[box_id] = { - "id": box_id, - "type": "ClassOCLConstraint", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}, - # ``expression`` carries the full canonical - # ``context X::method(params) pre|post: body`` text - # (set at JSON-to-BUML parse time). No reconstruction - # needed. - "constraint": constraint.expression, - } - # Mirror the invariant emit path: surface the - # natural-language description so JSON↔BUML round-trips - # are symmetric for method contracts too. - if getattr(constraint, "description", None): - elements[box_id]["description"] = constraint.description - _set_timestamp(elements[box_id], constraint) - rel_id = str(uuid.uuid4()) - relationships[rel_id] = { - "id": rel_id, - "name": "", - "type": "ClassOCLLink", - "owner": None, - "source": { - "direction": "Left", - "element": box_id, - "multiplicity": "", - "role": "", - }, - "target": { - "direction": "Right", - "element": class_id_map[cls], - "multiplicity": "", - "role": "", - }, - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}, - "path": [{"x": 0, "y": 0}, {"x": 0, "y": 0}], - "isManuallyLayouted": False, - } - - # Create comment elements from metadata descriptions - for comment_text, linked_class_id in comments_to_create: - comment_id = str(uuid.uuid4()) - x, y = get_position() - - # Create comment element - elements[comment_id] = { - "id": comment_id, - "name": comment_text, - "type": "Comments", - "owner": None, - "bounds": { - "x": x, - "y": y, - "width": 160, - "height": 100, - }, - } - - # Create Link relationship from comment to class - rel_id = str(uuid.uuid4()) - relationships[rel_id] = { - "id": rel_id, - "name": "", - "type": "Link", - "owner": None, - "source": { - "direction": "Right", - "element": comment_id, - "multiplicity": "", - "role": "", - }, - "target": { - "direction": "Left", - "element": linked_class_id, - "multiplicity": "", - "role": "", - }, - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}, - "path": [{"x": 0, "y": 0}, {"x": 0, "y": 0}], - "isManuallyLayouted": False, - } + assoc_edge_id = edge_by_name.get(type_obj.association.name) + if assoc_edge_id: + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=assoc_edge_id, + target=class_id_map[type_obj], + type_="ClassLinkRel", + data={"points": []}, + source_handle="Center", + target_handle="Up", + )) - # Handle domain model level comments (unlinked comments) if hasattr(domain_model, 'metadata') and domain_model.metadata and domain_model.metadata.description: - comment_id = str(uuid.uuid4()) - x, y = get_position() - - elements[comment_id] = { - "id": comment_id, - "name": domain_model.metadata.description, - "type": "Comments", - "owner": None, - "bounds": { - "x": x, - "y": y, - "width": 160, - "height": 100, - }, - } - - # Create the final structure - # Clean up implementation-related keys for attributes and empty values - for elem in elements.values(): - if elem.get("type") == "ClassAttribute": - elem.pop("implementationType", None) - elem.pop("stateMachineId", None) - elem.pop("quantumCircuitId", None) - elem.pop("neuralNetworkId", None) - if elem.get("type") == "ClassMethod": - if not elem.get("implementationType"): - elem.pop("implementationType", None) - if not elem.get("stateMachineId"): - elem.pop("stateMachineId", None) - if not elem.get("quantumCircuitId"): - elem.pop("quantumCircuitId", None) - if not elem.get("neuralNetworkId"): - elem.pop("neuralNetworkId", None) - + node = make_node( + node_id=str(uuid.uuid4()), + type_="comment", + data={"name": domain_model.metadata.description}, + position={"x": 0, "y": 0}, + width=160, + height=100, + ) + nodes.append(node) + auto_placed.append(node) + + # Auto-placed nodes go on the grid, below any nodes with a saved position. + auto_ids = {n["id"] for n in auto_placed} + placed = [n for n in nodes if n["id"] not in auto_ids] + origin = LAYOUT_ORIGIN + if placed: + origin = ( + min(n["position"]["x"] for n in placed), + max(n["position"]["y"] + n["height"] for n in placed) + LAYOUT_GAP_Y, + ) + grid_layout(auto_placed, origin=origin, columns=LAYOUT_MAX_COLUMNS, gap_y=LAYOUT_GAP_Y) + + default_size = {"width": LAYOUT_GRID_WIDTH, "height": LAYOUT_GRID_HEIGHT} result = { - "version": "3.0.0", + "version": "4.0.0", "type": "ClassDiagram", + "title": getattr(domain_model, "name", "") or "", "size": default_size, + "nodes": nodes, + "edges": edges, "interactive": {"elements": {}, "relationships": {}}, - "elements": elements, - "relationships": relationships, "assessments": {}, } - _set_timestamp(result, domain_model) - - return result + return _set_timestamp(result, domain_model) diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/component_diagram_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/component_diagram_converter.py index d65b47f88..9f56b309f 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/component_diagram_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/component_diagram_converter.py @@ -1,9 +1,10 @@ -"""Component diagram conversion: ComponentModel -> WME JSON. +"""Component diagram conversion: ComponentModel -> v4 WME JSON (``{nodes, edges}``). ``component_object_to_json`` is a pure metamodel-object -> JSON walk, the inverse of ``json_to_buml.component_diagram_processor``. ``component_buml_to_json(content)`` loads a BUML file produced by ``component_model_to_code`` and converts the model it defines. +Wire shape: ``docs/source/migrations/uml-v4-shape.md`` (ComponentDiagram). """ import logging @@ -33,35 +34,52 @@ ) from besser.BUML.metamodel.uml_component._stereotypes import tokenise_component_stereotype from besser.utilities.utils import sort_by_timestamp +from besser.utilities.web_modeling_editor.backend.constants.constants import ( + COMPONENT_REQUIRED_INTERFACE_EDGE_TYPES, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._node_builders import ( + envelope_size, + layout_unplaced_nodes, + make_positions_parent_relative, + node_from_layout, + parents_first, + stereotyped_edge, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._safe_buml_loader import ( + safe_load_buml, +) from besser.utilities.web_modeling_editor.backend.services.converters.component_legacy import ( drop_legacy_reverse_collaborations, legacy_edge_successor, ) +from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import element_id_taker from besser.utilities.web_modeling_editor.backend.services.converters.stereotype_tokens import ( format_agentic_edge_stereotype, format_component_stereotype, format_component_subtype_stereotype, validate_component_role_tokens, ) -from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import element_id_taker -from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._safe_buml_loader import ( - safe_load_buml, -) from besser.utilities.web_modeling_editor.backend.services.exceptions import ( ConversionError, ) logger = logging.getLogger(__name__) +_DEFAULT_SIZE = { + "component": (160, 100), + "componentSubsystem": (200, 120), + "componentInterface": (20, 20), +} + def component_object_to_json(model: ComponentModel) -> dict: - """Convert a ``ComponentModel`` into a WME Component diagram (JSON dict). + """Convert a ``ComponentModel`` into a v4 WME Component diagram (JSON dict). Args: model: The ``ComponentModel`` to convert. Returns: - dict: WME ``UMLModel`` envelope with ``elements`` and ``relationships``. + dict: v4 ``UMLModel`` envelope with ``nodes`` and ``edges``. """ if not isinstance(model, ComponentModel): raise ConversionError( @@ -73,10 +91,7 @@ def component_object_to_json(model: ComponentModel) -> dict: if errors: raise ConversionError("\n".join(errors)) - elements: dict = {} - relationships: dict = {} id_map: dict = {} - take_id = element_id_taker() def id_for(obj) -> str: @@ -87,175 +102,110 @@ def id_for(obj) -> str: # Every component, including those reachable only through a Subsystem. components = sort_by_timestamp(model.all_components()) interfaces = sort_by_timestamp(model.interfaces) - model_relationships = sort_by_timestamp(model.relationships) - - # Pre-mint ids in deterministic order so element / relationship ordering - # in the output is stable. - for c in components: - id_for(c) - for iface in interfaces: - id_for(iface) - for rel in model_relationships: - id_for(rel) + for element in (*components, *interfaces): + id_for(element) - for component in components: - elements[id_for(component)] = _emit_component_entry(component, id_for) + nodes = [_component_node(c, id_for) for c in components] + emitted_ids = {node["id"] for node in nodes} + nodes += [_interface_node(i, id_for, emitted_ids) for i in interfaces] + nodes = parents_first(nodes) - # Interfaces (free-standing — Component-diagram model holds them at root) - for interface in interfaces: - elements[id_for(interface)] = _emit_interface_entry(interface, id_for) + placed_ids = {id_for(e) for e in (*components, *interfaces) if (e.layout or {}).get("bounds")} + make_positions_parent_relative(nodes, placed_ids) + layout_unplaced_nodes(nodes, placed_ids) - for rel in model_relationships: - relationships[id_for(rel)] = _emit_relationship_entry(rel, id_for) - - size = _compute_size(elements) + edges = [_relationship_edge(rel, id_for) for rel in sort_by_timestamp(model.relationships)] return { - "version": "3.0.0", + "version": "4.0.0", "type": "ComponentDiagram", - "size": size, + "title": model.name or "", + "size": envelope_size(nodes), + "nodes": nodes, + "edges": edges, "interactive": {"elements": {}, "relationships": {}}, - "elements": elements, - "relationships": relationships, "assessments": {}, } -def _emit_component_entry(component: Component, id_for) -> dict: - """Emit a Component / Subsystem / Skill / Tool node entry.""" - layout = component.layout or {} - if isinstance(component, Subsystem): - wme_type = layout.get("wme_type") or "Subsystem" - else: - wme_type = layout.get("wme_type") or "Component" - bounds = layout.get("bounds") or _default_component_bounds(wme_type) - entry = { - "id": id_for(component), - "name": component.name, - "type": wme_type, - "owner": id_for(component.parent) if component.parent is not None else None, - "bounds": bounds, - } - # Skill/Tool/LLM/Database/RAG get the subtype-promotion token in front; - # the editor's «subsystem» / «component» defaults ride along as free-form - # stereotypes. +def _component_node(component: Component, id_for) -> dict: + """Emit a ``component`` / ``componentSubsystem`` node.""" + header = bool((component.layout or {}).get("displayStereotype", True)) + parent_id = id_for(component.parent) if component.parent is not None else None if isinstance(component, Subsystem): - stereotype = format_component_stereotype(component) - else: - stereotype = format_component_subtype_stereotype(component) + data = { + "name": component.name, + "stereotype": format_component_stereotype(component), + "isComponentSubsystemHeaderShown": header, + } + return node_from_layout(component, id_for(component), "componentSubsystem", data, parent_id, + _DEFAULT_SIZE["componentSubsystem"]) + # Skill/Tool/LLM/Database/RAG get the subtype-promotion token in front. + stereotype = format_component_subtype_stereotype(component) if isinstance(component, AgenticComponent): try: validate_component_role_tokens(tokenise_component_stereotype(stereotype)) except ValueError as exc: raise ConversionError(f"Component '{component.name}': {exc}") from exc - if stereotype: - entry["stereotype"] = stereotype - entry["displayStereotype"] = bool(layout.get("displayStereotype", True)) - if wme_type == "Component": - # The editor's Component element carries the cross-diagram links. - entry["realizes"] = list(component.realizes) - entry["processModelRefs"] = list(component.process_model_refs) - if component.agent_model_ref is not None: - entry["agentModelRef"] = component.agent_model_ref - return entry - - -def _emit_interface_entry(interface: Interface, id_for) -> dict: - """Emit a ComponentInterface entry.""" - layout = interface.layout or {} - wme_type = layout.get("wme_type") or "ComponentInterface" - bounds = layout.get("bounds") or {"x": 0, "y": 0, "width": 20, "height": 20} - return { - "id": id_for(interface), - "name": interface.name, - "type": wme_type, - "owner": layout.get("owner"), - "bounds": bounds, + data = { + "name": component.name, + "stereotype": stereotype, + "isComponentHeaderShown": header, + "realizes": list(component.realizes), + "processModelRefs": list(component.process_model_refs), } + if component.agent_model_ref is not None: + data["agentModelRef"] = component.agent_model_ref + return node_from_layout(component, id_for(component), "component", data, parent_id, + _DEFAULT_SIZE["component"]) -def _emit_relationship_entry(rel, id_for) -> dict: - """Emit one relationship entry. +def _interface_node(interface: Interface, id_for, emitted_ids: set) -> dict: + """Emit a ``componentInterface`` node; its drawn parent comes from the layout.""" + layout = interface.layout or {} + parent_id = layout.get("parentId", layout.get("owner")) + return node_from_layout( + interface, id_for(interface), "componentInterface", {"name": interface.name}, + parent_id if parent_id in emitted_ids else None, _DEFAULT_SIZE["componentInterface"], + ) + + +def _relationship_edge(rel, id_for) -> dict: + """Emit one edge. Raises: ConversionError: for a relationship class with no editor mapping. """ layout = rel.layout or {} - bounds = layout.get("bounds") or {"x": 0, "y": 0, "width": 1, "height": 1} - path = layout.get("path") or [{"x": 0, "y": 0}, {"x": 1, "y": 0}] - source = { - "element": id_for(rel.source), - "direction": layout.get("source_direction") or "Right", - } - target = { - "element": id_for(rel.target), - "direction": layout.get("target_direction") or "Left", - } - is_manually_layouted = bool(layout.get("isManuallyLayouted", False)) - if isinstance(rel, InterfaceProvided): - wme_type = "ComponentInterfaceProvided" + edge_type = "ComponentProvidedInterface" stereotype = " ".join(rel.stereotypes) elif isinstance(rel, InterfaceRequired): - wme_type = "ComponentInterfaceRequired" + stashed = layout.get("type") + edge_type = stashed if stashed in COMPONENT_REQUIRED_INTERFACE_EDGE_TYPES else "ComponentRequiredInterface" stereotype = " ".join(rel.stereotypes) elif isinstance(rel, AgenticEdge): - wme_type = "ComponentDependency" + edge_type = "ComponentDependency" stereotype = format_agentic_edge_stereotype(rel.kind, rel.stereotypes) elif isinstance(rel, ComponentDependency): - wme_type = "ComponentDependency" + edge_type = "ComponentDependency" stereotype = " ".join(rel.stereotypes) else: raise ConversionError( f"Component relationship class {type(rel).__name__} has no editor mapping." ) - - entry = { - "id": id_for(rel), - "name": rel.name or "", - "type": wme_type, - "owner": layout.get("owner"), - "bounds": bounds, - "path": path, - "source": source, - "target": target, - "isManuallyLayouted": is_manually_layouted, - } - if stereotype: - entry["stereotype"] = stereotype + edge = stereotyped_edge(rel, id_for, edge_type, stereotype) if isinstance(rel, AgenticEdge): if rel.interface_binding is not None: required, provided = rel.interface_binding - entry["interfaceBinding"] = {"required": id_for(required), "provided": id_for(provided)} + edge["data"]["interfaceBinding"] = {"required": id_for(required), "provided": id_for(provided)} if rel.collaboration_direction is not None: - entry["collaborationDirection"] = rel.collaboration_direction.value - return entry - - -def _default_component_bounds(wme_type: str) -> dict: - """Return a placeholder bounds dict for freshly-built (no-layout) elements.""" - if wme_type == "Subsystem": - return {"x": 0, "y": 0, "width": 200, "height": 120} - return {"x": 0, "y": 0, "width": 160, "height": 100} - - -def _compute_size(elements: dict) -> dict: - """Compute the diagram bounding box (min 800x600) from all element bounds.""" - max_x = 800 - max_y = 600 - for entry in elements.values(): - bounds = entry.get("bounds") or {} - right = (bounds.get("x") or 0) + (bounds.get("width") or 0) - bottom = (bounds.get("y") or 0) + (bounds.get("height") or 0) - if right > max_x: - max_x = right - if bottom > max_y: - max_y = bottom - return {"width": int(max_x), "height": int(max_y)} + edge["data"]["collaborationDirection"] = rel.collaboration_direction.value + return edge def component_buml_to_json(content: str, warnings: Optional[list] = None) -> dict: - """Convert Component BUML source into a WME Component diagram (JSON). + """Convert Component BUML source into a v4 WME Component diagram (JSON). Strip generated imports, then load the source with the restricted BUML loader and an explicit allowlist of Component metamodel names. Find the diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/deployment_diagram_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/deployment_diagram_converter.py index 59407c82b..de2a58d04 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/deployment_diagram_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/deployment_diagram_converter.py @@ -1,11 +1,12 @@ -"""Deployment diagram conversion: DeploymentModel -> WME JSON. +"""Deployment diagram conversion: DeploymentModel -> v4 WME JSON (``{nodes, edges}``). ``deployment_object_to_json`` is a pure metamodel-object -> JSON walk, the inverse of ``json_to_buml.deployment_diagram_processor``. The multiplicity of an artifact's first ``DeploymentRelation`` goes into the artifact's name suffix (``"Coder [3]"``) and a ``DeploymentComponent`` is emitted as the -editor's ``DeploymentComponent`` element. ``deployment_buml_to_json(content)`` +editor's ``deploymentComponent`` node. ``deployment_buml_to_json(content)`` loads a BUML file produced by ``deployment_model_to_code``. +Wire shape: ``docs/source/migrations/uml-v4-shape.md`` (DeploymentDiagram). """ import logging @@ -29,6 +30,20 @@ NodeKind, ) from besser.utilities.utils import sort_by_timestamp +from besser.utilities.web_modeling_editor.backend.constants.constants import ( + DEPLOYMENT_REQUIRED_INTERFACE_EDGE_TYPES, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._node_builders import ( + envelope_size, + layout_unplaced_nodes, + make_positions_parent_relative, + node_from_layout, + parents_first, + stereotyped_edge, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._safe_buml_loader import ( + safe_load_buml, +) from besser.utilities.web_modeling_editor.backend.services.converters.multiplicity_format import ( format_to_name, ) @@ -37,24 +52,28 @@ format_node_stereotype, ) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import element_id_taker -from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._safe_buml_loader import ( - safe_load_buml, -) from besser.utilities.web_modeling_editor.backend.services.exceptions import ( ConversionError, ) logger = logging.getLogger(__name__) +_DEFAULT_SIZE = { + "deploymentNode": (200, 140), + "deploymentArtifact": (160, 40), + "deploymentComponent": (160, 100), + "deploymentInterface": (20, 20), +} + def deployment_object_to_json(model: DeploymentModel) -> dict: - """Convert a ``DeploymentModel`` into a WME Deployment diagram (JSON dict). + """Convert a ``DeploymentModel`` into a v4 WME Deployment diagram (JSON dict). Args: model: The ``DeploymentModel`` to convert. Returns: - dict: WME ``UMLModel`` envelope with ``elements`` and ``relationships``. + dict: v4 ``UMLModel`` envelope with ``nodes`` and ``edges``. """ if not isinstance(model, DeploymentModel): raise ConversionError( @@ -62,8 +81,6 @@ def deployment_object_to_json(model: DeploymentModel) -> dict: f"got {type(model).__name__}." ) - elements: dict = {} - relationships: dict = {} id_map: dict = {} take_id = element_id_taker() @@ -77,50 +94,39 @@ def id_for(obj) -> str: all_artifacts = sort_by_timestamp(model.all_artifacts()) all_interfaces = sort_by_timestamp(model.interfaces) all_relationships = sort_by_timestamp(model.relationships) + elements = (*all_nodes, *all_artifacts, *all_interfaces) + for element in elements: + id_for(element) - # Pre-mint ids for stable ordering. - for n in all_nodes: - id_for(n) - for a in all_artifacts: - id_for(a) - for iface in all_interfaces: - id_for(iface) - for rel in all_relationships: - id_for(rel) - - # Index artifact -> deterministic DeploymentRelation for the multiplicity + # Artifact -> deterministic DeploymentRelation for the multiplicity # round-trip (the first relation by timestamp wins on divergence). artifact_to_relation = _index_artifact_to_relation(all_relationships) - for node in all_nodes: - elements[id_for(node)] = _emit_node_entry(node, id_for) + nodes = [_node_node(n, id_for) for n in all_nodes] + nodes += [_artifact_node(a, id_for, artifact_to_relation) for a in all_artifacts] + emitted_ids = {node["id"] for node in nodes} + nodes += [_interface_node(i, id_for, emitted_ids) for i in all_interfaces] + nodes = parents_first(nodes) - # Artifacts (including nested ones) - for artifact in all_artifacts: - elements[id_for(artifact)] = _emit_artifact_entry( - artifact, id_for, artifact_to_relation, - ) - - for interface in all_interfaces: - elements[id_for(interface)] = _emit_interface_entry(interface, id_for) + placed_ids = {id_for(e) for e in elements if (e.layout or {}).get("bounds")} + make_positions_parent_relative(nodes, placed_ids) + layout_unplaced_nodes(nodes, placed_ids) - # Relationships — emit explicit edges; owner-link-only relations are - # already encoded via the artifact's `owner` field and are skipped here - # to avoid double-encoding (see processor dedup logic). - for rel in all_relationships: - if (rel.layout or {}).get("wme_origin") == "owner": - continue - relationships[id_for(rel)] = _emit_relationship_entry(rel, id_for) - - size = _compute_size(elements) + # Parent-link-only relations are already encoded by the artifact's + # ``parentId`` and are not emitted as edges (see the processor's dedup). + edges = [ + _relationship_edge(rel, id_for) for rel in all_relationships + if (rel.layout or {}).get("wme_origin") != "owner" + ] return { - "version": "3.0.0", + "version": "4.0.0", "type": "DeploymentDiagram", - "size": size, + "title": model.name or "", + "size": envelope_size(nodes), + "nodes": nodes, + "edges": edges, "interactive": {"elements": {}, "relationships": {}}, - "elements": elements, - "relationships": relationships, "assessments": {}, } @@ -154,28 +160,20 @@ def _index_artifact_to_relation(relationships: list) -> dict: return out -def _emit_node_entry(node: Node, id_for) -> dict: - """Emit a DeploymentNode entry.""" - layout = node.layout or {} - wme_type = layout.get("wme_type") or "DeploymentNode" - bounds = layout.get("bounds") or {"x": 0, "y": 0, "width": 200, "height": 140} - entry = { - "id": id_for(node), +def _node_node(node: Node, id_for) -> dict: + """Emit a ``deploymentNode`` node.""" + data = { "name": node.name, - "type": wme_type, - "owner": id_for(node.parent) if node.parent is not None else None, - "bounds": bounds, + "stereotype": format_node_stereotype(node), + "isComponentHeaderShown": bool((node.layout or {}).get("displayStereotype", True)), } - stereotype = format_node_stereotype(node) - if stereotype: - entry["stereotype"] = stereotype - entry["displayStereotype"] = bool(layout.get("displayStereotype", True)) - return entry + parent_id = id_for(node.parent) if node.parent is not None else None + return node_from_layout(node, id_for(node), "deploymentNode", data, parent_id, + _DEFAULT_SIZE["deploymentNode"]) -def _emit_artifact_entry(artifact: Artifact, id_for, - artifact_to_relation: dict) -> dict: - """Emit a DeploymentArtifact or DeploymentComponent entry. +def _artifact_node(artifact: Artifact, id_for, artifact_to_relation: dict) -> dict: + """Emit a ``deploymentArtifact`` or ``deploymentComponent`` node. Suffixes the artifact's name with the multiplicity of its first DeploymentRelation (when non-default). Falls back to @@ -184,8 +182,7 @@ def _emit_artifact_entry(artifact: Artifact, id_for, """ layout = artifact.layout or {} is_component = isinstance(artifact, DeploymentComponent) - wme_type = "DeploymentComponent" if is_component else "DeploymentArtifact" - bounds = layout.get("bounds") or {"x": 0, "y": 0, "width": 160, "height": 40} + node_type = "deploymentComponent" if is_component else "deploymentArtifact" rel = artifact_to_relation.get(artifact) mult = rel.multiplicity if rel is not None else None @@ -195,111 +192,60 @@ def _emit_artifact_entry(artifact: Artifact, id_for, else: name = format_to_name(artifact.name, mult) - # The artifact's WME owner: its parent Node if nested, else None. - owner = id_for(artifact.parent) if artifact.parent is not None else None - - entry = { - "id": id_for(artifact), - "name": name, - "type": wme_type, - "owner": owner, - "bounds": bounds, - } + data = {"name": name} stereotype = format_artifact_stereotype(artifact) - if stereotype: - entry["stereotype"] = stereotype - entry["displayStereotype"] = bool(layout.get("displayStereotype", True)) - # The editor's DeploymentArtifact always carries ``manifests`` and, for an - # agent, ``agentModelRef``; a DeploymentComponent only when set. + if is_component: + data["stereotype"] = stereotype + data["isComponentHeaderShown"] = bool(layout.get("displayStereotype", True)) + elif stereotype: + data["stereotype"] = stereotype + # A deploymentArtifact always carries ``manifests`` and, for an agent, + # ``agentModelRef``; a deploymentComponent only when set. if not is_component or artifact.manifests: - entry["manifests"] = list(artifact.manifests) + data["manifests"] = list(artifact.manifests) if artifact.agent_model_ref is not None: - entry["agentModelRef"] = artifact.agent_model_ref - return entry + data["agentModelRef"] = artifact.agent_model_ref + parent_id = id_for(artifact.parent) if artifact.parent is not None else None + return node_from_layout(artifact, id_for(artifact), node_type, data, parent_id, + _DEFAULT_SIZE[node_type]) -def _emit_interface_entry(interface: Interface, id_for) -> dict: - """Emit a DeploymentInterface entry.""" + +def _interface_node(interface: Interface, id_for, emitted_ids: set) -> dict: + """Emit a ``deploymentInterface`` node; its drawn parent comes from the layout.""" layout = interface.layout or {} - wme_type = layout.get("wme_type") or "DeploymentInterface" - bounds = layout.get("bounds") or {"x": 0, "y": 0, "width": 20, "height": 20} - return { - "id": id_for(interface), - "name": interface.name, - "type": wme_type, - "owner": layout.get("owner"), - "bounds": bounds, - } + parent_id = layout.get("parentId", layout.get("owner")) + return node_from_layout( + interface, id_for(interface), "deploymentInterface", {"name": interface.name}, + parent_id if parent_id in emitted_ids else None, _DEFAULT_SIZE["deploymentInterface"], + ) -def _emit_relationship_entry(rel, id_for) -> dict: - """Emit one relationship entry. +def _relationship_edge(rel, id_for) -> dict: + """Emit one edge. Raises: ConversionError: for a relationship class with no editor mapping. """ - layout = rel.layout or {} - bounds = layout.get("bounds") or {"x": 0, "y": 0, "width": 1, "height": 1} - path = layout.get("path") or [{"x": 0, "y": 0}, {"x": 1, "y": 0}] - source = { - "element": id_for(rel.source), - "direction": layout.get("source_direction") or "Right", - } - target = { - "element": id_for(rel.target), - "direction": layout.get("target_direction") or "Left", - } - is_manually_layouted = bool(layout.get("isManuallyLayouted", False)) - - if isinstance(rel, DeploymentRelation): - wme_type = "DeploymentAssociation" - elif isinstance(rel, CommunicationPath): - wme_type = "DeploymentAssociation" + if isinstance(rel, (DeploymentRelation, CommunicationPath)): + edge_type = "DeploymentAssociation" elif isinstance(rel, DeploymentDependency): - wme_type = "DeploymentDependency" + edge_type = "DeploymentDependency" elif isinstance(rel, InterfaceProvided): - wme_type = "DeploymentInterfaceProvided" + edge_type = "DeploymentProvidedInterface" elif isinstance(rel, InterfaceRequired): - wme_type = "DeploymentInterfaceRequired" + stashed = (rel.layout or {}).get("type") + edge_type = (stashed if stashed in DEPLOYMENT_REQUIRED_INTERFACE_EDGE_TYPES + else "DeploymentRequiredInterface") else: raise ConversionError( f"Deployment relationship class {type(rel).__name__} has no editor mapping." ) - - entry = { - "id": id_for(rel), - "name": rel.name or "", - "type": wme_type, - "owner": layout.get("owner"), - "bounds": bounds, - "path": path, - "source": source, - "target": target, - "isManuallyLayouted": is_manually_layouted, - } - stereotype_parts = list(rel.stereotypes) - if stereotype_parts: - entry["stereotype"] = " ".join(stereotype_parts) - return entry - - -def _compute_size(elements: dict) -> dict: - """Compute the diagram bounding box (min 800x600) from all element bounds.""" - max_x = 800 - max_y = 600 - for entry in elements.values(): - bounds = entry.get("bounds") or {} - right = (bounds.get("x") or 0) + (bounds.get("width") or 0) - bottom = (bounds.get("y") or 0) + (bounds.get("height") or 0) - if right > max_x: - max_x = right - if bottom > max_y: - max_y = bottom - return {"width": int(max_x), "height": int(max_y)} + return stereotyped_edge(rel, id_for, edge_type, " ".join(rel.stereotypes)) def deployment_buml_to_json(content: str) -> dict: - """Convert Deployment BUML source into a WME Deployment diagram (JSON). + """Convert Deployment BUML source into a v4 WME Deployment diagram (JSON). Strip generated imports, then load the source with the restricted BUML loader and an explicit allowlist of Deployment metamodel names. Find the diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/nn_diagram_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/nn_diagram_converter.py index 6a6ef1ae0..8bffa2edf 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/nn_diagram_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/nn_diagram_converter.py @@ -1,8 +1,9 @@ """ -NN BUML → frontend JSON converter. +NN BUML -> v4 JSON converter. -Converts a BUML NN model into the element/relationship structure consumed -by the web editor for NNDiagrams. +Emits the v4 wire shape (``{nodes, edges}``) directly. Each layer's +attributes collapse onto ``data.attributes: dict`` (snake_case keys per +the spec at ``docs/source/migrations/uml-v4-shape.md``). """ import ast @@ -14,16 +15,14 @@ import besser.BUML.metamodel.nn as nn_module from besser.BUML.metamodel.nn import NN, Configuration, Dataset from besser.utilities.buml_code_builder.nn_model_builder import is_attr_explicitly_set +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._node_builders import ( + make_edge, + make_node, +) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import is_valid_element_id -# Stable namespace for uuid5-based element IDs. Using a fixed UUID here means -# the same BUML NN model, converted twice, produces byte-identical JSON — which -# makes round-trip snapshot tests reliable and helps downstream content-addressing. _NN_JSON_NAMESPACE = uuid.UUID('7a1a0c7e-0e9d-4e1c-a0e6-6e5b4e0c7e00') -# Thread-local monotonically-increasing counter. Reset at the top of every -# public conversion call (see nn_model_to_json). Thread-local so concurrent -# requests in the FastAPI thread pool don't interleave counter states. _id_state = threading.local() @@ -46,35 +45,27 @@ def _element_id(element) -> str: def _new_id(hint: str = '') -> str: - """Return a deterministic UUID for the next element in the current conversion. - - Sequence number is derived from a thread-local counter that ``nn_model_to_json`` - resets. The optional ``hint`` (e.g. 'container', 'attr:name') is folded into - the uuid5 key so different call sites at the same counter position still - produce distinct IDs — and identical inputs produce identical IDs across runs. - """ counter = getattr(_id_state, 'counter', 0) _id_state.counter = counter + 1 key = f"{counter}:{hint}" return str(uuid.uuid5(_NN_JSON_NAMESPACE, key)) -# Metamodel class → (frontend parent type, attribute type suffix) _MODULE_TYPE_MAP = { - 'Conv1D': ('Conv1DLayer', 'Conv1D'), - 'Conv2D': ('Conv2DLayer', 'Conv2D'), - 'Conv3D': ('Conv3DLayer', 'Conv3D'), - 'PoolingLayer': ('PoolingLayer', 'Pooling'), - 'SimpleRNNLayer': ('RNNLayer', 'RNN'), - 'LSTMLayer': ('LSTMLayer', 'LSTM'), - 'GRULayer': ('GRULayer', 'GRU'), - 'LinearLayer': ('LinearLayer', 'Linear'), - 'FlattenLayer': ('FlattenLayer', 'Flatten'), - 'EmbeddingLayer': ('EmbeddingLayer', 'Embedding'), - 'DropoutLayer': ('DropoutLayer', 'Dropout'), - 'LayerNormLayer': ('LayerNormalizationLayer', 'LayerNorm'), - 'BatchNormLayer': ('BatchNormalizationLayer', 'BatchNorm'), - 'TensorOp': ('TensorOp', 'TensorOp'), + 'Conv1D': 'Conv1DLayer', + 'Conv2D': 'Conv2DLayer', + 'Conv3D': 'Conv3DLayer', + 'PoolingLayer': 'PoolingLayer', + 'SimpleRNNLayer': 'RNNLayer', + 'LSTMLayer': 'LSTMLayer', + 'GRULayer': 'GRULayer', + 'LinearLayer': 'LinearLayer', + 'FlattenLayer': 'FlattenLayer', + 'EmbeddingLayer': 'EmbeddingLayer', + 'DropoutLayer': 'DropoutLayer', + 'LayerNormLayer': 'LayerNormalizationLayer', + 'BatchNormLayer': 'BatchNormalizationLayer', + 'TensorOp': 'TensorOp', } @@ -90,20 +81,13 @@ def _is_attr_set(obj, attr_name: str) -> bool: return is_attr_explicitly_set(obj, attr_name) -def _attr_type_for(field: str, suffix: str) -> str: - """Build the attribute `type` used by the frontend (e.g. 'NameAttributeConv2D').""" - pascal = ''.join(part.capitalize() for part in field.split('_')) - return f"{pascal}Attribute{suffix}" - - def _fmt_value(value: Any) -> str: - """Convert a Python value to the string representation used in the JSON 'value' field. + """Convert a Python value to the string stored in v4 ``data.attributes``. - Lists are formatted as ``[a, b, c]``; string items are kept bare (no quotes) - because the processor's parsers tolerate both ``[a, b]`` and ``['a', 'b']`` - and downstream consumers expect the bare form. The one exception is items - containing ``,`` or ``]``, which would round-trip incorrectly — those are - rejected so we fail fast instead of silently truncating. + Lists are formatted as ``[a, b, c]`` with string items single-quoted (the + processor strips the quotes again). Items containing ``,``, ``[``, ``]`` + or ``'`` would round-trip incorrectly, so they are rejected instead of + silently truncated. Dicts (and lists containing them — ``TensorOp.subscript_indices`` is a ``list[dict]``) are emitted as real JSON via :func:`json.dumps`. ``str()`` @@ -120,10 +104,6 @@ def _fmt_value(value: Any) -> str: ): return json.dumps(value) if isinstance(value, (list, tuple)): - # Tuples reach here when the metamodel setter accepted a tuple for - # a list-typed field (e.g. a hand-authored kernel_dim=(3, 3)). Treat - # them the same as lists so round-trip doesn't stringify the tuple - # syntax into something the processor can't re-parse cleanly. parts = [] for v in value: if isinstance(v, str): @@ -141,31 +121,6 @@ def _fmt_value(value: Any) -> str: return str(value) -def _make_attr(parent_id: str, field: str, value: Any, suffix: str, - bounds: dict[str, int], attr_type_hint: str = 'str', - mandatory: bool = False) -> dict[str, Any]: - """Build a single attribute element child dict.""" - formatted = _fmt_value(value) - return { - 'id': _new_id(), - 'name': f'{field} = {formatted}', - 'type': _attr_type_for(field, suffix), - 'owner': parent_id, - 'bounds': dict(bounds), - 'code': '', - 'visibility': 'public', - 'attributeType': attr_type_hint, - 'implementationType': 'none', - 'stateMachineId': '', - 'quantumCircuitId': '', - 'isOptional': not mandatory, - 'isDerived': False, - 'attributeName': field, - 'value': formatted, - 'isMandatory': mandatory, - } - - def _append_base_layer_fields(fields: list[tuple[str, Any, str, bool]], module) -> None: """Append base-layer fields (inherited from Layer) to the fields list.""" if _is_attr_set(module, 'is_layer_call'): @@ -195,7 +150,6 @@ def _module_fields(module) -> list[tuple[str, Any, str, bool]]: if module.stride_dim is not None: fields.append(('stride_dim', module.stride_dim, 'List', False)) if _is_attr_set(module, 'padding_amount') or module.padding_amount: - # Emit when user explicitly set (even to 0) or when non-default. fields.append(('padding_amount', module.padding_amount, 'int', False)) if _is_attr_set(module, 'padding_type') or (module.padding_type and module.padding_type != 'valid'): fields.append(('padding_type', module.padding_type, 'str', False)) @@ -205,8 +159,6 @@ def _module_fields(module) -> list[tuple[str, Any, str, bool]]: fields.append(('name_module_input', module.name_module_input, 'str', False)) if _is_attr_set(module, 'input_reused'): fields.append(('input_reused', module.input_reused, 'bool', False)) - # permute_in/out are bools in the metamodel; gate by explicit-set so - # a user-toggled False also round-trips back to the editor. if _is_attr_set(module, 'permute_in'): fields.append(('permute_in', module.permute_in, 'bool', False)) if _is_attr_set(module, 'permute_out'): @@ -240,9 +192,6 @@ def _module_fields(module) -> list[tuple[str, Any, str, bool]]: fields.append(('name_module_input', module.name_module_input, 'str', False)) if _is_attr_set(module, 'input_reused'): fields.append(('input_reused', module.input_reused, 'bool', False)) - # Pooling inherits permute_in / permute_out from Layer too (the - # processor reads them and the builder writes them). Mirror here so - # BUML→JSON preserves the user's choice on round-trip. if _is_attr_set(module, 'permute_in'): fields.append(('permute_in', module.permute_in, 'bool', False)) if _is_attr_set(module, 'permute_out'): @@ -513,7 +462,8 @@ def _configuration_fields(config: Configuration) -> list[tuple[str, Any, str, bo ('learning_rate', config.learning_rate, 'float', True), ('optimizer', config.optimizer, 'str', True), ('loss_function', config.loss_function, 'str', True), - ('metrics', config.metrics, 'List', True), + # Bare bracketed form, as the editor's metrics multiselect writes it. + ('metrics', '[' + ', '.join(config.metrics or []) + ']', 'List', True), ] if _is_attr_set(config, 'weight_decay') or ( config.weight_decay is not None and config.weight_decay != 0 @@ -543,203 +493,179 @@ def _dataset_fields(dataset: Dataset) -> list[tuple[str, Any, str, bool]]: return fields -def _emit_module(module, owner_id: str, x: int, y: int, - elements: dict[str, dict[str, Any]]) -> str: - """Create a layer/tensor_op element (with its attribute children) inside a container.""" - cls = type(module).__name__ - try: - parent_type, suffix = _MODULE_TYPE_MAP[cls] - except KeyError as exc: - raise ValueError( - f"Cannot emit module of type {cls!r}: no mapping to frontend " - f"element type. Add {cls!r} to _MODULE_TYPE_MAP." - ) from exc - element_id = _element_id(module) - attr_ids: list[str] = [] - - attr_bounds = {'x': x, 'y': y, 'width': 210, 'height': 20} - for field, value, attr_type_hint, mandatory in _module_fields(module): - attr = _make_attr(element_id, field, value, suffix, attr_bounds, - attr_type_hint=attr_type_hint, mandatory=mandatory) - elements[attr['id']] = attr - attr_ids.append(attr['id']) - - elements[element_id] = { - 'id': element_id, - 'name': parent_type, - 'type': parent_type, - 'owner': owner_id, - 'bounds': {'x': x, 'y': y, 'width': 110, 'height': 110}, - 'attributes': attr_ids, - 'methods': [], - } - return element_id +def _attrs_dict(fields: list[tuple[str, Any, str, bool]], layer_kind: str | None = None) -> dict: + """Collapse the field list into the v4 ``data.attributes`` dict. + + Some attribute slugs collide across layer kinds (e.g. ``dimension`` lives + on both PoolingLayer and BatchNormalizationLayer with different semantics). + The frontend disambiguates via ``qualifySlug(layerKind, slug)``; mirror the + same prefix when emitting so v4 round-trips on both sides. + """ + out: dict = {} + prefix = _LAYER_KIND_PREFIX.get(layer_kind or '') + for field_name, value, _hint, _mandatory in fields: + key = f'{prefix}.{field_name}' if (prefix is not None and field_name in _COLLIDING_SLUGS) else field_name + out[key] = _fmt_value(value) + return out + + +# Keep in sync with json_to_buml/nn_diagram_processor.py and the frontend +# qualifySlug() helper. +_COLLIDING_SLUGS = frozenset({'dimension'}) +_LAYER_KIND_PREFIX = { + 'PoolingLayer': 'pooling', + 'BatchNormalizationLayer': 'batch_normalization', +} -def _emit_container(name: str, x: int, y: int, width: int, height: int, - elements: dict[str, dict[str, Any]], - input_var: str | None = None, - return_vars: list[str] | None = None, - nn: NN | None = None) -> str: +def _emit_module_node(module, parent_id: str, x: int, y: int, nodes: list) -> str: + cls = type(module).__name__ + parent_type = _MODULE_TYPE_MAP.get(cls) + if parent_type is None: + raise ValueError( + f"Cannot emit module of type {cls!r}: no mapping to v4 node type." + ) + node_id = _element_id(module) + attrs = _attrs_dict(_module_fields(module), layer_kind=parent_type) + nodes.append(make_node( + node_id=node_id, + type_=parent_type, + data={"name": module.name, "attributes": attrs}, + position={"x": x, "y": y}, + parent_id=parent_id, + width=110, + height=110, + )) + return node_id + + +def _emit_container_node(name: str, x: int, y: int, width: int, height: int, nodes: list, + input_var: str | None = None, + return_vars: list[str] | None = None, + nn: NN | None = None) -> str: container_id = _element_id(nn) - container_dict = { - 'id': container_id, - 'name': name, - 'type': 'NNContainer', - 'owner': None, - 'bounds': {'x': x, 'y': y, 'width': width, 'height': height}, - } + data: dict[str, Any] = {"name": name} + # The NN's forward signature (NN.input_var / NN.return_vars) lives on the + # container node: ``data.input_var`` (str), ``data.return_vars`` (list). if input_var: - container_dict['input_var'] = input_var + data["input_var"] = input_var if return_vars: - container_dict['return_vars'] = return_vars - elements[container_id] = container_dict + data["return_vars"] = list(return_vars) + nodes.append(make_node( + node_id=container_id, + type_="NNContainer", + data=data, + position={"x": x, "y": y}, + width=width, + height=height, + )) return container_id -def _emit_nn_reference(ref_name: str, owner_id: str, x: int, y: int, - elements: dict[str, dict[str, Any]]) -> str: +def _emit_nn_reference_node(ref_name: str, target_id: str, parent_id: str, x: int, y: int, + nodes: list) -> str: + """``referenceTarget`` is the referenced container's node id, as the editor stores it.""" ref_id = _new_id() - elements[ref_id] = { - 'id': ref_id, - 'name': ref_name, - 'type': 'NNReference', - 'owner': owner_id, - 'bounds': {'x': x, 'y': y, 'width': 110, 'height': 110}, - 'referencedNN': ref_name, - } + nodes.append(make_node( + node_id=ref_id, + type_="NNReference", + data={"name": ref_name, "referenceTarget": target_id}, + position={"x": x, "y": y}, + parent_id=parent_id, + width=110, + height=110, + )) return ref_id -def _emit_nnnext(source_id: str, target_id: str, - relationships: dict[str, dict[str, Any]]) -> None: - rel_id = _new_id() - relationships[rel_id] = { - 'id': rel_id, - 'name': 'next', - 'type': 'NNNext', - 'owner': None, - 'bounds': {'x': 0, 'y': 0, 'width': 30, 'height': 31}, - 'path': [{'x': 0, 'y': 0}, {'x': 30, 'y': 0}], - 'source': {'direction': 'Right', 'element': source_id, 'multiplicity': '', 'role': ''}, - 'target': {'direction': 'Left', 'element': target_id, 'multiplicity': '', 'role': ''}, - 'isManuallyLayouted': False, - } - - -def _emit_container_link(rel_type: str, source_id: str, target_id: str, - relationships: dict[str, dict[str, Any]]) -> None: - """Emit an NNComposition or NNAssociation edge from an unowned element to the main NN container. - - Used to wire Configuration → container (composition) and Dataset → - container (association); without these the round-trip drops the - visual edges between the NN and its training/test data and config. - """ - rel_id = _new_id() - relationships[rel_id] = { - 'id': rel_id, - 'name': '', - 'type': rel_type, - 'owner': None, - 'bounds': {'x': 0, 'y': 0, 'width': 10, 'height': 100}, - 'path': [{'x': 5, 'y': 100}, {'x': 5, 'y': 0}], - 'source': {'direction': 'Up', 'element': source_id, 'multiplicity': '', 'role': ''}, - 'target': {'direction': 'Down', 'element': target_id, 'multiplicity': '', 'role': ''}, - 'isManuallyLayouted': False, - } - - -def _emit_configuration(config: Configuration, x: int, y: int, - elements: dict[str, dict[str, Any]]) -> str: - element_id = _new_id() - attr_ids: list[str] = [] - attr_bounds = {'x': x, 'y': y, 'width': 210, 'height': 20} - for field, value, attr_type_hint, mandatory in _configuration_fields(config): - attr = _make_attr(element_id, field, value, 'Configuration', attr_bounds, - attr_type_hint=attr_type_hint, mandatory=mandatory) - elements[attr['id']] = attr - attr_ids.append(attr['id']) - elements[element_id] = { - 'id': element_id, - 'name': 'Configuration', - 'type': 'Configuration', - 'owner': None, - 'bounds': {'x': x, 'y': y, 'width': 160, 'height': 200}, - 'attributes': attr_ids, - 'methods': [], - } - return element_id - - -def _emit_dataset(dataset: Dataset, parent_type: str, x: int, y: int, - elements: dict[str, dict[str, Any]]) -> str: - element_id = _element_id(dataset) - attr_ids: list[str] = [] - attr_bounds = {'x': x, 'y': y, 'width': 210, 'height': 20} - for field, value, attr_type_hint, mandatory in _dataset_fields(dataset): - attr = _make_attr(element_id, field, value, 'Dataset', attr_bounds, - attr_type_hint=attr_type_hint, mandatory=mandatory) - elements[attr['id']] = attr - attr_ids.append(attr['id']) - elements[element_id] = { - 'id': element_id, - 'name': parent_type, - 'type': parent_type, - 'owner': None, - 'bounds': {'x': x, 'y': y, 'width': 110, 'height': 110}, - 'attributes': attr_ids, - 'methods': [], - } - return element_id - - -def _emit_nn_container(nn: NN, y_base: int, - elements: dict[str, dict[str, Any]], - relationships: dict[str, dict[str, Any]], +def _emit_nnnext(source_id: str, target_id: str, edges: list) -> None: + edges.append(make_edge( + edge_id=_new_id(), + source=source_id, + target=target_id, + type_="NNNext", + data={"name": "next", "points": []}, + )) + + +def _emit_container_link(rel_type: str, source_id: str, target_id: str, edges: list) -> None: + edges.append(make_edge( + edge_id=_new_id(), + source=source_id, + target=target_id, + type_=rel_type, + data={"points": []}, + source_handle="top", + target_handle="bottom", + )) + + +def _emit_configuration_node(config: Configuration, x: int, y: int, nodes: list) -> str: + node_id = _new_id() + attrs = _attrs_dict(_configuration_fields(config)) + nodes.append(make_node( + node_id=node_id, + type_="Configuration", + data={"name": "Configuration", "attributes": attrs}, + position={"x": x, "y": y}, + width=160, + height=200, + )) + return node_id + + +def _emit_dataset_node(dataset: Dataset, parent_type: str, x: int, y: int, nodes: list) -> str: + node_id = _element_id(dataset) + attrs = _attrs_dict(_dataset_fields(dataset)) + nodes.append(make_node( + node_id=node_id, + type_=parent_type, + data={"name": parent_type, "attributes": attrs}, + position={"x": x, "y": y}, + width=200, + height=120, + )) + return node_id + + +def _emit_nn_container(nn: NN, y_base: int, nodes: list, edges: list, sub_nn_ids: dict[int, str] | None = None) -> str: - """ - Emit a container holding the modules of a single NN. - Returns the container id. Lays out modules left-to-right with NNNext relationships. - """ step = 140 module_count = max(len(nn.modules), 1) width = 30 + module_count * step container_x = -width // 2 - # Convert return_vars from comma-separated string to list - return_vars_list = [v.strip() for v in nn.return_vars.split(",")] if nn.return_vars else None - container_id = _emit_container(nn.name, container_x, y_base, - width=width, height=250, elements=elements, - input_var=nn.input_var if nn.input_var else None, - return_vars=return_vars_list, nn=nn) + # NN.return_vars is a comma-separated string; the editor stores a list. + return_vars_list = ( + [v.strip() for v in nn.return_vars.split(",") if v.strip()] + if nn.return_vars else None + ) + container_id = _emit_container_node( + nn.name, container_x, y_base, width, 250, nodes, + input_var=nn.input_var or None, + return_vars=return_vars_list, + nn=nn, + ) prev_id: str | None = None for i, module in enumerate(nn.modules): - x = container_x + 20 + i * step - y = y_base + 60 + # Relative to the container (``parentId``), left to right inside it. + x = 20 + i * step + y = 60 module_type = type(module).__name__ - # Pass sub_nn_ids through even when we recurse into a sub-NN's own - # container, so nested ``NN``-in-``modules`` entries route to - # _emit_nn_reference instead of _emit_module (which would KeyError - # on ``_MODULE_TYPE_MAP['NN']``). Keyed by id(module), not name — - # two sibling sub-NNs with identical display names are still distinct - # objects and must resolve to their own containers. if module_type == 'NN' and sub_nn_ids and id(module) in sub_nn_ids: - element_id = _emit_nn_reference(module.name, container_id, x, y, elements) + element_id = _emit_nn_reference_node( + module.name, sub_nn_ids[id(module)], container_id, x, y, nodes, + ) else: - element_id = _emit_module(module, container_id, x, y, elements) + element_id = _emit_module_node(module, container_id, x, y, nodes) if prev_id is not None: - _emit_nnnext(prev_id, element_id, relationships) + _emit_nnnext(prev_id, element_id, edges) prev_id = element_id return container_id def _collect_all_sub_nns(nn_model: NN) -> list: - """Return every transitively-reachable sub-NN in DFS post-order. - - Ensures deeply nested NNReferences (A → B → C) resolve — each level gets - its own container emitted, not just the top-level sub_nns list. - """ ordered: list = [] seen: set = set() @@ -756,71 +682,52 @@ def _visit(node: NN) -> None: def nn_model_to_json(nn_model: NN) -> dict[str, Any]: - """ - Convert a BUML NN instance into a web-editor NNDiagram model dict - (the inner `model` payload). - """ + """Convert a BUML NN instance into the v4 NNDiagram model dict.""" # Deterministic IDs: reset the per-conversion counter so the same input - # produces the same JSON bytes on every call (helpful for round-trip tests - # and for diffing BUML-to-JSON output). + # produces the same JSON bytes on every call. _reset_id_state() - elements: dict[str, dict[str, Any]] = {} - relationships: dict[str, dict[str, Any]] = {} - - # Emit every transitively-reachable sub-NN, not just the top-level list. - # The processor traverses NNReferences at any depth; we must emit a - # container for each one or the resulting NNReferences in deeper - # containers won't resolve on round-trip. - # Keyed by id(sub_nn) — two sibling sub-NNs with the same display name - # are still distinct objects; keying by name would let the second - # overwrite the first and silently reroute references (mirrors the - # iter-7 id-based bookkeeping in nn_model_builder). + nodes: list = [] + edges: list = [] + + # Emit every transitively-reachable sub-NN, not just the top-level list; + # keyed by id(sub_nn) so two sibling sub-NNs with the same display name + # stay distinct. sub_nn_ids: dict[int, str] = {} y_cursor = -700 for sub_nn in _collect_all_sub_nns(nn_model): - # Build sub_nn_ids incrementally so a sub-NN's own container can - # reference deeper sub-NNs already emitted. - cid = _emit_nn_container(sub_nn, y_cursor, elements, relationships, sub_nn_ids=sub_nn_ids) + cid = _emit_nn_container(sub_nn, y_cursor, nodes, edges, sub_nn_ids=sub_nn_ids) sub_nn_ids[id(sub_nn)] = cid y_cursor += 300 - # Main container - main_container_id = _emit_nn_container(nn_model, y_cursor, elements, relationships, sub_nn_ids=sub_nn_ids) + main_container_id = _emit_nn_container(nn_model, y_cursor, nodes, edges, sub_nn_ids=sub_nn_ids) - # Configuration (unowned, placed to the right) — composed into the main NN if nn_model.configuration is not None: - config_id = _emit_configuration(nn_model.configuration, x=700, y=y_cursor, elements=elements) - _emit_container_link('NNComposition', config_id, main_container_id, relationships) + config_id = _emit_configuration_node(nn_model.configuration, 700, y_cursor, nodes) + _emit_container_link('NNComposition', config_id, main_container_id, edges) - # Datasets (unowned, placed below) — associated with the main NN ds_x = -400 ds_y = y_cursor + 350 if getattr(nn_model, 'train_data', None) is not None: - train_id = _emit_dataset(nn_model.train_data, 'TrainingDataset', ds_x, ds_y, elements) - _emit_container_link('NNAssociation', train_id, main_container_id, relationships) + train_id = _emit_dataset_node(nn_model.train_data, 'TrainingDataset', ds_x, ds_y, nodes) + _emit_container_link('NNAssociation', train_id, main_container_id, edges) ds_x += 300 if getattr(nn_model, 'test_data', None) is not None: - test_id = _emit_dataset(nn_model.test_data, 'TestDataset', ds_x, ds_y, elements) - _emit_container_link('NNAssociation', test_id, main_container_id, relationships) + test_id = _emit_dataset_node(nn_model.test_data, 'TestDataset', ds_x, ds_y, nodes) + _emit_container_link('NNAssociation', test_id, main_container_id, edges) return { - 'version': '3.0.0', - 'type': 'NNDiagram', - 'size': {'width': 1520, 'height': 800}, - 'interactive': {'elements': {}, 'relationships': {}}, - 'elements': elements, - 'relationships': relationships, - 'assessments': {}, + "version": "4.0.0", + "type": "NNDiagram", + "title": "", + "size": {"width": 1520, "height": 800}, + "nodes": nodes, + "edges": edges, + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {}, } def _nn_add_method_whitelist(): - """Instance methods callable at top level on an already-constructed value. - - Kept narrow on purpose: only the add_* builder methods and a couple of - harmless configuration setters. Anything else (e.g. ``__class__`` - traversals or ``os.system``) is rejected by the AST visitor. - """ return { 'add_layer', 'add_tensor_op', 'add_sub_nn', 'add_configuration', 'add_train_data', 'add_test_data', @@ -828,27 +735,7 @@ def _nn_add_method_whitelist(): def _parse_nn_buml_ast(content: str, nn_module): - """Safely reconstruct an NN model from Python-looking BUML. - - Replaces the previous ``exec()``-based parser with an ``ast.parse`` + - whitelist visitor. Only a handful of top-level statement shapes survive: - - - ``import …`` / ``from … import …`` — skipped (metamodel names - are resolved from ``nn_module`` directly via the allowlist) - - ``name = `` — simple-target assignment - - ``obj.add_*(…)`` — builder method call - - And only these expression shapes are evaluable: Constant, Name (bound - to a prior assignment OR to a whitelisted metamodel class), List / - Tuple / Dict of allowed expressions, unary minus, and Call where the - callable is a whitelisted class. - - This stops the classic sandbox escape ``().__class__.__bases__[0] - .__subclasses__()`` because ``Attribute`` access on arbitrary values - is not evaluable — only the ``x.add_*(…)`` top-level method-call - pattern reaches ``getattr``, and the method name itself is - whitelisted. - """ + """Safely reconstruct an NN model from Python-looking BUML.""" allowed_classes = { name: getattr(nn_module, name) for name in dir(nn_module) if not name.startswith('_') @@ -875,7 +762,6 @@ def _eval(node, env): ) return [_eval(e, env) for e in node.elts] if isinstance(node, ast.Dict): - # ``{**other}`` encodes as a Dict whose key is ``None``. for k in node.keys: if k is None: raise ValueError( @@ -893,9 +779,6 @@ def _eval(node, env): ) return {_eval(e, env) for e in node.elts} if isinstance(node, ast.Call): - # Only allow calls whose callable is a whitelisted metamodel - # class — reject every attribute-based call (``foo.bar(…)``) - # except in the statement-level ``obj.add_*`` dispatcher below. if not isinstance(node.func, ast.Name): raise ValueError( "Only calls to whitelisted NN metamodel classes are " @@ -907,21 +790,15 @@ def _eval(node, env): raise ValueError( f"Call to non-whitelisted class {node.func.id!r}" ) - # Reject ``*args`` / ``**kwargs`` splats explicitly so an obscure - # downstream "missing required argument" doesn't hide what the - # visitor is refusing. The previous silent-drop behavior meant - # ``Conv2D(**malicious_dict)`` produced a cryptic metamodel error. for a in node.args: if isinstance(a, ast.Starred): raise ValueError( - "Positional *args unpacking is not supported in NN BUML; " - "pass arguments explicitly." + "Positional *args unpacking is not supported in NN BUML; pass arguments explicitly." ) for kw in node.keywords: if kw.arg is None: raise ValueError( - "**kwargs unpacking is not supported in NN BUML; " - "pass keyword arguments explicitly." + "**kwargs unpacking is not supported in NN BUML; pass keyword arguments explicitly." ) args = [_eval(a, env) for a in node.args] kwargs = {kw.arg: _eval(kw.value, env) for kw in node.keywords} @@ -932,28 +809,20 @@ def _eval(node, env): def _run_stmt(stmt, env): if isinstance(stmt, (ast.Import, ast.ImportFrom)): - return # silently skipped; all metamodel names are already in scope + return if isinstance(stmt, ast.Assign): - # Validate targets BEFORE evaluating value, so an attribute-target - # assignment (``obj.x = ...``) is rejected without running the - # right-hand side (which might construct an NN object with side - # effects). for target in stmt.targets: if not isinstance(target, ast.Name): raise ValueError( - "Only simple-name assignment targets are allowed " - "in NN BUML." + "Only simple-name assignment targets are allowed in NN BUML." ) value = _eval(stmt.value, env) for target in stmt.targets: env[target.id] = value return if isinstance(stmt, ast.Expr): - # Top-level expression — most commonly an ``obj.add_*(…)`` - # builder call. Docstrings and other bare expressions are - # ignored. if isinstance(stmt.value, ast.Constant): - return # docstring or stray literal + return if isinstance(stmt.value, ast.Call) and \ isinstance(stmt.value.func, ast.Attribute) and \ isinstance(stmt.value.func.value, ast.Name): @@ -966,14 +835,12 @@ def _run_stmt(stmt, env): for a in stmt.value.args: if isinstance(a, ast.Starred): raise ValueError( - "Positional *args unpacking is not supported in " - "NN BUML add_* builder calls." + "Positional *args unpacking is not supported in NN BUML add_* builder calls." ) for kw in stmt.value.keywords: if kw.arg is None: raise ValueError( - "**kwargs unpacking is not supported in NN BUML " - "add_* builder calls." + "**kwargs unpacking is not supported in NN BUML add_* builder calls." ) target = _eval(stmt.value.func.value, env) args = [_eval(a, env) for a in stmt.value.args] @@ -1013,11 +880,6 @@ def nn_buml_to_json(content: str) -> dict[str, Any]: if not all_nns: raise ValueError("No NN instance found in the NN BUML content") - # Build the `referenced` set transitively — every NN that appears anywhere - # in any NN's sub_nns tree, not just direct children. Without this, a - # grandchild sub-NN bound to a local variable (``c = NN(...)`` inside a - # BUML file where only ``a.add_sub_nn(b); b.add_sub_nn(c)`` appears) - # would be counted as top-level and trigger the multi-top-level error. referenced: set = set() _walk_stack = list(all_nns) while _walk_stack: @@ -1029,8 +891,6 @@ def nn_buml_to_json(content: str) -> dict[str, Any]: _walk_stack.append(sub) main_nns = [nn for nn in all_nns if id(nn) not in referenced] if len(main_nns) > 1: - # Symmetric with the processor (which already rejects this case); - # silently picking one of several top-level NNs is surprising. names = ', '.join(sorted(n.name for n in main_nns)) raise ValueError( f"NN BUML contains {len(main_nns)} top-level NN instances " @@ -1038,8 +898,6 @@ def nn_buml_to_json(content: str) -> dict[str, Any]: f"add_sub_nn(...) to mark them as sub-networks." ) if not main_nns: - # Every NN is referenced by another → cyclic; the processor raises - # the same way, keep the messages aligned. raise ValueError( "NN BUML has no top-level NN: every NN instance is referenced " "as a sub-network by another. Remove one of the add_sub_nn " diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/object_diagram_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/object_diagram_converter.py index da182dc00..2ab209c4b 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/object_diagram_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/object_diagram_converter.py @@ -1,6 +1,7 @@ """ -Object converter module for BUML to JSON conversion. -Handles object diagram processing and attribute mapping. +Object converter module for BUML to v4 JSON. + +Emits the v4 wire shape (``{nodes, edges}``) directly. """ import ast @@ -8,22 +9,19 @@ import uuid from typing import Dict, Any, List -logger = logging.getLogger(__name__) - from besser.utilities.buml_code_builder.common import safe_class_name -from besser.utilities.web_modeling_editor.backend.services.utils import ( - determine_connection_direction, calculate_connection_points, - calculate_path_points, calculate_relationship_bounds +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._node_builders import ( + make_node, make_edge, grid_layout, ) +logger = logging.getLogger(__name__) -#: Element types per diagram type: (object element, attribute element). -#: A UserDiagram is an object diagram over the user reference domain model; the -#: editor gives its objects and criteria their own element types, which -#: ``json_to_buml.object_diagram_processor`` reads back the same way. -_ELEMENT_TYPES = { - "ObjectDiagram": ("ObjectName", "ObjectAttribute"), - "UserDiagram": ("UserModelName", "UserModelAttribute"), +#: (object node type, link edge type) per diagram type. A UserDiagram is an +#: object diagram over the user reference domain model; +#: ``json_to_buml.object_diagram_processor`` reads both back the same way. +_NODE_TYPES = { + "ObjectDiagram": ("objectName", "ObjectLink"), + "UserDiagram": ("UserModelName", "UserModelLink"), } @@ -53,100 +51,86 @@ def _attribute_value(node: ast.AST): return None +def _resolve_class_index(domain_json: Dict[str, Any]): + """Build {class_name: node_id} and {node_id: {attr_name: meta}} from a v4 reference diagram.""" + class_name_to_id: dict = {} + class_id_to_attributes: dict = {} + for node in (domain_json or {}).get("nodes") or []: + if node.get("type") != "class": + continue + data = node.get("data") or {} + stereotype = (data.get("stereotype") or "").strip().lower() + if stereotype in ("interface", "enumeration", "oclconstraint"): + continue + class_name_to_id[data.get("name", "")] = node.get("id") + # The code names a class as object_model_to_code does: Class_ for Class + class_name_to_id.setdefault(safe_class_name(data.get("name", "")), node.get("id")) + attrs: dict = {} + for attr in data.get("attributes") or []: + attrs[attr.get("name", "")] = { + "id": attr.get("id"), + "type": attr.get("attributeType", "str"), + "defaultValue": attr.get("defaultValue"), + "visibility": attr.get("visibility", "public"), + } + class_id_to_attributes[node.get("id")] = attrs + return class_name_to_id, class_id_to_attributes + + +_CLASS_ASSOCIATION_EDGE_TYPES = ( + "ClassBidirectional", + "ClassUnidirectional", + "ClassAggregation", + "ClassComposition", +) + + +def _resolve_association_index(domain_json: Dict[str, Any]) -> list: + """List ``(edge_id, source_node_id, source_role, target_node_id, target_role)`` + for every v4 reference association edge that can host roles + (Bi/Uni/Aggregation/Composition).""" + out: list = [] + for edge in (domain_json or {}).get("edges") or []: + if edge.get("type") not in _CLASS_ASSOCIATION_EDGE_TYPES: + continue + d = edge.get("data") or {} + out.append(( + edge.get("id"), + edge.get("source"), d.get("sourceRole", "") or "", + edge.get("target"), d.get("targetRole", "") or "", + )) + return out + + def object_buml_to_json( content: str, domain_json: Dict[str, Any], diagram_type: str = "ObjectDiagram", ) -> Dict[str, Any]: + """Convert object model Python source to a v4 ``{nodes, edges}`` payload. + + ``diagram_type`` is ``"ObjectDiagram"`` (default) or ``"UserDiagram"``. A + UserDiagram uses ``UserModelName`` nodes whose rows are equality criteria + (``attributeOperator`` ``"=="``) and names each object's class in + ``className``; it carries no ``referenceDiagramData``, since the editor + supplies the user reference model itself. """ - Convert an object model Python file content to JSON format matching the frontend structure. - - Args: - content: Object model Python code as string - domain_json: Reference domain model JSON for class mapping - diagram_type: ``"ObjectDiagram"`` (default) or ``"UserDiagram"``. A - UserDiagram uses ``UserModelName`` / ``UserModelAttribute`` - elements (equality criteria, ``attributeOperator`` ``"=="``) and - names each object's class in ``className``; it carries no - ``referenceDiagramData``, since the editor supplies the user - reference model itself. - - Returns: - Dictionary representing the object diagram in JSON format - """ - if diagram_type not in _ELEMENT_TYPES: + if diagram_type not in _NODE_TYPES: raise ValueError(f"Unsupported object diagram type: {diagram_type}") is_user_diagram = diagram_type == "UserDiagram" - object_element_type, attribute_element_type = _ELEMENT_TYPES[diagram_type] - - elements = {} - relationships = {} - - # Default diagram size - default_size = {"width": 960, "height": 670} - - # Grid layout configuration for positioning objects - grid_size = { - "x_spacing": 250, - "y_spacing": 180, - "max_columns": 4, - } - - current_column = 0 - current_row = 0 - - def get_position(): - nonlocal current_column, current_row - x = -460 + (current_column * grid_size["x_spacing"]) - y = -300 + (current_row * grid_size["y_spacing"]) - - current_column += 1 - if current_column >= grid_size["max_columns"]: - current_column = 0 - current_row += 1 - - return x, y + object_node_type, link_edge_type = _NODE_TYPES[diagram_type] + nodes: list = [] + edges: list = [] try: - reference_diagram_json = domain_json - - # Create mapping from class names to class IDs in reference diagram - class_name_to_id = {} - class_id_to_attributes = {} - - for elem_id, elem in reference_diagram_json["elements"].items(): - if elem["type"] in ("Class", "AbstractClass"): - class_name_to_id[elem["name"]] = elem_id - # The code names a class as object_model_to_code does: Class_ for Class - class_name_to_id.setdefault(safe_class_name(elem["name"]), elem_id) - # Store class attributes for object attribute mapping - class_attributes = {} - for attr_id in elem.get("attributes", []): - if attr_id in reference_diagram_json["elements"]: - attr_elem = reference_diagram_json["elements"][attr_id] - # Extract attribute name (remove visibility and type info) - attr_name = attr_elem["name"].split(":")[0].strip().lstrip("+-#~") - # Get the type: new format has attributeType, legacy has it in the name - attr_type = attr_elem.get("attributeType") - if not attr_type: - # Legacy format: parse type from name like "+ name: type" - parts = attr_elem["name"].split(":") - attr_type = parts[1].strip() if len(parts) > 1 else "str" - attr_default = attr_elem.get("defaultValue") - attr_visibility = attr_elem.get("visibility", "public") - class_attributes[attr_name] = { - "id": attr_id, - "type": attr_type, - "defaultValue": attr_default, - "visibility": attr_visibility, - } - class_id_to_attributes[elem_id] = class_attributes - - # Superclasses per class (ClassInheritance: source = specific, target = general) + reference_diagram_json = domain_json or {} + class_name_to_id, class_id_to_attributes = _resolve_class_index(reference_diagram_json) + + # Superclasses per class (ClassInheritance: source = specific, target = general). parents_of: Dict[str, List[str]] = {} - for rel in reference_diagram_json["relationships"].values(): - if rel.get("type") == "ClassInheritance": - parents_of.setdefault(rel["source"]["element"], []).append(rel["target"]["element"]) + for edge in reference_diagram_json.get("edges") or []: + if edge.get("type") == "ClassInheritance": + parents_of.setdefault(edge.get("source"), []).append(edge.get("target")) def lineage(class_id: str) -> List[str]: """The class followed by all its ancestors, nearest first.""" @@ -170,7 +154,6 @@ def lineage(class_id: str) -> List[str]: for class_id in class_id_to_attributes } - # Parse the Python code to extract object instances try: tree = ast.parse(content) except SyntaxError as e: @@ -178,26 +161,19 @@ def lineage(class_id: str) -> List[str]: f"Failed to parse object model Python code: syntax error at line {e.lineno}: {e.msg}" ) from e - # Track objects and their information - objects_by_name = {} - object_class_mapping = {} - object_comments = {} # object_var -> comment_text - om_comment = None # ObjectModel metadata comment + objects_by_name: dict = {} + object_class_mapping: dict = {} + object_comments: dict = {} + om_comment = None - # Extract object instantiations using fluent API for node in ast.walk(tree): if isinstance(node, ast.Assign): for target in node.targets: if isinstance(target, ast.Name): var_name = target.id - - # Check if this is an object instantiation using fluent API if isinstance(node.value, ast.Call): - # Look for pattern: ClassName("ObjectName").attributes(...).build() call_chain = [] current = node.value - - # Walk back through the method chain while isinstance(current, ast.Call): if isinstance(current.func, ast.Attribute): call_chain.append(current.func.attr) @@ -207,34 +183,24 @@ def lineage(class_id: str) -> List[str]: break else: break - - # Reverse to get the correct order call_chain.reverse() - # Check if this matches the fluent pattern; an object - # without slots is just ClassName("ObjectName").build() + # An object without slots is ClassName("name").build(). if len(call_chain) >= 2 and call_chain[-1] == "build": class_name = call_chain[0] if class_name in class_name_to_id: - # Extract object name and attributes object_name = var_name object_instance_name = None attributes = {} - - # Get the initial call arguments for object name init_call = node.value while isinstance(init_call, ast.Call) and isinstance(init_call.func, ast.Attribute): init_call = init_call.func.value - if isinstance(init_call, ast.Call) and len(init_call.args) > 0: if isinstance(init_call.args[0], ast.Constant): object_instance_name = init_call.args[0].value - - # Find attributes call in the chain attr_call = node.value while isinstance(attr_call, ast.Call): if isinstance(attr_call.func, ast.Attribute) and attr_call.func.attr == "attributes": - # Extract attributes from keyword arguments for kw in attr_call.keywords: value = _attribute_value(kw.value) if value is not None: @@ -243,18 +209,14 @@ def lineage(class_id: str) -> List[str]: attr_call = attr_call.func.value if isinstance(attr_call.func, ast.Attribute) else None if not attr_call: break - objects_by_name[object_name] = { "class_name": class_name, "class_id": class_name_to_id[class_name], "instance_name": object_instance_name or object_name, - "attributes": attributes + "attributes": attributes, } object_class_mapping[object_name] = class_name - - # Check for ObjectModel instantiation with metadata elif call_chain and call_chain[0] == "ObjectModel": - # Extract ObjectModel metadata for kw in node.value.keywords: if kw.arg == "metadata": if isinstance(kw.value, ast.Call): @@ -267,10 +229,8 @@ def lineage(class_id: str) -> List[str]: "Could not evaluate ObjectModel metadata description: %s", e ) - # Check for object.classifier.metadata = Metadata(...) patterns target = node.targets[0] if isinstance(target, ast.Attribute) and target.attr == "metadata": - # This could be: obj.classifier.metadata = ... if isinstance(target.value, ast.Attribute) and target.value.attr == "classifier": obj_var = target.value.value.id if isinstance(target.value.value, ast.Name) else None if obj_var and isinstance(node.value, ast.Call): @@ -281,112 +241,93 @@ def lineage(class_id: str) -> List[str]: except (ValueError, TypeError) as e: logger.warning( "Could not evaluate object metadata description for '%s': %s", - obj_var, e + obj_var, e, ) - # Create object elements in JSON format - object_var_to_id = {} # object variable name -> element ID + # Emit object nodes. + object_var_to_node_id: dict = {} + object_nodes: list = [] for obj_name, obj_info in objects_by_name.items(): - x, y = get_position() object_id = str(uuid.uuid4()) - object_var_to_id[obj_name] = object_id - - # Create object attribute elements - object_attribute_ids = [] class_id = obj_info["class_id"] class_attributes = class_id_to_attributes.get(class_id, {}) - - attr_y_offset = 30 + attribute_rows: list = [] for attr_name, attr_value in obj_info["attributes"].items(): - attr_id = str(uuid.uuid4()) - object_attribute_ids.append(attr_id) - - # Format the value appropriately if isinstance(attr_value, str): formatted_value = attr_value else: formatted_value = str(attr_value) - - # Get the corresponding class attribute info if available class_attr_info = class_attributes.get(attr_name) - class_attr_id = class_attr_info["id"] if class_attr_info else None attr_type = class_attr_info["type"] if class_attr_info else "str" - - attr_element = { - "id": attr_id, - "name": f"{attr_name} = {formatted_value}", - "type": attribute_element_type, - "owner": object_id, - "bounds": { - "x": x + 0.5, - "y": y + attr_y_offset - 0.5, - "width": 199, - "height": 30 - }, - "attributeId": class_attr_id, + # v4 object rows keep the attribute name and runtime value + # in separate fields (``ObjectNodeAttribute.value``); the + # frontend renders "name = value" from the split fields. + # ``visibility`` + ``attributeType`` together keep the + # frontend's v3 round-trip from re-parsing the row and + # dropping the type. + row: dict = { + "id": str(uuid.uuid4()), + "name": attr_name, + "value": formatted_value, "attributeType": attr_type, + "visibility": (class_attr_info or {}).get("visibility") or "public", } + if class_attr_info and class_attr_info.get("id"): + row["attributeId"] = class_attr_info["id"] + if class_attr_info and class_attr_info.get("defaultValue") is not None: + row["defaultValue"] = class_attr_info["defaultValue"] if is_user_diagram: # A BUML slot is an equality criterion; the comparator of a # non-equality criterion ("age < 18") is not in the metamodel. - attr_element["attributeOperator"] = "==" - if class_attr_info and class_attr_info.get("defaultValue") is not None: - attr_element["defaultValue"] = class_attr_info["defaultValue"] - elements[attr_id] = attr_element - attr_y_offset += 30 - - # Calculate object height based on attributes - object_height = max(70, 40 + len(object_attribute_ids) * 30) - - object_element = { - "id": object_id, + row["attributeOperator"] = "==" + attribute_rows.append(row) + object_height = max(70, 40 + len(attribute_rows) * 30) + node_payload: dict = { "name": obj_info["instance_name"], - "type": object_element_type, - "owner": None, - "bounds": { - "x": x, - "y": y, - "width": 200, - "height": object_height - }, - "attributes": object_attribute_ids, + "classId": class_id, + "attributes": attribute_rows, "methods": [], - "classId": class_id } if is_user_diagram: # The editor resolves user-model classes from its own copy of - # the user metamodel, whose class IDs differ from the ones + # the user metamodel, whose class ids differ from the ones # generated here; the class name is the stable key. - object_element["classId"] = None - object_element["className"] = obj_info["class_name"] - elements[object_id] = object_element - - # Look for object links/relationships - associations = [ - (rel_id, rel.get("source", {}), rel.get("target", {})) - for rel_id, rel in reference_diagram_json["relationships"].items() - if rel["type"] in ["ClassBidirectional", "ClassUnidirectional", "ClassComposition", "ClassAggregation"] - ] + node_payload["classId"] = None + node_payload["className"] = obj_info["class_name"] + object_nodes.append(make_node( + node_id=object_id, + type_=object_node_type, + data=node_payload, + position={"x": 0, "y": 0}, + width=200, + height=object_height, + )) + object_var_to_node_id[obj_name] = object_id + grid_layout(object_nodes, origin=(-460, -300), columns=4, gap_x=50, gap_y=80) + nodes.extend(object_nodes) + + # Object links. + associations = _resolve_association_index(reference_diagram_json) def find_association(class_id: str, role: str): """The association whose far end is ``role`` and whose near end is the object's class or an ancestor; else any association with that end name.""" own = set(lineage(class_id)) if class_id else set() fallback = None - for rel_id, source, target in associations: - if (target.get("role") == role and source.get("element") in own) or ( - source.get("role") == role and target.get("element") in own + for edge_id, source_node, source_role, target_node, target_role in associations: + if (target_role == role and source_node in own) or ( + source_role == role and target_node in own ): - return rel_id - if fallback is None and role in (source.get("role"), target.get("role")): - fallback = rel_id + return edge_id + if fallback is None and role in (source_role, target_role): + fallback = edge_id return fallback for node in ast.walk(tree): if not isinstance(node, ast.Assign): continue - # Look for assignments like: obj1.end = obj2 (or {obj2, obj3} for a - # to-many end, as object_model_to_code writes them) + # obj1.end = obj2, or {obj2, obj3} for a to-many end (as + # object_model_to_code writes them). if isinstance(node.value, ast.Name): target_vars = [node.value.id] elif isinstance(node.value, (ast.Set, ast.List, ast.Tuple)): @@ -397,149 +338,72 @@ def find_association(class_id: str, role: str): if not isinstance(target, ast.Attribute): continue obj_name = target.value.id if isinstance(target.value, ast.Name) else None - relationship_name = target.attr - source_id = object_var_to_id.get(obj_name) + source_id = object_var_to_node_id.get(obj_name) if not source_id: continue - + relationship_name = target.attr assoc_id = find_association(objects_by_name[obj_name]["class_id"], relationship_name) - for target_obj in target_vars: - target_id = object_var_to_id.get(target_obj) + target_id = object_var_to_node_id.get(target_obj) if not target_id: continue - rel_id = str(uuid.uuid4()) - relationships[rel_id] = { - "id": rel_id, - "name": f"{relationship_name}", - "type": "ObjectLink", - "owner": None, - "bounds": { - "x": -260, - "y": -315, - "width": 300, - "height": 80 - }, - "path": [ - {"x": 0, "y": 80}, - {"x": 40, "y": 80}, - {"x": 40, "y": 0}, - {"x": 300, "y": 0}, - {"x": 300, "y": 65} - ], - "source": { - "direction": "Right", - "element": source_id + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=source_id, + target=target_id, + type_=link_edge_type, + data={ + "name": relationship_name, + "associationId": assoc_id, + "points": [], }, - "target": { - "direction": "Topleft", - "element": target_id - }, - "isManuallyLayouted": False, - "associationId": assoc_id - } + source_handle="right", + target_handle="top-left", + )) - # Position for comments + # Comments (``comment`` nodes + ``CommentLink`` edges — the types + # the React Flow frontend registers). comment_x = -970 comment_y = -300 - - # Create comment elements from metadata - # 1. ObjectModel comment (unlinked) if om_comment: - comment_id = str(uuid.uuid4()) - elements[comment_id] = { - "id": comment_id, - "name": om_comment, - "type": "Comments", - "owner": None, - "bounds": { - "x": comment_x, - "y": comment_y, - "width": 200, - "height": 100, - }, - } + nodes.append(make_node( + node_id=str(uuid.uuid4()), + type_="comment", + data={"name": om_comment}, + position={"x": comment_x, "y": comment_y}, + width=200, + height=100, + )) comment_y += 130 - # 2. Object comments (linked to objects) for obj_var, comment_text in object_comments.items(): - if obj_var in object_var_to_id: + if obj_var in object_var_to_node_id: comment_id = str(uuid.uuid4()) - object_id = object_var_to_id[obj_var] - - elements[comment_id] = { - "id": comment_id, - "name": comment_text, - "type": "Comments", - "owner": None, - "bounds": { - "x": comment_x, - "y": comment_y, - "width": 200, - "height": 100, - }, - } - - # Create Link relationship - link_id = str(uuid.uuid4()) - source_element = elements[comment_id] - target_element = elements[object_id] - - source_dir, target_dir = determine_connection_direction( - source_element["bounds"], target_element["bounds"] - ) - - source_point = calculate_connection_points( - source_element["bounds"], source_dir - ) - target_point = calculate_connection_points( - target_element["bounds"], target_dir - ) - - path_points = calculate_path_points( - source_point, target_point, source_dir, target_dir - ) - rel_bounds = calculate_relationship_bounds(path_points) - - relationships[link_id] = { - "id": link_id, - "name": "", - "type": "Link", - "owner": None, - "bounds": rel_bounds, - "path": path_points, - "source": { - "direction": source_dir, - "element": comment_id, - "bounds": { - "x": source_point["x"], - "y": source_point["y"], - "width": 0, - "height": 0, - }, - }, - "target": { - "direction": target_dir, - "element": object_id, - "bounds": { - "x": target_point["x"], - "y": target_point["y"], - "width": 0, - "height": 0, - }, - }, - "isManuallyLayouted": False, - } - + nodes.append(make_node( + node_id=comment_id, + type_="comment", + data={"name": comment_text}, + position={"x": comment_x, "y": comment_y}, + width=200, + height=100, + )) + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=comment_id, + target=object_var_to_node_id[obj_var], + type_="CommentLink", + data={"points": []}, + )) comment_y += 130 result = { - "version": "3.0.0", + "version": "4.0.0", "type": diagram_type, - "size": default_size, + "title": "", + "size": {"width": 960, "height": 670}, + "nodes": nodes, + "edges": edges, "interactive": {"elements": {}, "relationships": {}}, - "elements": elements, - "relationships": relationships, "assessments": {}, } if not is_user_diagram: diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/project_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/project_converter.py index 3fa6fecf4..8a6b15663 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/project_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/project_converter.py @@ -5,6 +5,7 @@ """ import ast +import json import logging import uuid import re @@ -17,13 +18,13 @@ from besser.utilities.web_modeling_editor.backend.services.exceptions import ConversionError from .class_diagram_converter import parse_buml_content, class_buml_to_json +from .bpmn_diagram_converter import bpmn_buml_to_json from .state_machine_converter import state_machine_to_json from .agent_diagram_converter import agent_buml_to_json from .object_diagram_converter import object_buml_to_json from .gui_diagram_converter import gui_buml_to_json from .quantum_diagram_converter import quantum_buml_to_json from .nn_diagram_converter import nn_buml_to_json -from .bpmn_diagram_converter import bpmn_buml_to_json from .kg_diagram_converter import kg_buml_to_json from .component_diagram_converter import component_buml_to_json from .deployment_diagram_converter import deployment_buml_to_json @@ -57,6 +58,8 @@ r'^user_object_model(?:_\d+)?\s*(?::[^=\n]*)?=(?!=)', re.MULTILINE, ) _OBJECT_MODEL_NAME = re.compile(r'ObjectModel\(\s*name\s*=\s*"((?:[^"\\]|\\.)*)"') + + def _parse_user_reference_section(section_code: str) -> Optional[DomainModel]: """Return the parsed model if a STRUCTURAL section is the user reference domain model, else ``None``. @@ -73,6 +76,17 @@ def _parse_user_reference_section(section_code: str) -> Optional[DomainModel]: return domain_model if is_user_reference_domain_model(domain_model) else None +def _string_kwarg(prefix: str, code: str) -> str: + """The string literal after `` = `` in ``code`` (escapes decoded), or ''.""" + match = re.search(prefix + r'\s*=\s*"((?:[^"\\]|\\.)*)"', code) + if not match: + return "" + try: + return ast.literal_eval(f'"{match.group(1)}"') + except (ValueError, SyntaxError): + return match.group(1) + + def _object_model_title(section_code: str) -> str: """Return the ``ObjectModel(name=...)`` of an object section, or ''.""" match = _OBJECT_MODEL_NAME.search(section_code) @@ -84,6 +98,64 @@ def _object_model_title(section_code: str) -> str: return match.group(1) +# Written by project_builder in the PROJECT DEFINITION section. +_DIAGRAM_ID_LINE = re.compile(r'^# diagram-id (\w+): (".*")\s*$', re.MULTILINE) +_DIAGRAM_TITLE_LINE = re.compile(r'^# diagram-title (\w+): (".*")\s*$', re.MULTILINE) +_DIAGRAM_REFERENCES_LINE = re.compile(r'^# diagram-references (\w+): (\{.*\})\s*$', re.MULTILINE) +_CLASS_IDS_LINE = re.compile(r'^# class-ids (\{.*\})\s*$', re.MULTILINE) +_PROJECT_NAME_LINE = re.compile(r'^# project-name (".*")\s*$', re.MULTILINE) + + +def _project_display_name(definition: str) -> Optional[str]: + """The editor's project name, recorded when the B-UML name had to be sanitised.""" + match = _PROJECT_NAME_LINE.search(definition) + if not match: + return None + try: + name = json.loads(match.group(1)) + except ValueError: + return None + return name if isinstance(name, str) else None + + +def _parse_recorded_values(pattern: re.Pattern, content: str, value_type: type = str) -> Dict[str, list]: + """``{diagram type: [value, ...]}`` from ``# : `` lines, in order.""" + values: Dict[str, list] = {} + for diagram_type, raw_value in pattern.findall(content): + try: + value = json.loads(raw_value) + except ValueError: + continue + if isinstance(value, value_type): + values.setdefault(diagram_type, []).append(value) + return values + + +def _parse_editor_ids(content: str) -> Tuple[Dict[str, List[str]], Dict[str, Dict[str, str]]]: + """Read the web editor ids a project export carries. + + Returns ``(diagram ids per diagram type, in section order; + {class diagram id: {class name: class node id}})``. Malformed lines are ignored. + """ + diagram_ids = _parse_recorded_values(_DIAGRAM_ID_LINE, content) + class_ids: Dict[str, Dict[str, str]] = {} + match = _CLASS_IDS_LINE.search(content) + if match: + try: + parsed = json.loads(match.group(1)) + except ValueError: + parsed = {} + if isinstance(parsed, dict): + class_ids = {k: v for k, v in parsed.items() if isinstance(v, dict)} + return diagram_ids, class_ids + + +def _ids_for(diagram_ids: Dict[str, List[str]], diagram_type: str, count: int) -> List[Optional[str]]: + """The recorded ids of ``diagram_type``, or Nones when they do not line up with the sections.""" + ids = diagram_ids.get(diagram_type) or [] + return list(ids) if len(ids) == count else [None] * count + + # All known section header keywords used as boundary markers ALL_SECTION_KEYWORDS = [ 'STRUCTURAL', 'OBJECT', 'AGENT', 'GUI', 'QUANTUM', 'STATE MACHINE', 'NN', @@ -92,16 +164,11 @@ def _object_model_title(section_code: str) -> str: def empty_model(diagram_type: str) -> Dict[str, Any]: - """ - Create an empty model template for the specified diagram type. + """Create an empty model template for the given diagram type. - Args: - diagram_type: Type of diagram to create empty model for - - Returns: - Dictionary representing empty model structure + Returns the v4 wire shape (``{nodes, edges}``) for BESSER WME-driven + diagrams; ``GUINoCodeDiagram`` keeps its bespoke shape. """ - # GUINoCodeDiagram has a different structure with pages instead of elements if diagram_type == "GUINoCodeDiagram": return { "version": "3.0.0", @@ -123,11 +190,11 @@ def empty_model(diagram_type: str) -> Dict[str, Any]: } return { - "version": "3.0.0", + "version": "4.0.0", "type": diagram_type, "size": {"width": 1400, "height": 740}, - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], "interactive": {"elements": {}, "relationships": {}}, "assessments": {} } @@ -237,6 +304,9 @@ def _convert_section( domain_sections: List[Tuple[str, str]], class_diagram_list: List[Dict[str, Any]], user_reference_json: Dict[str, Any] = None, + diagram_id: Optional[str] = None, + class_ids: Optional[Dict[str, str]] = None, + references: Optional[Dict[str, str]] = None, warnings: Optional[List[str]] = None, ) -> Dict[str, Any]: """ @@ -250,6 +320,9 @@ def _convert_section( class_diagram_list: Already-converted class diagrams (needed for object diagram references) user_reference_json: The user reference domain model as class-diagram JSON (needed for ``user_object_model`` sections) + diagram_id: The diagram's editor id, kept when the export recorded it + class_ids: ``{class name: class node id}`` recorded for a class diagram + references: the editor ``references`` recorded for an object diagram warnings: Receives a message for every repair made to load the section Returns: @@ -257,26 +330,38 @@ def _convert_section( ``None`` for a section that is skipped (a Component section that does not load is reported in ``warnings``) """ - diagram_id = str(uuid.uuid4()) + diagram_id = diagram_id or str(uuid.uuid4()) last_update = datetime.now(timezone.utc).isoformat() try: if model_name == "domain_model": parsed = parse_buml_content(section_code, warnings) + if class_ids: + parsed._wme_class_index = { + wid: parsed.get_class_by_name(name) + for name, wid in class_ids.items() + if isinstance(wid, str) and parsed.get_class_by_name(name) is not None + } model = class_buml_to_json(parsed) elif model_name == "object_model": # Object diagrams need the domain model code prepended for context # Combine all domain sections as context prefix domain_code = "\n".join(code for _, code in domain_sections) - combined_code = domain_code + "\n" + section_code if domain_code else section_code # Use the first class diagram's model as reference, or empty dict class_model_ref = class_diagram_list[0]["model"] if class_diagram_list else {} + # The referenced class diagram instead, when the export recorded it. + referenced_id = (references or {}).get("ClassDiagram") + for index, class_entry in enumerate(class_diagram_list[:len(domain_sections)]): + if referenced_id and class_entry["id"] == referenced_id: + domain_code = domain_sections[index][1] + class_model_ref = class_entry["model"] + combined_code = domain_code + "\n" + section_code if domain_code else section_code model = object_buml_to_json(combined_code, class_model_ref) elif model_name == "user_object_model": model = object_buml_to_json( - section_code, user_reference_json or {"elements": {}, "relationships": {}}, + section_code, user_reference_json or {"nodes": [], "edges": []}, diagram_type="UserDiagram", ) @@ -339,12 +424,18 @@ def _convert_section( f"Failed to convert '{title}' section ({model_name}): {e}" ) from e - return { + entry = { "id": diagram_id, "title": title, "model": model, "lastUpdate": last_update, } + if references: + entry["references"] = references + # The editor keeps an agent's default LLM on the diagram config envelope. + if model_name == "agent" and isinstance(model.get("config"), dict): + entry["config"] = model.pop("config") + return entry # Detection heuristics for single-diagram BUML files that omit the Project(...) @@ -558,17 +649,18 @@ def project_to_json(content: str, warnings: Optional[List[str]] = None) -> Dict[ model_names = re.findall(r'\b(\w+)\b', model_match.group(1)) logger.debug("Detected model names in project: %s", model_names) - # Extract project metadata - project_name_match = re.search(r'Project\s*\(\s*name\s*=\s*"(.*?)"', project_code) - project_desc_match = re.search(r'Metadata\s*\(\s*description\s*=\s*"(.*?)"', project_code) - project_owner_match = re.search(r'owner\s*=\s*"(.*?)"', project_code) - - project_name = project_name_match.group(1) if project_name_match else "Unnamed Project" - project_description = project_desc_match.group(1) if project_desc_match else "No description" - project_owner = project_owner_match.group(1) if project_owner_match else "Unknown" + # Extract project metadata from the project definition, not from the + # first Metadata(...) / owner= of some model section above it. + project_name = (_project_display_name(project_code) + or _string_kwarg(r'Project\s*\(\s*name', project_code) or "Unnamed Project") + project_description = _string_kwarg(r'Metadata\s*\(\s*description', project_code) or "No description" + project_owner = _string_kwarg(r'\bowner', project_code) or "Unknown" # diagram_jsons maps diagram type -> list of diagram entries diagram_jsons: Dict[str, List[Dict[str, Any]]] = {} + recorded_ids, recorded_class_ids = _parse_editor_ids(content) + recorded_titles = _parse_recorded_values(_DIAGRAM_TITLE_LINE, content) + recorded_references = _parse_recorded_values(_DIAGRAM_REFERENCES_LINE, content, dict) # First pass: extract all structural/domain sections (needed as context for object diagrams) # Check for both exact "domain_model" and suffixed variants like "domain_model_1" @@ -622,14 +714,16 @@ def project_to_json(content: str, warnings: Optional[List[str]] = None) -> Dict[ seen_base_names.add(base_name) if base_name == "user_object_model": + user_ids = _ids_for(recorded_ids, "UserDiagram", len(user_object_sections)) diagram_jsons["UserDiagram"] = [ _convert_section( base_name, section_code, _object_model_title(section_code) or title or DIAGRAM_DEFAULT_TITLES["UserDiagram"], domain_sections, [], user_reference_json, + diagram_id=user_id, ) - for title, section_code in user_object_sections + for (title, section_code), user_id in zip(user_object_sections, user_ids) ] continue @@ -653,11 +747,16 @@ def project_to_json(content: str, warnings: Optional[List[str]] = None) -> Dict[ continue diagram_list = [] + section_ids = _ids_for(recorded_ids, diagram_type, len(sections)) + section_titles = _ids_for(recorded_titles, diagram_type, len(sections)) + section_references = _ids_for(recorded_references, diagram_type, len(sections)) for idx, (title, section_code) in enumerate(sections): resolved_title = title if title else default_title # Append index suffix for multi-diagram types (only when more than one) if len(sections) > 1 and not title: resolved_title = f"{default_title} {idx + 1}" + # The editor's own title, when the export recorded it. + resolved_title = section_titles[idx] or resolved_title logger.debug( "Converting section %d/%d for %s: '%s'", @@ -668,7 +767,11 @@ def project_to_json(content: str, warnings: Optional[List[str]] = None) -> Dict[ class_diagrams = diagram_jsons.get("ClassDiagram", []) entry = _convert_section( base_name, section_code, resolved_title, - domain_sections, class_diagrams, warnings=warnings, + domain_sections, class_diagrams, + diagram_id=section_ids[idx], + class_ids=recorded_class_ids.get(section_ids[idx]) if section_ids[idx] else None, + references=section_references[idx], + warnings=warnings, ) if entry is not None: diagram_list.append(entry) diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/state_machine_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/state_machine_converter.py index 31c5b4259..e13e1c0bf 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/state_machine_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/state_machine_converter.py @@ -1,9 +1,13 @@ """ -State machine conversion from BUML to JSON format. +State machine conversion from BUML to v4 JSON. Provides two entry points: -- ``state_machine_object_to_json(sm)`` - converts a StateMachine metamodel object directly -- ``state_machine_to_json(content)`` - legacy: AST-parses a Python code string (for file import) +- ``state_machine_object_to_json(sm)`` — converts a StateMachine metamodel + object directly. +- ``state_machine_to_json(content)`` — legacy AST-parses a Python code + string (for file import). + +Both emit the v4 wire shape directly (``{nodes, edges}``). """ import uuid @@ -13,53 +17,79 @@ ) from besser.utilities.buml_code_builder.common import _sanitize_identifier from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import element_id_taker -from besser.utilities.web_modeling_editor.backend.services.utils import ( - determine_connection_direction, calculate_connection_points, - calculate_path_points, calculate_relationship_bounds +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._node_builders import ( + make_node, make_edge, ) -def state_machine_object_to_json(sm: StateMachine) -> dict: - """Convert a StateMachine metamodel instance to JSON format matching the frontend structure. - This is the preferred converter that works directly from the metamodel object, - avoiding the need to generate and re-parse Python code strings. +def _call_arg_name(call: ast.Call): + """Name passed as the first argument: ``f(x)`` -> ``x``, ``f(g())`` -> ``g``.""" + if not call.args: + return None + arg = call.args[0] + if isinstance(arg, ast.Name): + return arg.id + if isinstance(arg, ast.Call) and isinstance(arg.func, ast.Name): + return arg.func.id + return None + + +def _parse_transition_chain(go_to: ast.Call): + """``(source, event, guards, target)`` variable names of a transition + statement as the B-UML builder writes it -- ``s.when_event(e).go_to(t)``, + ``s.when_event(e).with_condition(c)...go_to(t)`` or + ``s.when_condition(c)...go_to(t)`` -- else ``None``.""" + target = go_to.args[0].id if go_to.args and isinstance(go_to.args[0], ast.Name) else None + guards = [] + link = go_to.func.value + while ( + isinstance(link, ast.Call) + and isinstance(link.func, ast.Attribute) + and link.func.attr == "with_condition" + ): + guards.insert(0, _call_arg_name(link)) + link = link.func.value + if not ( + isinstance(link, ast.Call) + and isinstance(link.func, ast.Attribute) + and link.func.attr in ("when_event", "when_condition") + and isinstance(link.func.value, ast.Name) + ): + return None + event = None + if link.func.attr == "when_event": + event = _call_arg_name(link) + else: + guards.insert(0, _call_arg_name(link)) + return link.func.value.id, event, [g for g in guards if g], target - Args: - sm: A StateMachine metamodel instance. +def state_machine_object_to_json(sm: StateMachine) -> dict: + """Convert a StateMachine metamodel instance to the v4 wire shape.""" + nodes: list = [] + edges: list = [] - Returns: - Dictionary in the frontend JSON format for state machine diagrams. - """ - elements = {} - relationships = {} # States, transitions and code-block bodies keep their ids (the editor's, when the machine came from it). take_id = element_id_taker() - - default_size = {"width": 1980, "height": 640} - - # Track positions for layout states_x = -550 states_y = -300 code_blocks_x = -970 code_blocks_y = 80 - # Create initial node initial_node_id = str(uuid.uuid4()) - elements[initial_node_id] = { - "id": initial_node_id, - "name": "", - "type": "StateInitialNode", - "owner": None, - "bounds": {"x": states_x - 300, "y": states_y + 20, "width": 45, "height": 45}, - } - - # Collect all unique Body, Event, and Condition objects for code blocks - all_bodies = {} # name -> Body - all_events = {} # name -> Event - all_conditions = {} # name -> Condition - state_id_map = {} # State object -> element_id - state_var_map = {} # State object -> variable name (sanitized) + nodes.append(make_node( + node_id=initial_node_id, + type_="StateInitialNode", + data={"name": ""}, + position={"x": states_x - 300, "y": states_y + 20}, + width=45, + height=45, + )) + + all_bodies = {} + all_events = {} + all_conditions = {} + state_id_map: dict = {} for state in sm.states: if state.body and state.body.name not in all_bodies: @@ -73,10 +103,23 @@ def state_machine_object_to_json(sm: StateMachine) -> dict: if condition.name not in all_conditions: all_conditions[condition.name] = condition - # Create code block elements for functions - created_code_blocks = {} # function name -> {"id": ..., "source": ...} + created_code_blocks: dict = {} + + def _emit_code_block(name: str, source: str, code_block_id: str = None) -> None: + nonlocal code_blocks_x + code_block_id = code_block_id or str(uuid.uuid4()) + cleaned = "\n".join(line.rstrip() for line in source.splitlines() if line.strip()) + nodes.append(make_node( + node_id=code_block_id, + type_="StateCodeBlock", + data={"name": name, "code": cleaned, "language": "python"}, + position={"x": code_blocks_x, "y": code_blocks_y}, + width=580, + height=200, + )) + created_code_blocks[name] = code_block_id + code_blocks_x += 610 - # Process bodies for name, body in all_bodies.items(): if name in created_code_blocks: continue @@ -85,108 +128,47 @@ def state_machine_object_to_json(sm: StateMachine) -> dict: if isinstance(action, CustomCodeAction): source_code = action.code break - if not source_code and body.code: + if not source_code and getattr(body, "code", None): source_code = body.code - if source_code: - code_block_id = take_id(body) - cleaned_source = "\n".join( - line.rstrip() for line in source_code.splitlines() if line.strip() - ) - elements[code_block_id] = { - "id": code_block_id, - "name": name, - "type": "StateCodeBlock", - "owner": None, - "bounds": { - "x": code_blocks_x, - "y": code_blocks_y, - "width": 580, - "height": 200, - }, - "code": cleaned_source, - "language": "python", - } - created_code_blocks[name] = {"id": code_block_id, "source": cleaned_source} - code_blocks_x += 610 + _emit_code_block(name, source_code, take_id(body)) - # Process events for name, event in all_events.items(): if name in created_code_blocks: continue - source_code = getattr(event, '_source_code', "") + source_code = getattr(event, '_source_code', "") or "" if source_code: - code_block_id = str(uuid.uuid4()) - cleaned_source = "\n".join( - line.rstrip() for line in source_code.splitlines() if line.strip() - ) - elements[code_block_id] = { - "id": code_block_id, - "name": name, - "type": "StateCodeBlock", - "owner": None, - "bounds": { - "x": code_blocks_x, - "y": code_blocks_y, - "width": 580, - "height": 200, - }, - "code": cleaned_source, - "language": "python", - } - created_code_blocks[name] = {"id": code_block_id, "source": cleaned_source} - code_blocks_x += 610 + _emit_code_block(name, source_code) - # Process conditions (guard expressions backed by code blocks). - # Only create code blocks for function-backed conditions (code starts with "def "). - # Inline expression guards (e.g. "x > 10") are stored directly in the - # transition's "guard" field without a separate code block. for name, condition in all_conditions.items(): if name in created_code_blocks: continue source_code = getattr(condition, 'code', "") or "" if source_code and source_code.lstrip().startswith("def "): - code_block_id = str(uuid.uuid4()) - cleaned_source = "\n".join( - line.rstrip() for line in source_code.splitlines() if line.strip() - ) - elements[code_block_id] = { - "id": code_block_id, - "name": name, - "type": "StateCodeBlock", - "owner": None, - "bounds": { - "x": code_blocks_x, - "y": code_blocks_y, - "width": 580, - "height": 200, - }, - "code": cleaned_source, - "language": "python", - } - created_code_blocks[name] = {"id": code_block_id, "source": cleaned_source} - code_blocks_x += 610 + _emit_code_block(name, source_code) - # Create state elements for state in sm.states: state_id = take_id(state) state_id_map[state] = state_id - state_var_map[state] = _sanitize_identifier(state.name) - - elements[state_id] = { - "id": state_id, - "name": state.name, - "type": "State", - "owner": None, - "bounds": { - "x": states_x, - "y": states_y, - "width": 160, - "height": 100, + bodies_data: list = [] + fallbacks_data: list = [] + if state.body and state.body.name in created_code_blocks: + bodies_data.append({"id": str(uuid.uuid4()), "name": state.body.name}) + if state.fallback_body and state.fallback_body.name in created_code_blocks: + fallbacks_data.append({"id": str(uuid.uuid4()), "name": state.fallback_body.name}) + + nodes.append(make_node( + node_id=state_id, + type_="State", + data={ + "name": state.name, + "bodies": bodies_data, + "fallbackBodies": fallbacks_data, }, - "bodies": [], - "fallbackBodies": [], - } + position={"x": states_x, "y": states_y}, + width=160, + height=100, + )) if states_x < 200: states_x += 490 @@ -194,295 +176,114 @@ def state_machine_object_to_json(sm: StateMachine) -> dict: states_x = -280 states_y += 220 - # Add initial node transition + # Initial transition. for state in sm.states: if state.initial: - state_id = state_id_map[state] - initial_rel_id = str(uuid.uuid4()) - relationships[initial_rel_id] = { - "id": initial_rel_id, - "name": "", - "type": "StateTransition", - "owner": None, - "source": { - "direction": "Right", - "element": initial_node_id, - "bounds": { - "x": elements[initial_node_id]["bounds"]["x"] + 45, - "y": elements[initial_node_id]["bounds"]["y"] + 22.5, - "width": 0, - "height": 0, - }, - }, - "target": { - "direction": "Left", - "element": state_id, - "bounds": { - "x": elements[state_id]["bounds"]["x"], - "y": elements[state_id]["bounds"]["y"] + 35, - "width": 0, - "height": 0, - }, - }, - "bounds": { - "x": elements[initial_node_id]["bounds"]["x"] + 45, - "y": elements[initial_node_id]["bounds"]["y"] + 22.5, - "width": elements[state_id]["bounds"]["x"] - - (elements[initial_node_id]["bounds"]["x"] + 45), - "height": 1, - }, - "path": [ - { - "x": elements[initial_node_id]["bounds"]["x"] + 45, - "y": elements[initial_node_id]["bounds"]["y"] + 22.5, - }, - { - "x": elements[state_id]["bounds"]["x"], - "y": elements[initial_node_id]["bounds"]["y"] + 22.5, - }, - ], - "isManuallyLayouted": False, - } - break # Only one initial state - - # Process state bodies and fallback bodies - for state in sm.states: - state_id = state_id_map[state] - - if state.body and state.body.name in created_code_blocks: - body_id = str(uuid.uuid4()) - elements[body_id] = { - "id": body_id, - "name": state.body.name, - "type": "StateBody", - "owner": state_id, - "bounds": { - "x": elements[state_id]["bounds"]["x"] + 0.5, - "y": elements[state_id]["bounds"]["y"] + 40.5, - "width": 159, - "height": 30, - }, - } - elements[state_id]["bodies"].append(body_id) - - if state.fallback_body and state.fallback_body.name in created_code_blocks: - fallback_id = str(uuid.uuid4()) - elements[fallback_id] = { - "id": fallback_id, - "name": state.fallback_body.name, - "type": "StateFallbackBody", - "owner": state_id, - "bounds": { - "x": elements[state_id]["bounds"]["x"] + 0.5, - "y": elements[state_id]["bounds"]["y"] + 70.5, - "width": 159, - "height": 30, - }, - } - elements[state_id]["fallbackBodies"].append(fallback_id) - - # Create transitions + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=initial_node_id, + target=state_id_map[state], + type_="StateTransition", + data={"name": "", "points": []}, + )) + break + + # State transitions. for state in sm.states: source_id = state_id_map[state] for transition in state.transitions: - # Skip transitions that have neither event nor conditions (auto transitions - # without guards are not representable in the JSON format) if not transition.event and not transition.conditions: continue - dest_id = state_id_map.get(transition.dest) if not dest_id: continue - rel_id = take_id(transition) - source_element = elements[source_id] - target_element = elements[dest_id] - - source_dir, target_dir = determine_connection_direction( - source_element["bounds"], target_element["bounds"] - ) - source_point = calculate_connection_points(source_element["bounds"], source_dir) - target_point = calculate_connection_points(target_element["bounds"], target_dir) - path_points = calculate_path_points(source_point, target_point, source_dir, target_dir) - rel_bounds = calculate_relationship_bounds(path_points) - event_var = _sanitize_identifier(transition.event.name) if transition.event else "" - - relationships[rel_id] = { - "id": rel_id, - "name": event_var, - "type": "StateTransition", - "owner": None, - "bounds": rel_bounds, - "path": path_points, - "source": { - "direction": source_dir, - "element": source_id, - "bounds": { - "x": source_point["x"], - "y": source_point["y"], - "width": 0, - "height": 0, - }, - }, - "target": { - "direction": target_dir, - "element": dest_id, - "bounds": { - "x": target_point["x"], - "y": target_point["y"], - "width": 0, - "height": 0, - }, - }, - "isManuallyLayouted": False, - } - - # Add event_params if present + edge_data: dict = {"name": event_var, "points": []} event_params = getattr(transition, '_event_params', None) if event_params: - relationships[rel_id]["params"] = str(event_params) - - # Add guard expression if conditions are present. - # If the condition name matches a created code block, use the name - # so the round-trip can re-associate it. Otherwise, use the code - # text directly (inline guard expression). + edge_data["params"] = str(event_params) if transition.conditions: - cond = transition.conditions[0] # primary guard + cond = transition.conditions[0] if cond.name in created_code_blocks: guard_value = cond.name - elif cond.code: + elif getattr(cond, "code", None): guard_value = cond.code else: guard_value = cond.name - relationships[rel_id]["guard"] = guard_value - - # Position for comments + edge_data["guard"] = guard_value + + edges.append(make_edge( + edge_id=take_id(transition), + source=source_id, + target=dest_id, + type_="StateTransition", + data=edge_data, + )) + + # Comments (``comment`` nodes + ``CommentLink`` edges — the types the + # React Flow frontend registers). comment_x = -970 comment_y = -300 - - # Create comment elements from metadata if sm.metadata and sm.metadata.description: - comment_id = str(uuid.uuid4()) - elements[comment_id] = { - "id": comment_id, - "name": sm.metadata.description, - "type": "Comments", - "owner": None, - "bounds": { - "x": comment_x, - "y": comment_y, - "width": 200, - "height": 100, - }, - } + nodes.append(make_node( + node_id=str(uuid.uuid4()), + type_="comment", + data={"name": sm.metadata.description}, + position={"x": comment_x, "y": comment_y}, + width=200, + height=100, + )) comment_y += 130 - # State comments (linked to states) for state in sm.states: if state.metadata and state.metadata.description: comment_id = str(uuid.uuid4()) - state_id = state_id_map[state] - - elements[comment_id] = { - "id": comment_id, - "name": state.metadata.description, - "type": "Comments", - "owner": None, - "bounds": { - "x": comment_x, - "y": comment_y, - "width": 200, - "height": 100, - }, - } - - link_id = str(uuid.uuid4()) - source_element = elements[comment_id] - target_element = elements[state_id] - - source_dir, target_dir = determine_connection_direction( - source_element["bounds"], target_element["bounds"] - ) - source_point = calculate_connection_points(source_element["bounds"], source_dir) - target_point = calculate_connection_points(target_element["bounds"], target_dir) - path_points = calculate_path_points(source_point, target_point, source_dir, target_dir) - rel_bounds = calculate_relationship_bounds(path_points) - - relationships[link_id] = { - "id": link_id, - "name": "", - "type": "Link", - "owner": None, - "bounds": rel_bounds, - "path": path_points, - "source": { - "direction": source_dir, - "element": comment_id, - "bounds": { - "x": source_point["x"], - "y": source_point["y"], - "width": 0, - "height": 0, - }, - }, - "target": { - "direction": target_dir, - "element": state_id, - "bounds": { - "x": target_point["x"], - "y": target_point["y"], - "width": 0, - "height": 0, - }, - }, - "isManuallyLayouted": False, - } - + nodes.append(make_node( + node_id=comment_id, + type_="comment", + data={"name": state.metadata.description}, + position={"x": comment_x, "y": comment_y}, + width=200, + height=100, + )) + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=comment_id, + target=state_id_map[state], + type_="CommentLink", + data={"points": []}, + )) comment_y += 130 return { - "version": "3.0.0", + "version": "4.0.0", "type": "StateMachineDiagram", - "size": default_size, + "title": getattr(sm, "name", "") or "", + "size": {"width": 1980, "height": 640}, + "nodes": nodes, + "edges": edges, "interactive": {"elements": {}, "relationships": {}}, - "elements": elements, - "relationships": relationships, "assessments": {}, } def state_machine_to_json(content: str): - """Convert a state machine Python file content to JSON format matching the frontend structure. - - This is the legacy entry point that AST-parses a Python code string. It is still - used for file-import scenarios (e.g. ``/get-json-model`` endpoint). For converting - a StateMachine metamodel object, use ``state_machine_object_to_json`` instead. - """ + """Convert a state machine Python file to the v4 wire shape (legacy).""" + nodes: list = [] + edges: list = [] - elements = {} - relationships = {} - - # Default diagram size - default_size = {"width": 1980, "height": 640} - - # Track positions for layout states_x = -550 states_y = -300 code_blocks_x = -970 code_blocks_y = 80 - # Parse the Python code tree = ast.parse(content) - # Track states and functions - states = {} # name -> state_id mapping - functions = {} # name -> function_node mapping - - # Track metadata for comments - state_comments = {} # state_var -> comment_text - sm_comment = None # StateMachine metadata comment + states: dict = {} + functions: dict = {} + state_comments: dict = {} + sm_comment = None - # First pass: collect all functions and state machine name for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): functions[node.name] = { @@ -497,23 +298,21 @@ def state_machine_to_json(content: str): ): for kw in node.value.keywords: if kw.arg == "metadata": - # Extract StateMachine metadata if isinstance(kw.value, ast.Call): for meta_kw in kw.value.keywords: if meta_kw.arg == "description": sm_comment = ast.literal_eval(meta_kw.value) - # Create initial node initial_node_id = str(uuid.uuid4()) - elements[initial_node_id] = { - "id": initial_node_id, - "name": "", - "type": "StateInitialNode", - "owner": None, - "bounds": {"x": states_x - 300, "y": states_y + 20, "width": 45, "height": 45}, - } + nodes.append(make_node( + node_id=initial_node_id, + type_="StateInitialNode", + data={"name": ""}, + position={"x": states_x - 300, "y": states_y + 20}, + width=45, + height=45, + )) - # Second pass: collect states and their configurations for node in ast.walk(tree): if isinstance(node, ast.Assign): if isinstance(node.value, ast.Call): @@ -540,318 +339,139 @@ def state_machine_to_json(content: str): "name": state_name, "is_initial": is_initial, "is_final": is_final, - "bodies": [], - "fallback_bodies": [], + "bodies_data": [], + "fallback_data": [], } - - # Always create as a regular State element - elements[state_id] = { - "id": state_id, - "name": state_name, - "type": "State", - "owner": None, - "bounds": { - "x": states_x, - "y": states_y, - "width": 160, - "height": 100, + nodes.append(make_node( + node_id=state_id, + type_="State", + data={ + "name": state_name, + "bodies": [], + "fallbackBodies": [], }, - "bodies": [], - "fallbackBodies": [], - } - + position={"x": states_x, "y": states_y}, + width=160, + height=100, + )) if states_x < 200: states_x += 490 else: states_x = -280 states_y += 220 - # After creating all states, add initial node transition + nodes_by_id = {n["id"]: n for n in nodes} + + # Initial transition (only one initial state). for state_info in states.values(): if state_info["is_initial"]: - initial_rel_id = str(uuid.uuid4()) - relationships[initial_rel_id] = { - "id": initial_rel_id, - "name": "", - "type": "StateTransition", - "owner": None, - "source": { - "direction": "Right", - "element": initial_node_id, - "bounds": { - "x": elements[initial_node_id]["bounds"]["x"] + 45, - "y": elements[initial_node_id]["bounds"]["y"] + 22.5, - "width": 0, - "height": 0, - }, - }, - "target": { - "direction": "Left", - "element": state_info["id"], - "bounds": { - "x": elements[state_info["id"]]["bounds"]["x"], - "y": elements[state_info["id"]]["bounds"]["y"] + 35, - "width": 0, - "height": 0, - }, - }, - "bounds": { - "x": elements[initial_node_id]["bounds"]["x"] + 45, - "y": elements[initial_node_id]["bounds"]["y"] + 22.5, - "width": elements[state_info["id"]]["bounds"]["x"] - - (elements[initial_node_id]["bounds"]["x"] + 45), - "height": 1, - }, - "path": [ - { - "x": elements[initial_node_id]["bounds"]["x"] + 45, - "y": elements[initial_node_id]["bounds"]["y"] + 22.5, - }, - { - "x": elements[state_info["id"]]["bounds"]["x"], - "y": elements[initial_node_id]["bounds"]["y"] + 22.5, - }, - ], - "isManuallyLayouted": False, - } - break # Only one initial state should exist + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=initial_node_id, + target=state_info["id"], + type_="StateTransition", + data={"name": "", "points": []}, + )) + break - # Create final nodes and transitions for final states for state_info in states.values(): if state_info["is_final"]: final_node_id = str(uuid.uuid4()) state_id = state_info["id"] - state_bounds = elements[state_id]["bounds"] - - # Position final node to the right of the state - final_node_x = state_bounds["x"] + state_bounds["width"] + 100 - final_node_y = state_bounds["y"] + (state_bounds["height"] / 2) - 22.5 - - elements[final_node_id] = { - "id": final_node_id, - "name": "", - "type": "StateFinalNode", - "owner": None, - "bounds": { - "x": final_node_x, - "y": final_node_y, - "width": 45, - "height": 45, - }, - } - - # Create transition from state to final node - source_point = { - "x": state_bounds["x"] + state_bounds["width"], - "y": state_bounds["y"] + state_bounds["height"] / 2, - } - target_point = { - "x": final_node_x, - "y": final_node_y + 22.5, - } - - final_rel_id = str(uuid.uuid4()) - relationships[final_rel_id] = { - "id": final_rel_id, - "name": "", - "type": "StateTransition", - "owner": None, - "source": { - "direction": "Right", - "element": state_id, - "bounds": { - "x": source_point["x"], - "y": source_point["y"], - "width": 0, - "height": 0, - }, - }, - "target": { - "direction": "Left", - "element": final_node_id, - "bounds": { - "x": target_point["x"], - "y": target_point["y"], - "width": 0, - "height": 0, - }, - }, - "bounds": { - "x": source_point["x"], - "y": source_point["y"], - "width": target_point["x"] - source_point["x"], - "height": 1, - }, - "path": [source_point, target_point], - "isManuallyLayouted": False, - } - - # Track created code blocks to avoid duplication - created_code_blocks = {} - - # When processing functions + state_node = nodes_by_id.get(state_id) + if not state_node: + continue + sx = state_node["position"]["x"] + sy = state_node["position"]["y"] + sw = state_node["width"] + sh = state_node["height"] + nodes.append(make_node( + node_id=final_node_id, + type_="StateFinalNode", + data={"name": ""}, + position={"x": sx + sw + 100, "y": sy + (sh / 2) - 22.5}, + width=45, + height=45, + )) + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=state_id, + target=final_node_id, + type_="StateTransition", + data={"name": "", "points": []}, + )) + + created_code_blocks: dict = {} for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): function_name = node.name - if function_name not in created_code_blocks: - code_block_id = str(uuid.uuid4()) - function_source = ast.get_source_segment(content, node) - - # Clean up the source code - cleaned_source = "\n".join( - line.rstrip() - for line in function_source.splitlines() - if line.strip() # Only include non-empty lines - ) - - elements[code_block_id] = { - "id": code_block_id, - "name": function_name, - "type": "StateCodeBlock", - "owner": None, - "bounds": { - "x": code_blocks_x, - "y": code_blocks_y, - "width": 580, - "height": 200, - }, - "code": cleaned_source, - "language": "python", - } - created_code_blocks[function_name] = { - "id": code_block_id, - "source": cleaned_source, - } - code_blocks_x += 610 - - # Third pass: process state bodies and transitions + if function_name in created_code_blocks: + continue + code_block_id = str(uuid.uuid4()) + function_source = ast.get_source_segment(content, node) or "" + cleaned_source = "\n".join( + line.rstrip() + for line in function_source.splitlines() + if line.strip() + ) + nodes.append(make_node( + node_id=code_block_id, + type_="StateCodeBlock", + data={"name": function_name, "code": cleaned_source, "language": "python"}, + position={"x": code_blocks_x, "y": code_blocks_y}, + width=580, + height=200, + )) + created_code_blocks[function_name] = code_block_id + code_blocks_x += 610 + + # Process state bodies + transitions. for node in ast.walk(tree): if isinstance(node, ast.Expr): if isinstance(node.value, ast.Call): if isinstance(node.value.func, ast.Attribute): - # Handle set_body if node.value.func.attr == "set_body": state_var = node.value.func.value.id body_func = node.value.keywords[0].value.id if state_var in states and body_func in created_code_blocks: state = states[state_var] - body_id = str(uuid.uuid4()) - elements[body_id] = { - "id": body_id, - "name": body_func, - "type": "StateBody", - "owner": state["id"], - "bounds": { - "x": elements[state["id"]]["bounds"]["x"] + 0.5, - "y": elements[state["id"]]["bounds"]["y"] + 40.5, - "width": 159, - "height": 30, - }, - } - elements[state["id"]]["bodies"].append(body_id) - - # Handle when_event(...).go_to(...) - elif ( - node.value.func.attr == "go_to" - and isinstance(node.value.func.value, ast.Call) - and isinstance(node.value.func.value.func, ast.Attribute) - and node.value.func.value.func.attr == "when_event" - ): - source_state = node.value.func.value.func.value.id - rel_id = str(uuid.uuid4()) - - event_name = None - target_state = node.value.args[0].id if node.value.args and isinstance(node.value.args[0], ast.Name) else None - event_params = None - - if node.value.func.value.args: - event_arg = node.value.func.value.args[0] - if isinstance(event_arg, ast.Name): - event_name = event_arg.id - elif isinstance(event_arg, ast.Call) and isinstance(event_arg.func, ast.Name): - event_name = event_arg.func.id - - if source_state in states and target_state in states: - source_element = elements[states[source_state]["id"]] - target_element = elements[states[target_state]["id"]] - - source_dir, target_dir = determine_connection_direction( - source_element["bounds"], target_element["bounds"] - ) - - source_point = calculate_connection_points( - source_element["bounds"], source_dir - ) - target_point = calculate_connection_points( - target_element["bounds"], target_dir - ) - - path_points = calculate_path_points( - source_point, target_point, source_dir, target_dir - ) - rel_bounds = calculate_relationship_bounds(path_points) - - relationships[rel_id] = { - "id": rel_id, - "name": event_name, - "type": "StateTransition", - "owner": None, - "bounds": rel_bounds, - "path": path_points, - "source": { - "direction": source_dir, - "element": states[source_state]["id"], - "bounds": { - "x": source_point["x"], - "y": source_point["y"], - "width": 0, - "height": 0, - }, - }, - "target": { - "direction": target_dir, - "element": states[target_state]["id"], - "bounds": { - "x": target_point["x"], - "y": target_point["y"], - "width": 0, - "height": 0, - }, - }, - "isManuallyLayouted": False, - } - - if event_params: - relationships[rel_id]["params"] = str(event_params) - - # Add handling for fallback bodies + state_node = nodes_by_id.get(state["id"]) + if state_node: + state_node["data"]["bodies"].append({ + "id": str(uuid.uuid4()), + "name": body_func, + }) + + elif node.value.func.attr == "go_to": + transition = _parse_transition_chain(node.value) + if transition: + source_state, event_name, guards, target_state = transition + if source_state in states and target_state in states: + data = {"name": event_name, "points": []} + if guards: + # The editor keeps one guard per transition. + data["guard"] = guards[0] + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=states[source_state]["id"], + target=states[target_state]["id"], + type_="StateTransition", + data=data, + )) + elif node.value.func.attr == "set_fallback_body": state_var = node.value.func.value.id fallback_func = node.value.args[0].id if state_var in states and fallback_func in functions: state = states[state_var] - fallback_id = str(uuid.uuid4()) - elements[fallback_id] = { - "id": fallback_id, - "name": fallback_func, - "type": "StateFallbackBody", - "owner": state["id"], - "bounds": { - "x": elements[state["id"]]["bounds"]["x"] + 0.5, - "y": elements[state["id"]]["bounds"]["y"] + 70.5, - "width": 159, - "height": 30, - }, - } - elements[state["id"]]["fallbackBodies"].append(fallback_id) - - # Handle state metadata - elif node.value.func.attr == "metadata": - # This is an assignment like: state_var.metadata = Metadata(...) - pass # Will be handled in Assign nodes + state_node = nodes_by_id.get(state["id"]) + if state_node: + state_node["data"]["fallbackBodies"].append({ + "id": str(uuid.uuid4()), + "name": fallback_func, + }) elif isinstance(node, ast.Assign): - # Check for state.metadata = Metadata(...) patterns if len(node.targets) == 1: target = node.targets[0] if isinstance(target, ast.Attribute) and target.attr == "metadata": @@ -861,106 +481,47 @@ def state_machine_to_json(content: str): if kw.arg == "description": state_comments[state_var] = ast.literal_eval(kw.value) - # Position for comments comment_x = -970 comment_y = -300 - # Create comment elements from metadata - # 1. State machine comment (unlinked) if sm_comment: - comment_id = str(uuid.uuid4()) - elements[comment_id] = { - "id": comment_id, - "name": sm_comment, - "type": "Comments", - "owner": None, - "bounds": { - "x": comment_x, - "y": comment_y, - "width": 200, - "height": 100, - }, - } + nodes.append(make_node( + node_id=str(uuid.uuid4()), + type_="comment", + data={"name": sm_comment}, + position={"x": comment_x, "y": comment_y}, + width=200, + height=100, + )) comment_y += 130 - # 2. State comments (linked to states) for state_var, comment_text in state_comments.items(): if state_var in states: comment_id = str(uuid.uuid4()) - state_id = states[state_var]["id"] - - elements[comment_id] = { - "id": comment_id, - "name": comment_text, - "type": "Comments", - "owner": None, - "bounds": { - "x": comment_x, - "y": comment_y, - "width": 200, - "height": 100, - }, - } - - # Create Link relationship - link_id = str(uuid.uuid4()) - source_element = elements[comment_id] - target_element = elements[state_id] - - source_dir, target_dir = determine_connection_direction( - source_element["bounds"], target_element["bounds"] - ) - - source_point = calculate_connection_points( - source_element["bounds"], source_dir - ) - target_point = calculate_connection_points( - target_element["bounds"], target_dir - ) - - path_points = calculate_path_points( - source_point, target_point, source_dir, target_dir - ) - rel_bounds = calculate_relationship_bounds(path_points) - - relationships[link_id] = { - "id": link_id, - "name": "", - "type": "Link", - "owner": None, - "bounds": rel_bounds, - "path": path_points, - "source": { - "direction": source_dir, - "element": comment_id, - "bounds": { - "x": source_point["x"], - "y": source_point["y"], - "width": 0, - "height": 0, - }, - }, - "target": { - "direction": target_dir, - "element": state_id, - "bounds": { - "x": target_point["x"], - "y": target_point["y"], - "width": 0, - "height": 0, - }, - }, - "isManuallyLayouted": False, - } - + nodes.append(make_node( + node_id=comment_id, + type_="comment", + data={"name": comment_text}, + position={"x": comment_x, "y": comment_y}, + width=200, + height=100, + )) + edges.append(make_edge( + edge_id=str(uuid.uuid4()), + source=comment_id, + target=states[state_var]["id"], + type_="CommentLink", + data={"points": []}, + )) comment_y += 130 return { - "version": "3.0.0", + "version": "4.0.0", "type": "StateMachineDiagram", - "size": default_size, + "title": "", + "size": {"width": 1980, "height": 640}, + "nodes": nodes, + "edges": edges, "interactive": {"elements": {}, "relationships": {}}, - "elements": elements, - "relationships": relationships, "assessments": {}, } diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/trace_matching.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/trace_matching.py index 6fe65bda6..f64c87c97 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/trace_matching.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/trace_matching.py @@ -34,7 +34,6 @@ Key = Tuple[str, ...] -_TOP_LEVEL_TYPES = {"Class", "AbstractClass", "Interface", "Enumeration", "AssociationClass"} _METHOD_NAME = re.compile(r"^\s*[+\-#~]?\s*([^(\s]+)") @@ -44,34 +43,50 @@ def _method_name(label: str) -> str: return match.group(1) if match else label +def _data(item: Dict[str, Any]) -> Dict[str, Any]: + data = item.get("data") + return data if isinstance(data, dict) else {} + + def _diagram_keys(model: Dict[str, Any]) -> Dict[Key, str]: - """Qualified-name key -> element id, for one imported class diagram (editor JSON).""" - elements = model.get("elements", {}) + """Qualified-name key -> element id, for one imported class diagram (v4 editor JSON).""" + nodes = [node for node in model.get("nodes") or [] if isinstance(node, dict)] + names = {node.get("id"): _data(node).get("name", "") for node in nodes} keys: Dict[Key, str] = {} - for element in elements.values(): - owner = elements.get(element.get("owner") or "") - kind, name = element.get("type"), element.get("name", "") - if owner is None and kind in _TOP_LEVEL_TYPES: - keys[("type", name)] = element["id"] - elif kind == "ClassOCLConstraint": - keys[("constraint", name)] = element["id"] - elif owner is not None and kind == "ClassMethod": - keys[("method", owner.get("name", ""), _method_name(name))] = element["id"] - elif owner is not None and kind == "ClassAttribute": - member = "literal" if owner.get("type") == "Enumeration" else "attribute" - keys[(member, owner.get("name", ""), name)] = element["id"] - for relationship in model.get("relationships", {}).values(): - ends = [elements.get(relationship.get(side, {}).get("element") or "", {}).get("name", "") - for side in ("source", "target")] - if relationship.get("type") == "ClassInheritance": - keys[("generalization", *ends)] = relationship["id"] - else: - if relationship.get("name"): - keys[("association", relationship["name"])] = relationship["id"] - keys[("association-ends", *sorted(ends))] = relationship["id"] + for node in nodes: + data, name = _data(node), _data(node).get("name", "") + if node.get("type") == "ClassOCLConstraint": + keys[("constraint", name)] = node["id"] + continue + if node.get("type") != "class": + continue + keys[("type", name)] = node["id"] + member = "literal" if (data.get("stereotype") or "").strip().lower() == "enumeration" else "attribute" + for row in data.get("attributes") or []: + if isinstance(row, dict) and row.get("id"): + keys[(member, name, row.get("name", ""))] = row["id"] + for row in data.get("methods") or []: + if isinstance(row, dict) and row.get("id"): + keys[("method", name, _method_name(row.get("name", "")))] = row["id"] + for row in data.get("oclConstraints") or []: + if isinstance(row, dict) and row.get("id") and row.get("name"): + keys[("constraint", row["name"])] = row["id"] + for edge in model.get("edges") or []: + if not isinstance(edge, dict) or edge.get("source") not in names or edge.get("target") not in names: + continue + ends = [names[edge["source"]], names[edge["target"]]] + if edge.get("type") == "ClassInheritance": + keys[("generalization", *ends)] = edge["id"] + elif edge.get("type") in _ASSOCIATION_EDGE_TYPES: + if _data(edge).get("name"): + keys[("association", _data(edge)["name"])] = edge["id"] + keys[("association-ends", *sorted(ends))] = edge["id"] return keys +_ASSOCIATION_EDGE_TYPES = {"ClassBidirectional", "ClassUnidirectional", "ClassAggregation", "ClassComposition"} + + def _artifact_keys(artifact: ModelArtifact) -> List[Key]: """The keys an artifact may match, best first.""" kind, name = artifact.element_type, artifact.name @@ -114,17 +129,13 @@ def _artifact_keys(artifact: ModelArtifact) -> List[Key]: def _ids_in(model: Any) -> Set[str]: - """Every id an imported diagram's JSON holds: the keys of its ``elements`` and ``relationships`` - and every ``id`` value, at any depth (a GUI's pages and components carry theirs in ``id`` and - ``attributes.id``).""" + """Every ``id`` value an imported diagram's JSON holds, at any depth: its nodes, edges, rows and + components (a GUI's pages and components carry theirs in ``id`` and ``attributes.id``).""" ids: Set[str] = set() pending = [model] while pending: value = pending.pop() if isinstance(value, dict): - for key in ("elements", "relationships"): - if isinstance(value.get(key), dict): - ids.update(k for k in value[key] if isinstance(k, str)) if isinstance(value.get("id"), str): ids.add(value["id"]) pending.extend(value.values()) @@ -143,20 +154,31 @@ def _ids_in(model: Any) -> Set[str]: _MATCHED_BY_NAME = {"AgentDiagram", "StateMachineDiagram"} +def _named_elements(model: Dict[str, Any]): + """``(id, editor type, fields)`` of the canvas nodes (fields in ``data``) and the agent components.""" + for node in model.get("nodes") or []: + if isinstance(node, dict): + yield node.get("id"), node.get("type"), _data(node) + components = model.get("components") + for component_id, component in (components.items() if isinstance(components, dict) else ()): + if isinstance(component, dict): + yield component.get("id") or component_id, component.get("type"), component + + def _named_keys(model: Dict[str, Any]) -> Dict[Key, str]: """(metaclass, name) -> element id, for the elements whose name is the only one of their kind.""" keys: Dict[Key, str] = {} ambiguous: Set[Key] = set() - for element in {**(model.get("elements") or {}), **(model.get("components") or {})}.values(): - metaclass = _NAMED_ELEMENT_TYPES.get(element.get("type")) - if metaclass == "AgentState" and element.get("stateType") == "reasoning": + for element_id, element_type, fields in _named_elements(model): + metaclass = _NAMED_ELEMENT_TYPES.get(element_type) + if metaclass == "AgentState" and fields.get("stateType") == "reasoning": metaclass = "ReasoningState" - if metaclass is None or not element.get("name"): + if metaclass is None or not fields.get("name"): continue - key = (metaclass, element["name"]) + key = (metaclass, fields["name"]) if key in keys: ambiguous.add(key) - keys[key] = element["id"] + keys[key] = element_id return {key: element_id for key, element_id in keys.items() if key not in ambiguous} diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/__init__.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/__init__.py index 9e9633452..bd1fdab63 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/__init__.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/__init__.py @@ -3,14 +3,13 @@ """ from .class_diagram_processor import process_class_diagram +# bpmn_diagram_processor must be imported before project_converter (which does +# ``from . import (..., process_bpmn_diagram)``). +from .bpmn_diagram_processor import process_bpmn_diagram from .object_diagram_processor import process_object_diagram from .state_machine_processor import process_state_machine from .agent_diagram_processor import process_agent_diagram from .a2a_tags import annotate_agent_with_a2a -# bpmn_diagram_processor must be imported before project_converter — the latter does -# `from . import (..., process_bpmn_diagram)` to wire BPMN into project conversion, so -# the name has to be present in this package's namespace when project_converter loads. -from .bpmn_diagram_processor import process_bpmn_diagram from .gui_diagram_processor import process_gui_diagram from .quantum_diagram_processor import process_quantum_diagram from .nn_diagram_processor import process_nn_diagram @@ -26,6 +25,7 @@ __all__ = [ 'process_class_diagram', + 'process_bpmn_diagram', 'process_object_diagram', 'process_state_machine', 'process_agent_diagram', @@ -34,9 +34,8 @@ 'process_gui_diagram', 'process_quantum_diagram', 'process_nn_diagram', - 'link_method_neural_networks', - 'process_bpmn_diagram', 'process_kg_diagram', + 'link_method_neural_networks', 'process_component_diagram', 'process_deployment_diagram', 'process_trace', diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/_node_helpers.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/_node_helpers.py new file mode 100644 index 000000000..ceb359305 --- /dev/null +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/_node_helpers.py @@ -0,0 +1,97 @@ +"""Helpers for reading the v4 ``{nodes[], edges[]}`` wire shape. + +The v4 React-Flow wire shape is a flat list of nodes and edges (see +``docs/source/migrations/uml-v4-shape.md``). These helpers read a single +v4 node and never mutate their input. +""" + +from __future__ import annotations + + +def node_data(node: dict) -> dict: + """Return the ``data`` dict of a node (always a dict, never ``None``).""" + data = node.get("data") + return data if isinstance(data, dict) else {} + + +def node_bounds(node: dict) -> dict: + """Reconstruct the v3-style ``{x, y, width, height}`` bounds for a node. + + Some converters still want bounds for layout-preserving round-trips; + this helper makes the v3 shape available without re-encoding logic + everywhere. + """ + pos = node.get("position") or {} + width = node.get("width", 0) + height = node.get("height", 0) + measured = node.get("measured") or {} + return { + "x": pos.get("x", 0), + "y": pos.get("y", 0), + "width": width or measured.get("width", 0), + "height": height or measured.get("height", 0), + } + + +def absolute_bounds(node: dict, nodes_by_id: dict) -> dict: + """``node_bounds`` with the position made absolute. + + A v4 ``position`` is relative to the ``parentId`` node, so the ancestors' + positions are added (cycle-safe). Converters stash absolute bounds in the + metamodel ``layout``, as v3 and diagram-interchange formats do. + """ + bounds = node_bounds(node) + seen = {node.get("id")} + parent = nodes_by_id.get(node.get("parentId")) + while parent is not None and parent.get("id") not in seen: + seen.add(parent.get("id")) + position = parent.get("position") or {} + bounds["x"] += position.get("x", 0) + bounds["y"] += position.get("y", 0) + parent = nodes_by_id.get(parent.get("parentId")) + return bounds + + +def edge_layout(edge: dict) -> dict: + """Opaque layout stash for an edge: id, absolute points, handles, routing flag.""" + data = edge.get("data") if isinstance(edge.get("data"), dict) else {} + return { + "id": edge.get("id"), + "points": data.get("points") or [], + "source_direction": edge.get("sourceHandle"), + "target_direction": edge.get("targetHandle"), + "isManuallyLayouted": data.get("isManuallyLayouted", False), + } + + +def node_layout(node: dict, nodes_by_id: dict) -> dict: + """Opaque layout stash for a node of a Component / Deployment diagram. + + ``id``, ``parentId``, absolute ``bounds``, the stereotype header flag as + ``displayStereotype`` (the key v8.1 ``.py`` exports already use) and colours. + """ + data = node_data(node) + layout = { + "id": node.get("id"), + "parentId": node.get("parentId"), + "bounds": absolute_bounds(node, nodes_by_id), + } + header = data.get("isComponentSubsystemHeaderShown", data.get("isComponentHeaderShown")) + if header is not None: + layout["displayStereotype"] = bool(header) + for style_key in ("fillColor", "strokeColor", "textColor", "highlight"): + if style_key in data: + layout[style_key] = data[style_key] + return layout + + +def reject_unreadable_model(json_data: object, diagram_type: str) -> None: + """Raise ``ConversionError`` for a legacy v3 or malformed diagram, which + would otherwise convert to an empty or broken model.""" + # Lazy: the validators package imports modules that import the converters. + from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_diagram_not_legacy, + ) + if isinstance(json_data, dict): + title = json_data.get("title") if isinstance(json_data.get("title"), str) else None + ensure_diagram_not_legacy(json_data.get("model"), diagram_type=diagram_type, title=title) diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/a2a_tags.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/a2a_tags.py index 86c43b145..43584fb39 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/a2a_tags.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/a2a_tags.py @@ -10,7 +10,7 @@ a2a:;peer=;ref=;flow=;[order=;]kind=<...> -2. `annotate_agent_with_a2a` — a re-walk of the raw AgentDiagram JSON that stashes +2. `annotate_agent_with_a2a` — a re-walk of the raw v4 AgentDiagram JSON that stashes the parsed in/out edges on `agent._a2a` (a side-map, no metamodel change). It is a no-op (sets no attribute) when the diagram carries no `a2a:` tag, so legacy agents stay byte-identical and the generator's `getattr(agent, "_a2a", None)` is falsy. @@ -72,6 +72,20 @@ def parse_a2a_line(line: str) -> Optional[dict]: } +def format_a2a_line(edge: dict) -> Optional[str]: + """Inverse of `parse_a2a_line`: the wire tag for a parsed edge, or None without a peer.""" + if not isinstance(edge, dict) or edge.get("dir") not in ("in", "out") or not edge.get("peer"): + return None + parts = [f"a2a:{edge['dir']}", f"peer={edge['peer']}", f"ref={edge.get('ref') or ''}"] + if edge.get("flow"): + parts.append(f"flow={edge['flow']}") + if isinstance(edge.get("order"), int) and edge["order"] != _ORDER_SENTINEL: + parts.append(f"order={edge['order']}") + if edge.get("kind") in _KINDS: + parts.append(f"kind={edge['kind']}") + return ";".join(parts) + + def parse_a2a_out_block(description: Optional[str]) -> list: """Parse an AgentState.description (possibly multi-line) into a list of out-edges, sorted by ascending `order`. Non-a2a lines (human comments) are ignored — a state @@ -87,45 +101,48 @@ def parse_a2a_out_block(description: Optional[str]) -> list: def annotate_agent_with_a2a(agent, agent_diagram_json: dict): - """Attach `agent._a2a = {outbound, inbound}` parsed from the AgentDiagram JSON. + """Attach `agent._a2a = {outbound, inbound}` parsed from the v4 AgentDiagram JSON. Standalone: does NOT touch process_agent_diagram. Call it right after the agent is built. No-op (no attribute set) when the diagram carries no a2a: tag, so legacy agents stay byte-identical and the generator's getattr(agent,'_a2a',None) is falsy. Reads only strings (peer/state/intent names), so it never needs the built State/Transition objects — fully decoupled from the metamodel. + + Tags ride on ``AgentState`` node ``data.description`` (``a2a:out`` lines) and on + transition edge ``data.name`` (``a2a:in``), the intent on + ``data.predefined.intentName``. """ if not isinstance(agent_diagram_json, dict): return agent model = agent_diagram_json.get("model") or agent_diagram_json - elements = model.get("elements", {}) or {} - relationships = model.get("relationships", {}) or {} + nodes = [n for n in (model.get("nodes") or []) if isinstance(n, dict)] + edges = [e for e in (model.get("edges") or []) if isinstance(e, dict)] + states = {n.get("id"): n.get("data") or {} for n in nodes if n.get("type") == "AgentState"} - def _state_name(elem_id): - el = elements.get(elem_id, {}) - return el.get("name", "") if el.get("type") == "AgentState" else "" + def _state_name(node_id): + return (states.get(node_id) or {}).get("name", "") - # ── outbound: a2a:out lines on each AgentState.description ── + # ── outbound: a2a:out lines on each AgentState description ── outbound = [] - for el in elements.values(): - if el.get("type") != "AgentState": - continue - for edge in parse_a2a_out_block(el.get("description")): - edge["state"] = el.get("name", "") + for data in states.values(): + for edge in parse_a2a_out_block(data.get("description")): + edge["state"] = data.get("name", "") outbound.append(edge) # ── inbound: a2a:in on a when_intent_matched transition's `name` ── inbound = [] - for rel in relationships.values(): - if rel.get("type") not in ("AgentStateTransition", "AgentStateTransitionInit"): + for edge in edges: + if edge.get("type") not in ("AgentStateTransition", "AgentStateTransitionInit"): continue - parsed = parse_a2a_line(rel.get("name", "")) + data = edge.get("data") or {} + parsed = parse_a2a_line(data.get("name", "")) if not (parsed and parsed["dir"] == "in" and parsed["peer"]): continue - predefined = rel.get("predefined") or {} - parsed["intent"] = predefined.get("intentName") or rel.get("intentName") or "" - parsed["source_state"] = _state_name((rel.get("source") or {}).get("element")) - parsed["target_state"] = _state_name((rel.get("target") or {}).get("element")) + predefined = data.get("predefined") or {} + parsed["intent"] = predefined.get("intentName") or data.get("intentName") or "" + parsed["source_state"] = _state_name(edge.get("source")) + parsed["target_state"] = _state_name(edge.get("target")) inbound.append(parsed) if outbound or inbound: diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/agent_diagram_processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/agent_diagram_processor.py index ec4142bea..4edada746 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/agent_diagram_processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/agent_diagram_processor.py @@ -1,5 +1,14 @@ """ -Agent diagram processing for converting JSON to BUML format. +Agent diagram processing for converting v4 JSON to BUML format. + +Reads the v4 wire shape natively: canvas ``nodes`` / ``edges`` plus the +off-canvas ``components`` map (intents, LLMs, RAG databases, tools, skills, +workspaces, GUIs). ``AgentState`` action rows (``data.bodies`` / +``data.fallbackBodies``) are dispatched one by one on their ``actionType`` +(metamodel class name) or legacy ``replyType``, preserving their order. +``_normalise_agent_transitions`` collapses the historical +``AgentStateTransition`` shapes (see ``docs/source/migrations/uml-v4-shape.md``) +to the canonical ``transitionType + predefined|custom`` form. """ import logging @@ -52,18 +61,36 @@ GUIEvent, ) from besser.BUML.metamodel.structural import DomainModel, Metadata -from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.gui_diagram_processor import ( - process_gui_diagram, +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + node_data, ) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import EditorIds from besser.utilities.web_modeling_editor.backend.services.converters.parsers import sanitize_text from besser.utilities.web_modeling_editor.backend.services.validators.python_code_validator import ( validate_custom_code_action, ) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + reject_unreadable_model, +) from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.utils import sanitize_name logger = logging.getLogger(__name__) +#: ``AgentState`` action-row keys in read order: ``actions`` wins over the +#: legacy ``bodies`` (same for the fallback body). Shared with the simulator's +#: custom-code gate, which must see every row the converter reads. +STATE_BODY_KEYS = ("actions", "bodies") +STATE_FALLBACK_BODY_KEYS = ("fallbackActions", "fallbackBodies") +STATE_ACTION_ROW_KEYS = STATE_BODY_KEYS + STATE_FALLBACK_BODY_KEYS + + +def _first_present(data: dict, keys: tuple): + """Value of the first key of ``keys`` present in ``data``, else None.""" + for key in keys: + if key in data: + return data[key] + return None + _DEFAULT_INPUT_PROMPT_MODE = "last_user_message" @@ -358,8 +385,265 @@ def _build_body_from_action_elements(body_name, action_element_ids, elements, return body if action_added else None +# --------------------------------------------------------------------------- +# v4 input helpers +# --------------------------------------------------------------------------- + +# The React Flow frontend creates ``comment`` nodes tethered by +# ``CommentLink`` edges; ``Comments`` / ``Link`` are the legacy spellings. +COMMENT_NODE_TYPES = ("comment", "Comments") +COMMENT_LINK_TYPES = ("CommentLink", "Link") + +# Off-canvas agent component types (``model.components``). Nodes of these +# types are a legacy input only (pre-Components-page React Flow models). +AGENT_COMPONENT_TYPES = frozenset({ + "AgentIntent", "AgentIntentBody", "AgentRagElement", "AgentTool", + "AgentSkill", "AgentWorkspace", "AgentLLM", "AgentGUI", +}) + +# Placeholder label older v4 writers put on the ``name`` of an LLM row. +_LLM_ROW_PLACEHOLDER = "AI response 🪄" + + +def _normalise_body_row(row: dict) -> dict: + """Lift legacy v4 row conventions onto the canonical action-row fields. + + * Older v4 LLM / LLM-chat rows carried the system prompt on ``name``; + the canonical field is ``system_message``. + * v4 code rows carry the source on ``code`` (``name`` may be a label); + the dispatcher reads the source from ``name``. + """ + out = dict(row) + action_type = _resolve_action_type(out) + if action_type in ("LLMReplyAction", "LLMChatAction") and "system_message" not in out: + legacy_prompt = out.get("name") or "" + if legacy_prompt and legacy_prompt != _LLM_ROW_PLACEHOLDER: + out["system_message"] = legacy_prompt + elif action_type == "CustomCodeAction": + code_source = out.get("code") + if isinstance(code_source, str) and code_source: + out["name"] = code_source + return out + + +def _build_body_from_action_rows(body_name, rows, language, source_language, translate_text, + build_db_reply_fn=None, gui_defs_by_id=None): + """Build a Body from the v4 inline action rows of an AgentState (order preserved).""" + if not isinstance(rows, list) or not rows: + return None + index: dict = {} + ids: list = [] + for position, row in enumerate(rows): + if not isinstance(row, dict): + continue + row_id = row.get("id") or f"{body_name}_{position}" + if row_id in index: + row_id = f"{row_id}_{position}" + index[row_id] = _normalise_body_row(row) + ids.append(row_id) + return _build_body_from_action_elements( + body_name, ids, index, language, source_language, translate_text, + build_db_reply_fn=build_db_reply_fn, gui_defs_by_id=gui_defs_by_id, + ) + + +def _node_to_components(node: dict) -> list: + """Flatten a legacy v4 component node into ``model.components`` entries.""" + data = dict(node_data(node)) + node_id = node.get("id") + node_type = node.get("type") + # node.data never carries geometry, but drop stray canvas keys (``width`` is a GUI field). + for key in ("bounds", "position", "measured", "parentId"): + data.pop(key, None) + if node_type == "AgentIntent": + rows = data.pop("training_phrases", None) + if not isinstance(rows, list) or not rows: + rows = data.get("bodies") or [] + entries = [] + body_ids = [] + for position, row in enumerate(rows): + if isinstance(row, str): + body_ids.append(row) + continue + if not isinstance(row, dict): + continue + body_id = row.get("id") or f"{node_id}-body-{position}" + body_ids.append(body_id) + entries.append({"id": body_id, "type": "AgentIntentBody", "name": row.get("name", ""), + "owner": node_id}) + intent = {**data, "id": node_id, "type": "AgentIntent", "name": data.get("name", ""), + "owner": None, "bodies": body_ids} + return [intent] + entries + if node_type == "AgentIntentBody": + return [{**data, "id": node_id, "type": "AgentIntentBody", "name": data.get("name", ""), + "owner": node.get("parentId") or data.get("owner")}] + return [{**data, "id": node_id, "type": node_type, "name": data.get("name", ""), "owner": None}] + + +def collect_agent_components(json_data: dict) -> dict: + """Merge every location agent components may be stored in, keyed by id. + + Precedence (later wins): legacy component nodes in ``model.nodes`` < + diagram-level ``agentComponents`` < ``model.agentComponents`` < + ``model.components`` (canonical). A v3 ``model.elements`` map is never read. + """ + model_data = json_data.get("model") or {} + merged: dict = {} + for node in model_data.get("nodes") or []: + if isinstance(node, dict) and node.get("type") in AGENT_COMPONENT_TYPES: + for entry in _node_to_components(node): + merged[entry["id"]] = entry + for source in (json_data.get("agentComponents"), model_data.get("agentComponents"), + model_data.get("components")): + if isinstance(source, dict): + for component_id, component in source.items(): + if isinstance(component, dict): + merged[component_id] = {**component, "id": component.get("id") or component_id} + return merged + + +def _normalise_agent_transitions(edges: list[dict]) -> list[dict]: + """Collapse legacy AgentStateTransition shapes to the canonical v4 form. + + The v4 canonical shape is on ``edge.data``: + transitionType: 'predefined' | 'custom' + predefined: { predefinedType, intentName?, fileType?, formGuiId?, conditionValue? } + custom: { event, condition: string[], guiEventGuiId? } + + Legacy shapes are accepted (see uml-v4-shape.md). Fallthrough order: + 1. transitionType=='custom' OR legacy condition=='custom_transition' + OR custom.event/condition non-empty -> emit canonical custom block. + 2. Otherwise emit canonical predefined block. + + Returns a NEW list of edges; input is not mutated. + """ + out: list[dict] = [] + for edge in edges: + if edge.get("type") != "AgentStateTransition": + out.append(edge) + continue + nedge = dict(edge) + ndata = dict(edge.get("data") or {}) + predefined = ndata.get("predefined") or {} + custom = ndata.get("custom") or {} + + is_custom = ( + ndata.get("transitionType") == "custom" + or ndata.get("condition") == "custom_transition" + # The editor leaves an idle ``custom: {event: "None"}`` on predefined transitions. + or (isinstance(custom.get("event"), str) and custom.get("event") not in ("", "None")) + or (isinstance(custom.get("condition"), list) and any( + isinstance(c, str) and c.strip() for c in custom["condition"] + )) + or (isinstance(ndata.get("conditionValue"), dict) and ( + ndata["conditionValue"].get("events") or ndata["conditionValue"].get("conditions") + )) + ) + if ndata.get("transitionType") == "predefined" and not ndata.get("condition") == "custom_transition": + is_custom = False + + if is_custom: + event = ( + custom.get("event") + or ndata.get("event") + or ndata.get("customEvent") + or "None" + ) + cond = custom.get("condition") + if not (isinstance(cond, list) and cond): + # Older shapes keep the conditions on the edge data, as development read them. + cond = next( + (c for c in (ndata.get("conditions"), ndata.get("condition")) if isinstance(c, list) and c), + cond, + ) + if not isinstance(cond, list): + cond = ndata.get("customConditions") + if not isinstance(cond, list): + cv = ndata.get("conditionValue") + if isinstance(cv, dict): + events = cv.get("events") or [] + if isinstance(events, list) and events and not custom.get("event"): + event = events[0] + cond = cv.get("conditions") or [] + if not isinstance(cond, list): + cond = [] + block: dict = {"event": event, "condition": cond} + gui_event_gui_id = custom.get("guiEventGuiId") or ndata.get("guiEventGuiId") + if gui_event_gui_id: + block["guiEventGuiId"] = gui_event_gui_id + ndata["transitionType"] = "custom" + ndata["custom"] = block + ndata.pop("predefined", None) + else: + predefined_type = ( + predefined.get("predefinedType") + or ndata.get("predefinedType") + or (ndata.get("condition") if isinstance(ndata.get("condition"), str) else None) + or "when_intent_matched" + ) + block = {"predefinedType": predefined_type} + # An intent name or file type stored only as ``conditionValue`` (older + # shapes) still names it, as on development. + legacy_value = next( + (v for v in (predefined.get("conditionValue"), ndata.get("conditionValue")) if isinstance(v, str) and v), + None, + ) + intent_name = predefined.get("intentName") or ndata.get("intentName") + if not intent_name and predefined_type == "when_intent_matched": + intent_name = legacy_value or intent_name + if intent_name is not None: + block["intentName"] = intent_name + file_type = predefined.get("fileType") or ndata.get("fileType") + if not file_type and predefined_type == "when_file_received": + file_type = legacy_value or file_type + if file_type is not None: + block["fileType"] = file_type + form_gui_id = predefined.get("formGuiId") or ndata.get("formGuiId") + if form_gui_id: + block["formGuiId"] = form_gui_id + cv = predefined.get("conditionValue") + if cv is None: + if ndata.get("variable") is not None or ndata.get("operator") is not None: + cv = { + "variable": ndata.get("variable", ""), + "operator": ndata.get("operator", ""), + "targetValue": ndata.get("targetValue", ""), + } + else: + cv = ndata.get("conditionValue") + if cv is not None: + block["conditionValue"] = cv + ndata["transitionType"] = "predefined" + ndata["predefined"] = block + ndata.pop("custom", None) + nedge["data"] = ndata + out.append(nedge) + return out + + +_FILE_MIME_MAP = { + "pdf": "application/pdf", + "txt": "text/plain", + "json": "application/json", + "csv": "text/csv", + "xml": "text/xml", + "png": "image/png", + "jpg": "image/jpeg", + "jpeg": "image/jpeg", + "gif": "image/gif", + "mp3": "audio/mpeg", + "mp4": "video/mp4", +} + + def process_agent_diagram(json_data, warnings: Optional[list] = None): - """Build the B-UML ``Agent`` of an agent diagram's JSON, validated. + """Process an Agent Diagram in the v4 wire shape and return an Agent, validated. + + Canvas: ``model.nodes`` (``AgentState`` with inline ``data.bodies`` / + ``data.fallbackBodies`` action rows, ``comment``) and ``model.edges`` + (``AgentStateTransition``, ``CommentLink``). Off-canvas components come + from ``model.components`` and the legacy locations merged by + :func:`collect_agent_components`. Pass a ``warnings`` list where the agent is exported or converted rather than run: two transitions BAF cannot run are then reported there (and logged) @@ -368,11 +652,19 @@ def process_agent_diagram(json_data, warnings: Optional[list] = None): kept. Agent generation and the simulator pass none, so both raise. """ first_warning = len(warnings) if warnings is not None else 0 - # Extract language from config if present - config = json_data.get('config') or {} + # The diagram's config envelope is canonical (the editor writes it); a + # ``model.config`` from agent_buml_to_json is read underneath it. + reject_unreadable_model(json_data, "AgentDiagram") + model_config = (json_data.get('model') or {}).get('config') + envelope_config = json_data.get('config') + config = { + **(model_config if isinstance(model_config, dict) else {}), + **(envelope_config if isinstance(envelope_config, dict) else {}), + } lang_value = config.get('language', '') language = lang_value.lower() if isinstance(lang_value, str) and lang_value else None source_language = config.get('source_language') + def translate_text(text, lang, src_lang=None): # Use deep-translator's GoogleTranslator for free translation if not lang or lang == 'none': @@ -383,8 +675,7 @@ def translate_text(text, lang, src_lang=None): return text src_code = lang_map.get(src_lang.lower()) if src_lang and isinstance(src_lang, str) else 'auto' try: - translated = GoogleTranslator(source=src_code, target=target_lang).translate(text) - return translated + return GoogleTranslator(source=src_code, target=target_lang).translate(text) except Exception as e: logger.error("Translation error: %s", e) return text @@ -402,53 +693,42 @@ def build_db_reply(element: dict) -> DBReply: send_reply=bool(element.get("sendReply", True)), ) - """Process Agent Diagram specific elements and return an Agent model.""" - # Create the agent model - title = sanitize_name(json_data.get('title', 'Generated_Agent')) + title = sanitize_name(json_data.get('title') or 'Generated_Agent') agent = Agent(title) # States, intents, transitions, tools, skills, workspaces and RAGs take the id of the editor # element they are built from: the id a trace refers to them by. editor_ids = EditorIds() - # Get elements and relationships from the JSON data model_data = json_data.get('model') or {} - elements = model_data.get('elements') or {} - relationships = model_data.get('relationships') or {} - # Agent components (LLMs, intents, tools, skills, workspaces, RAGs) may be stored in: - # - model.components (new schema – preferred) - # - top-level agentComponents (legacy schema) - # - model.elements itself (old template / backward-compat format) - # Merge all sources; model.components wins over agentComponents for duplicate keys. - legacy_agent_components = json_data.get('agentComponents') or {} - model_components = model_data.get('components') or {} - all_components = {**legacy_agent_components, **model_components} - elements = {**elements, **all_components} - - # Track states and bodies for later reference + nodes = model_data.get('nodes') or [] + edges = model_data.get('edges') or [] + if not isinstance(nodes, list): + nodes = [] + if not isinstance(edges, list): + edges = [] + edges = _normalise_agent_transitions(edges) + nodes_by_id = {n.get("id"): n for n in nodes if isinstance(n, dict) and n.get("id")} + components = collect_agent_components(json_data) + states_by_id = {} intents_by_id = {} rag_dbs_by_id = {} rag_dbs_by_name = {} gui_defs_by_id = {} # gui_id -> {persist, width, is_form} of its AgentGUI component + comment_nodes = {} + comment_links = {} - # Store comments for later processing - comment_elements = {} # {comment_id: comment_text} - comment_links = {} # {comment_id: [linked_element_ids]} + for node in nodes: + if isinstance(node, dict) and node.get("type") in COMMENT_NODE_TYPES: + comment_nodes[node.get("id")] = node_data(node).get("name", "") - # First pass: Process intents, primitives, and comments - intent_count = 0 - for element_id, element in elements.items(): + # Components: LLMs, tools, skills, workspaces, intents, GUIs, RAG databases. + for element_id, element in components.items(): element_type = element.get("type") - if element_type == "Comments": - comment_text = element.get("name", "") - comment_elements[element_id] = comment_text - continue - elif element_type == "AgentLLM": + if element_type == "AgentLLM": llm_name = sanitize_text((element.get("name") or "").strip()) - if not llm_name: - continue - if any(existing.name == llm_name for existing in agent.llms): + if not llm_name or any(existing.name == llm_name for existing in agent.llms): continue provider = (element.get("provider") or "openai").lower() llm_parameters = element.get("parameters") @@ -459,20 +739,16 @@ def build_db_reply(element: dict) -> DBReply: num_prev_int = int(num_prev) if num_prev is not None else 1 except (TypeError, ValueError): num_prev_int = 1 - global_ctx = element.get("global_context") or None agent.new_llm( name=llm_name, provider=provider, parameters=llm_parameters, num_previous_messages=num_prev_int, - global_context=global_ctx, + global_context=element.get("global_context") or None, ) - continue elif element_type == "AgentTool": tool_name = sanitize_text((element.get("name") or "").strip()) - if not tool_name: - continue - if any(t.name == tool_name for t in agent.tools): + if not tool_name or any(t.name == tool_name for t in agent.tools): continue tool = agent.new_tool( name=tool_name, @@ -480,12 +756,9 @@ def build_db_reply(element: dict) -> DBReply: code=element.get("code", "") or "", ) editor_ids.assign(tool, element_id) - continue elif element_type == "AgentSkill": skill_name = sanitize_text((element.get("name") or "").strip()) - if not skill_name: - continue - if any(s.name == skill_name for s in agent.skills): + if not skill_name or any(s.name == skill_name for s in agent.skills): continue skill = agent.new_skill( name=skill_name, @@ -493,12 +766,9 @@ def build_db_reply(element: dict) -> DBReply: description=element.get("description") or None, ) editor_ids.assign(skill, element_id) - continue elif element_type == "AgentWorkspace": ws_name = sanitize_text((element.get("name") or "").strip()) - if not ws_name: - continue - if any(w.name == ws_name for w in agent.workspaces): + if not ws_name or any(w.name == ws_name for w in agent.workspaces): continue writable = element.get("writable") if writable is None: @@ -514,49 +784,43 @@ def build_db_reply(element: dict) -> DBReply: max_read_bytes=int(max_read_bytes), ) editor_ids.assign(workspace, element_id) - continue - elif element_type == "AgentReasoningState": - # Reasoning states are created in the state-construction passes below. - continue elif element_type == "AgentIntent": intent_name = element.get("name") training_sentences = [] - intent_description = element.get("intent_description", None) - # Collect training sentences — IDs stored under "bodies" (canonical) or - # "ownedElements" (legacy: diagrams saved by an older panel version). + # Training sentences: ids of AgentIntentBody components under "bodies" + # (canonical) or "ownedElements" (legacy panel builds). body_id_list = element.get("bodies") or element.get("ownedElements") or [] - for body_id in body_id_list: - body_element = elements.get(body_id) - if body_element: + for body_ref in body_id_list: + body_element = components.get(body_ref) if isinstance(body_ref, str) else body_ref + if isinstance(body_element, dict): training_sentence = sanitize_text(body_element.get("name", "")) if language: training_sentence = translate_text(training_sentence, language, source_language) if training_sentence: training_sentences.append(training_sentence) - - # Create intent and add to agent - intent = Intent(intent_name, training_sentences, description=intent_description) + intent = Intent(intent_name, training_sentences, description=element.get("intent_description", None)) agent.add_intent(intent) editor_ids.assign(intent, element_id) intents_by_id[element_id] = intent - intent_count += 1 elif element_type == "AgentGUI": - resolved_gui_id = sanitize_text(element.get("gui_id", "").strip()) + resolved_gui_id = sanitize_text((element.get("gui_id") or "").strip()) if not resolved_gui_id: continue gui_defs_by_id[resolved_gui_id] = { "persist": bool(element.get("persist", True)), - "width": sanitize_text(element.get("width", "")) or None, + "width": sanitize_text(element.get("width", "") or "") or None, "is_form": bool(element.get("is_form", False)), } # The GrapesJS design becomes a B-UML GUIModel. Agent GUIs are not bound to a # class diagram, hence the empty domain model. A GUI that has not been designed # yet (guiModel null) becomes an empty GUIModel so replies referencing it resolve. + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.gui_diagram_processor import ( # noqa: E501 — lazy: avoids an import cycle + process_gui_diagram, + ) agent.add_gui_model( resolved_gui_id, process_gui_diagram(element.get("guiModel") or {}, None, DomainModel("AgentGUIDomain")), ) - continue elif element_type == "AgentRagElement": rag_name = sanitize_text((element.get("name") or "").strip()) if not rag_name: @@ -564,7 +828,6 @@ def build_db_reply(element: dict) -> DBReply: if rag_name in rag_dbs_by_name: rag_dbs_by_id[element_id] = rag_dbs_by_name[rag_name] continue - sanitized_slug = rag_name.lower().replace(' ', '_') or "default" embedding_provider = (element.get("embedding_provider") or "openai").lower() if embedding_provider == "ollama": @@ -584,10 +847,11 @@ def build_db_reply(element: dict) -> DBReply: chunk_size=1000, chunk_overlap=100, ) + # The LLM is referenced by name; an empty value means "resolve the + # agent default at codegen time". rag_llm_name = sanitize_text((element.get("llm_name") or element.get("llm") or "").strip()) or "" rag_llm_prompt_raw = element.get("llm_prompt") or element.get("llmPrompt") or "" rag_llm_prompt = sanitize_text(rag_llm_prompt_raw.strip()) or None - raw_k = element.get("k") try: rag_k = int(raw_k) if raw_k is not None else 4 @@ -595,7 +859,6 @@ def build_db_reply(element: dict) -> DBReply: rag_k = 4 if rag_k <= 0: rag_k = 4 - raw_npm = element.get("num_previous_messages") if raw_npm is None: raw_npm = element.get("numPreviousMessages") @@ -605,7 +868,6 @@ def build_db_reply(element: dict) -> DBReply: rag_num_previous_messages = 0 if rag_num_previous_messages < 0: rag_num_previous_messages = 0 - rag_use_hybrid = bool(element.get("use_hybrid_rag", False)) raw_bm25 = element.get("bm25_weight") try: @@ -614,7 +876,6 @@ def build_db_reply(element: dict) -> DBReply: rag_bm25_weight = 0.6 if not (0 < rag_bm25_weight < 1): rag_bm25_weight = 0.6 - rag_config = agent.new_rag( name=rag_name, vector_store=vector_store, @@ -630,122 +891,93 @@ def build_db_reply(element: dict) -> DBReply: rag_dbs_by_id[element_id] = rag_config rag_dbs_by_name[rag_name] = rag_config - def _is_reasoning_element(element: dict) -> bool: - """Return True if this element represents a ReasoningState (old or new schema).""" - if element.get("type") == "AgentReasoningState": - return True - if element.get("type") == "AgentState" and element.get("stateType") == "reasoning": - return True - return False + def _is_state_node(node: dict) -> bool: + return isinstance(node, dict) and node.get("type") in ("AgentState", "AgentReasoningState") - def _is_standard_state_element(element: dict) -> bool: - """Return True if this element represents a standard AgentState.""" - if element.get("type") == "AgentState": - return element.get("stateType", "standard") != "reasoning" - return False + def _is_reasoning_node(node: dict, data: dict) -> bool: + """Reasoning states: ``AgentState`` + ``data.stateType == 'reasoning'`` (canonical) + or the legacy ``AgentReasoningState`` node type.""" + if node.get("type") == "AgentReasoningState": + return True + return node.get("type") == "AgentState" and data.get("stateType") == "reasoning" - # First identify the initial state + # Initial state: the ``data.initial`` flag (canonical v4); fall back to the + # legacy ``StateInitialNode`` marker + init edge. initial_state_id = None - for element_id, element in elements.items(): - if element.get("type") in ("AgentState", "AgentReasoningState"): - # Check if this is an initial state - for rel in relationships.values(): - rel_type = rel.get("type") - if rel_type not in ("AgentStateTransition", "AgentStateTransitionInit"): - continue - target_el = rel.get("target") or {} - source_el = rel.get("source") or {} - source_elem_id = source_el.get("element", "") - if (target_el.get("element") == element_id and - elements.get(source_elem_id, {}).get("type") == "StateInitialNode"): - initial_state_id = element_id - break - if initial_state_id: + for node in nodes: + if _is_state_node(node) and node_data(node).get("initial") is True: + initial_state_id = node.get("id") + break + if initial_state_id is None: + for edge in edges: + if edge.get("type") not in ("AgentStateTransition", "AgentStateTransitionInit"): + continue + source_node = nodes_by_id.get(edge.get("source")) or {} + target_node = nodes_by_id.get(edge.get("target")) or {} + if source_node.get("type") == "StateInitialNode" and _is_state_node(target_node): + initial_state_id = target_node.get("id") break - def _build_reasoning_state(element_id: str, element: dict, is_initial: bool): - state_name = element.get("name", "") - llm_name = element.get("llm_name") or element.get("llm") + def _build_reasoning_state(node_id: str, data: dict, is_initial: bool): + state_name = data.get("name", "") or "" + llm_name = data.get("llm_name") or data.get("llm") llm_value = llm_name.strip() if isinstance(llm_name, str) and llm_name.strip() else None - kwargs = { - "name": state_name, - "llm": llm_value, - "initial": is_initial, - } - if element.get("max_steps") is not None: - kwargs["max_steps"] = int(element.get("max_steps")) - if element.get("enable_task_planning") is not None: - kwargs["enable_task_planning"] = bool(element.get("enable_task_planning")) - if element.get("stream_steps") is not None: - kwargs["stream_steps"] = bool(element.get("stream_steps")) - if element.get("system_prompt") is not None: - kwargs["system_prompt"] = element.get("system_prompt") - if element.get("fallback_message") is not None: - kwargs["fallback_message"] = element.get("fallback_message") - rs = agent.new_reasoning_state(**kwargs) - editor_ids.assign(rs, element_id) + kwargs = {"name": state_name, "llm": llm_value, "initial": is_initial} + if data.get("max_steps") is not None: + kwargs["max_steps"] = int(data.get("max_steps")) + if data.get("enable_task_planning") is not None: + kwargs["enable_task_planning"] = bool(data.get("enable_task_planning")) + if data.get("stream_steps") is not None: + kwargs["stream_steps"] = bool(data.get("stream_steps")) + if data.get("system_prompt") is not None: + kwargs["system_prompt"] = data.get("system_prompt") + if data.get("fallback_message") is not None: + kwargs["fallback_message"] = data.get("fallback_message") # Tools, skills and workspaces are registered at the agent level and - # shared by every reasoning state; the metamodel has no per-state - # subset concept, so no per-state ref lists are parsed here. - states_by_id[element_id] = rs + # shared by every reasoning state. + rs = agent.new_reasoning_state(**kwargs) + editor_ids.assign(rs, node_id) + states_by_id[node_id] = rs return rs - def _build_standard_state(element_id: str, element: dict, is_initial: bool): - """Create a standard AgentState and its body/fallback body from the new schema.""" - state_name = element.get("name", "") + def _build_agent_state(node_id: str, data: dict, is_initial: bool): + state_name = data.get("name", "") or "" agent_state = agent.new_state(name=state_name, initial=is_initial) - editor_ids.assign(agent_state, element_id) - states_by_id[element_id] = agent_state - - # Resolve action element IDs — new key "actions", backward-compat key "bodies" - action_ids = element.get("actions", element.get("bodies", [])) - body = _build_body_from_action_elements( - f"{state_name}_body", action_ids, elements, + editor_ids.assign(agent_state, node_id) + states_by_id[node_id] = agent_state + body = _build_body_from_action_rows( + f"{state_name}_body", _first_present(data, STATE_BODY_KEYS), language, source_language, translate_text, - build_db_reply_fn=build_db_reply, - gui_defs_by_id=gui_defs_by_id, + build_db_reply_fn=build_db_reply, gui_defs_by_id=gui_defs_by_id, ) if body: agent_state.set_body(body) - - # Only attach a fallback body if fallbackBodyEnabled is absent (legacy) or True - fallback_enabled = element.get("fallbackBodyEnabled", True) - if fallback_enabled: - fallback_ids = element.get("fallbackActions", element.get("fallbackBodies", [])) - fallback_body = _build_body_from_action_elements( - f"{state_name}_fallback_body", fallback_ids, elements, + # Only attach a fallback body if fallbackBodyEnabled is absent (legacy) or True. + if data.get("fallbackBodyEnabled", True): + fallback_body = _build_body_from_action_rows( + f"{state_name}_fallback_body", _first_present(data, STATE_FALLBACK_BODY_KEYS), language, source_language, translate_text, - build_db_reply_fn=build_db_reply, - gui_defs_by_id=gui_defs_by_id, + build_db_reply_fn=build_db_reply, gui_defs_by_id=gui_defs_by_id, ) if fallback_body: agent_state.set_fallback_body(fallback_body) - return agent_state - # Process the initial state first if found - if initial_state_id: - element = elements.get(initial_state_id) - if _is_reasoning_element(element): - _build_reasoning_state(initial_state_id, element, is_initial=True) + def _build_state(node: dict, is_initial: bool): + data = node_data(node) + if _is_reasoning_node(node, data): + _build_reasoning_state(node.get("id"), data, is_initial) else: - _build_standard_state(initial_state_id, element, is_initial=True) + _build_agent_state(node.get("id"), data, is_initial) - # Now process the rest of the states (including reasoning states) - for element_id, element in elements.items(): - if element_id == initial_state_id: - continue - if _is_reasoning_element(element): - _build_reasoning_state(element_id, element, is_initial=False) - elif _is_standard_state_element(element): - _build_standard_state(element_id, element, is_initial=False) - - # Build intent lookup dict for O(1) resolution during transition processing. - # Intent names are unique case-insensitively in BUML (see Agent._validate_state_intent_name_collisions), - # so we accept both exact and casefold matches. This protects against frontend personalization - # variants that emit intentName references with different casing than the intent definitions - # they were derived from — without this, the lookup misses and a duplicate Intent is created - # that never appears in agent.intents, leaving the template referencing an undefined variable. + if initial_state_id: + _build_state(nodes_by_id[initial_state_id], is_initial=True) + for node in nodes: + if _is_state_node(node) and node.get("id") != initial_state_id: + _build_state(node, is_initial=False) + + # Intent names are unique case-insensitively in BUML, so accept both exact and + # casefold matches (personalization variants may change the casing). intent_lookup = {intent.name: intent for intent in agent.intents} intent_lookup_casefold = { intent.name.casefold(): intent @@ -753,359 +985,256 @@ def _build_standard_state(element_id: str, element: dict, is_initial: bool): if isinstance(intent.name, str) } - # Third pass: Process transitions and comment links transition_count = 0 - for relationship_id, relationship in relationships.items(): - # The state a transition is being added to, and how many it had before: the one this - # relationship adds takes its id. - transition_from = None - if relationship.get("type") == "Link": - # Handle comment links - source_element_id = relationship.get("source", {}).get("element") - target_element_id = relationship.get("target", {}).get("element") - + for edge in edges: + edge_type = edge.get("type") + if edge_type in COMMENT_LINK_TYPES: + source_id = edge.get("source") + target_id = edge.get("target") comment_id = None - target_id = None - - if source_element_id in comment_elements: - comment_id = source_element_id - target_id = target_element_id - elif target_element_id in comment_elements: - comment_id = target_element_id - target_id = source_element_id - - if comment_id and target_id: - if comment_id not in comment_links: - comment_links[comment_id] = [] - comment_links[comment_id].append(target_id) - elif relationship.get("type") in ["AgentStateTransition", "AgentStateTransitionInit"]: - source_id = relationship.get("source", {}).get("element") - target_id = relationship.get("target", {}).get("element") - - # Skip initial node transitions (already handled when creating states) - if elements.get(source_id, {}).get("type") == "StateInitialNode": - continue - - source_state = states_by_id.get(source_id) - target_state = states_by_id.get(target_id) - - if not source_state or not target_state: - logger.warning( - "Skipping agent transition: source '%s' or target '%s' state not found.", - source_id, target_id - ) - continue + target = None + if source_id in comment_nodes: + comment_id, target = source_id, target_id + elif target_id in comment_nodes: + comment_id, target = target_id, source_id + if comment_id and target: + comment_links.setdefault(comment_id, []).append(target) + continue + if edge_type not in ("AgentStateTransition", "AgentStateTransitionInit"): + continue - if source_state and target_state: - transition_from = (source_state, len(source_state.transitions)) - transition_type = relationship.get("transitionType") - predefined_block = relationship.get("predefined") or {} - custom_block = relationship.get("custom") or {} + source_id = edge.get("source") + target_id = edge.get("target") + if (nodes_by_id.get(source_id) or {}).get("type") == "StateInitialNode": + continue + source_state = states_by_id.get(source_id) + target_state = states_by_id.get(target_id) + if not source_state or not target_state: + logger.warning( + "Skipping agent transition: source '%s' or target '%s' state not found.", + source_id, target_id, + ) + continue - condition_name = "" + # The transition this edge adds takes its id. + transitions_before = len(source_state.transitions) + edge_data = edge.get("data") or {} + predefined_block = edge_data.get("predefined") or {} + custom_block = edge_data.get("custom") or {} + + if edge_data.get("transitionType") == "custom": + selected_event = custom_block.get("event") + custom_conditions = custom_block.get("condition") + if not isinstance(custom_conditions, list): + custom_conditions = [] + normalized_event = "None" + if isinstance(selected_event, str) and selected_event and selected_event != "None": + normalized_event = selected_event + condition_name = "custom_transition" + transition_payload = {"event": normalized_event, "conditions": custom_conditions} + if custom_block.get("guiEventGuiId"): + transition_payload["guiEventGuiId"] = custom_block.get("guiEventGuiId") + else: + condition_name = predefined_block.get("predefinedType") or "" + if condition_name == "when_intent_matched": + transition_payload = predefined_block.get("intentName") + elif condition_name == "when_file_received": + transition_payload = predefined_block.get("fileType") + elif condition_name == "when_form_submitted": + transition_payload = predefined_block.get("formGuiId") or "" + else: + transition_payload = predefined_block.get("conditionValue") + if transition_payload is None: transition_payload = "" - is_custom_transition = ( - transition_type == "custom" + if condition_name == "when_intent_matched": + intent_to_match = intent_lookup.get(transition_payload) + if intent_to_match is None and isinstance(transition_payload, str): + intent_to_match = intent_lookup_casefold.get(transition_payload.casefold()) + if intent_to_match: + source_state.when_intent_matched(intent_to_match).go_to(target_state) + transition_count += 1 + elif isinstance(transition_payload, str) and transition_payload.strip(): + unresolved_intent = Intent(transition_payload.strip()) + TransitionBuilder( + source=source_state, + event=ReceiveTextEvent(), + conditions=[IntentMatcher(unresolved_intent)], + ).go_to(target_state) + transition_count += 1 + else: + message = ( + f"Transition from '{source_state.name}' to '{target_state.name}' is " + "'when_intent_matched' but names no intent. Select the intent that " + "triggers it, or use 'auto' to continue without waiting, or " + "'when_no_intent_matched' for a fallback transition." ) - - if is_custom_transition: - selected_event = ( - custom_block.get("event") - or relationship.get("event") - or relationship.get("customEvent") - ) - custom_conditions = ( - custom_block.get("condition") - if isinstance(custom_block.get("condition"), list) - else relationship.get("conditions") + if warnings is None: + raise ValueError(message) + warnings.append(f"{message} It was left out.") + + elif condition_name == "when_no_intent_matched": + source_state.when_no_intent_matched().go_to(target_state) + transition_count += 1 + + elif condition_name == "when_variable_operation_matched": + if isinstance(transition_payload, dict): + variable_name = transition_payload.get("variable") + operator_value = transition_payload.get("operator") + target_value = transition_payload.get("targetValue") + if not variable_name or not operator_value: + logger.warning( + "Incomplete variable operation condition (variable=%s, operator=%s) " + "for transition from '%s' to '%s'. Falling back to no_intent_matched.", + variable_name, operator_value, source_state.name, target_state.name, ) - if not isinstance(custom_conditions, list): - custom_conditions = relationship.get("customConditions") - if not isinstance(custom_conditions, list): - custom_conditions = [] - - normalized_event = "None" - if isinstance(selected_event, str) and selected_event and selected_event != "None": - normalized_event = selected_event - condition_name = "custom_transition" - transition_payload = { - "event": normalized_event, - "conditions": custom_conditions if isinstance(custom_conditions, list) else [], - } - # Carry GUIEvent.message_id through so GUIEvent round-trips correctly. - _gui_mid = ( - custom_block.get("guiEventGuiId") - or relationship.get("guiEventGuiId") - ) - if _gui_mid: - transition_payload["guiEventGuiId"] = _gui_mid + source_state.when_no_intent_matched().go_to(target_state) + transition_count += 1 else: - condition_name = ( - predefined_block.get("predefinedType") - or relationship.get("predefinedType") - or "" - ) - if condition_name == "when_intent_matched": - transition_payload = ( - predefined_block.get("intentName") - or relationship.get("intentName") - ) - elif condition_name == "when_file_received": - transition_payload = ( - predefined_block.get("fileType") - or relationship.get("fileType") - ) - else: - transition_payload = predefined_block.get("conditionValue") - - if transition_payload is None: - transition_payload = relationship.get("conditionValue", "") - - # Create appropriate transition based on condition - if condition_name == "when_intent_matched": - # Find the intent by name via O(1) lookup, falling back to a - # case-insensitive match so personalization variants whose JSON - # uses a different casing than the intent definition still resolve - # to the same intent object. - intent_to_match = intent_lookup.get(transition_payload) - if intent_to_match is None and isinstance(transition_payload, str): - intent_to_match = intent_lookup_casefold.get(transition_payload.casefold()) - - if intent_to_match: - source_state.when_intent_matched(intent_to_match).go_to(target_state) - transition_count += 1 - elif isinstance(transition_payload, str) and transition_payload.strip(): - unresolved_intent = Intent(transition_payload.strip()) - TransitionBuilder( - source=source_state, - event=ReceiveTextEvent(), - conditions=[IntentMatcher(unresolved_intent)], + operator_map = { + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + ">=": operator.ge, + ">": operator.gt, + "!=": operator.ne, + } + op_func = operator_map.get(operator_value) + if op_func: + source_state.when_variable_matches_operation( + var_name=variable_name, + operation=op_func, + target=target_value, ).go_to(target_state) transition_count += 1 else: - message = ( - f"Transition from '{source_state.name}' to '{target_state.name}' is " - "'when_intent_matched' but names no intent. Select the intent that " - "triggers it, or use 'auto' to continue without waiting, or " - "'when_no_intent_matched' for a fallback transition." - ) - if warnings is None: - raise ValueError(message) - warnings.append(f"{message} It was left out.") - - elif condition_name == "when_no_intent_matched": - source_state.when_no_intent_matched().go_to(target_state) - transition_count += 1 - - elif condition_name == "when_variable_operation_matched": - # Check if transition payload is a dictionary - if isinstance(transition_payload, dict): - variable_name = transition_payload.get("variable") - operator_value = transition_payload.get("operator") - target_value = transition_payload.get("targetValue") - - if not variable_name or not operator_value: - logger.warning( - "Incomplete variable operation condition (variable=%s, operator=%s) " - "for transition from '%s' to '%s'. Falling back to no_intent_matched.", - variable_name, operator_value, - source_state.name, target_state.name, - ) - source_state.when_no_intent_matched().go_to(target_state) - transition_count += 1 - else: - # Map string operators to actual operator functions - operator_map = { - "<": operator.lt, - "<=": operator.le, - "==": operator.eq, - ">=": operator.ge, - ">": operator.gt, - "!=": operator.ne - } - - op_func = operator_map.get(operator_value) - if op_func: - source_state.when_variable_matches_operation( - var_name=variable_name, - operation=op_func, - target=target_value - ).go_to(target_state) - transition_count += 1 - else: - logger.warning( - "Unknown operator '%s' for variable operation transition " - "from '%s' to '%s'. Skipping.", - operator_value, source_state.name, target_state.name, - ) - else: - # If transition_payload is not a dictionary, add a simple transition logger.warning( - "Expected dict for when_variable_operation_matched condition but got %s. " - "Falling back to no_intent_matched for transition from '%s' to '%s'.", - type(transition_payload).__name__, source_state.name, target_state.name, + "Unknown operator '%s' for variable operation transition from '%s' to '%s'. Skipping.", + operator_value, source_state.name, target_state.name, ) - source_state.when_no_intent_matched().go_to(target_state) - transition_count += 1 - - elif condition_name == "when_form_submitted": - form_gui_id = ( - predefined_block.get("formGuiId") - or relationship.get("formGuiId") - or "" - ) - form_id = form_gui_id if form_gui_id else None - source_state.when_form_submitted(form_id=form_id).go_to(target_state) - transition_count += 1 - - elif condition_name == "when_file_received": - _mime_map = { - "pdf": "application/pdf", - "txt": "text/plain", - "json": "application/json", - "csv": "text/csv", - "xml": "text/xml", - "png": "image/png", - "jpg": "image/jpeg", - "jpeg": "image/jpeg", - "gif": "image/gif", - "mp3": "audio/mpeg", - "mp4": "video/mp4", - } - if isinstance(transition_payload, str) and transition_payload.strip(): - tokens = [t.strip() for t in transition_payload.split(",") if t.strip()] - resolved = [ - token if "/" in token else _mime_map.get(token.lower(), token) - for token in tokens - ] - if len(resolved) == 1: - source_state.when_file_received(resolved[0]).go_to(target_state) - else: - source_state.when_file_received(resolved).go_to(target_state) - else: - source_state.when_file_received().go_to(target_state) - transition_count += 1 - - elif condition_name == "auto": - source_state.go_to(target_state) - transition_count += 1 - - elif condition_name == "custom_transition": - event_instance = None - custom_conditions = [] - - if isinstance(transition_payload, dict): - selected_event = transition_payload.get("event") - # Backward compatibility for older payloads that used "events": [..] - if not selected_event: - raw_events = transition_payload.get("events") or [] - if isinstance(raw_events, list) and raw_events: - selected_event = raw_events[0] - - if selected_event == "ReceiveTextEvent": - event_instance = ReceiveTextEvent() - elif selected_event == "ReceiveMessageEvent": - event_instance = ReceiveMessageEvent("") - elif selected_event == "ReceiveJSONEvent": - event_instance = ReceiveJSONEvent() - elif selected_event == "ReceiveFileEvent": - event_instance = ReceiveFileEvent() - elif selected_event == "DummyEvent": - event_instance = DummyEvent() - elif selected_event == "WildcardEvent": - event_instance = WildcardEvent() - elif selected_event == "GUIEvent": - gui_event_gui_id = transition_payload.get("guiEventGuiId", "") - message_id = gui_event_gui_id if gui_event_gui_id else None - event_instance = GUIEvent(message_id=message_id) - elif selected_event == "None": - event_instance = None - - raw_conditions = transition_payload.get("conditions") or [] - if isinstance(raw_conditions, list): - custom_conditions = [c for c in raw_conditions if isinstance(c, str) and c.strip()] - - condition_objects = [] - for condition_index, custom_condition_code in enumerate(custom_conditions, start=1): - generated_name = f"condition_{transition_count + 1}_{condition_index}" - custom_condition = Condition(name=generated_name, callable=None) - # The generated agent wires the transition to ``generated_name``, so the - # function must carry that name whatever the author called it (the - # editor's template is ``def condition(...)``): two transitions would - # otherwise collide, or reference a function that does not exist. - custom_condition.code = rename_condition_function(custom_condition_code, generated_name) - condition_objects.append(custom_condition) - - transition_builder = None - if event_instance is not None: - transition_builder = source_state.when_event(event_instance) - - if condition_objects: - if transition_builder is None: - transition_builder = source_state.when_condition(condition_objects[0]) - for extra_condition in condition_objects[1:]: - transition_builder.with_condition(extra_condition) - else: - for custom_condition in condition_objects: - transition_builder.with_condition(custom_condition) - - if transition_builder is not None: - transition_builder.go_to(target_state) - transition_count += 1 - else: - source_state.go_to(target_state) - transition_count += 1 - + else: + logger.warning( + "Expected dict for when_variable_operation_matched condition but got %s. " + "Falling back to no_intent_matched for transition from '%s' to '%s'.", + type(transition_payload).__name__, source_state.name, target_state.name, + ) + source_state.when_no_intent_matched().go_to(target_state) + transition_count += 1 + + elif condition_name == "when_form_submitted": + form_id = transition_payload if isinstance(transition_payload, str) and transition_payload else None + source_state.when_form_submitted(form_id=form_id).go_to(target_state) + transition_count += 1 + + elif condition_name == "when_file_received": + # Comma-separated list of MIME types or short extensions (pdf, csv, ...). + if isinstance(transition_payload, str) and transition_payload.strip(): + tokens = [t.strip() for t in transition_payload.split(",") if t.strip()] + resolved = [ + token if "/" in token else _FILE_MIME_MAP.get(token.lower(), token) + for token in tokens + ] + if len(resolved) == 1: + source_state.when_file_received(resolved[0]).go_to(target_state) else: - # Default to no_intent_matched if no condition specified - source_state.when_no_intent_matched().go_to(target_state) - transition_count += 1 + source_state.when_file_received(resolved).go_to(target_state) + else: + source_state.when_file_received().go_to(target_state) + transition_count += 1 + + elif condition_name == "auto": + source_state.go_to(target_state) + transition_count += 1 + + elif condition_name == "custom_transition": + event_instance = None + custom_conditions = [] + if isinstance(transition_payload, dict): + selected_event = transition_payload.get("event") + if selected_event == "ReceiveTextEvent": + event_instance = ReceiveTextEvent() + elif selected_event == "ReceiveMessageEvent": + event_instance = ReceiveMessageEvent("") + elif selected_event == "ReceiveJSONEvent": + event_instance = ReceiveJSONEvent() + elif selected_event == "ReceiveFileEvent": + event_instance = ReceiveFileEvent() + elif selected_event == "DummyEvent": + event_instance = DummyEvent() + elif selected_event == "WildcardEvent": + event_instance = WildcardEvent() + elif selected_event == "GUIEvent": + message_id = transition_payload.get("guiEventGuiId") or None + event_instance = GUIEvent(message_id=message_id) + raw_conditions = transition_payload.get("conditions") or [] + if isinstance(raw_conditions, list): + custom_conditions = [c for c in raw_conditions if isinstance(c, str) and c.strip()] + + condition_objects = [] + for condition_index, custom_condition_code in enumerate(custom_conditions, start=1): + generated_name = f"condition_{transition_count + 1}_{condition_index}" + custom_condition = Condition(name=generated_name, callable=None) + # The generated agent wires the transition to ``generated_name``, so the + # function must carry that name whatever the author called it (the + # editor's template is ``def condition(...)``): two transitions would + # otherwise collide, or reference a function that does not exist. + custom_condition.code = rename_condition_function(custom_condition_code, generated_name) + condition_objects.append(custom_condition) + + transition_builder = None + if event_instance is not None: + transition_builder = source_state.when_event(event_instance) + if condition_objects: + if transition_builder is None: + transition_builder = source_state.when_condition(condition_objects[0]) + for extra_condition in condition_objects[1:]: + transition_builder.with_condition(extra_condition) + else: + for custom_condition in condition_objects: + transition_builder.with_condition(custom_condition) + if transition_builder is not None: + transition_builder.go_to(target_state) + else: + source_state.go_to(target_state) + transition_count += 1 - if transition_from is not None: - state, before = transition_from - if len(state.transitions) == before + 1: - editor_ids.assign(state.transitions[-1], relationship.get("id") or relationship_id) + else: + source_state.when_no_intent_matched().go_to(target_state) + transition_count += 1 + + if len(source_state.transitions) == transitions_before + 1: + editor_ids.assign(source_state.transitions[-1], edge.get("id")) - # Process comments - for comment_id, comment_text in comment_elements.items(): + for comment_id, comment_text in comment_nodes.items(): if comment_id in comment_links: - # Comment is linked to one or more elements - for linked_element_id in comment_links[comment_id]: - if linked_element_id in states_by_id: - # Apply comment to state's metadata - state = states_by_id[linked_element_id] + for linked_id in comment_links[comment_id]: + if linked_id in states_by_id: + state = states_by_id[linked_id] if state.metadata is None: state.metadata = Metadata(description=comment_text) else: - # Append to existing description existing_desc = state.metadata.description or "" state.metadata.description = ( f"{existing_desc}\n{comment_text}" if existing_desc else comment_text ) else: - # Unlinked comment - add to Agent metadata if agent.metadata is None: agent.metadata = Metadata(description=comment_text) else: - # Append to existing description existing_desc = agent.metadata.description or "" agent.metadata.description = f"{existing_desc}\n{comment_text}" if existing_desc else comment_text - # Apply default LLM from the customization config block (if set). - # The customization tab persists which registered LLM is the default; - # without an explicit pointer the agent already auto-defaulted to the - # first one registered. + # Apply the default LLM from the diagram config block (if set); without an + # explicit pointer the agent already auto-defaulted to the first one registered. default_llm_name_cfg = (config or {}).get("default_llm_name") if isinstance(default_llm_name_cfg, str) and default_llm_name_cfg.strip(): if any(existing.name == default_llm_name_cfg for existing in agent.llms): agent.set_default_llm(default_llm_name_cfg) - # Validate the agent model at build time so all callers get validation for free + # Validate the agent model at build time so all callers get validation for free. agent.validate(raise_exception=True, check_auto_transitions=warnings is None) if warnings is not None: warnings.extend(agent.auto_transition_problems()) for message in warnings[first_warning:]: logger.warning("Agent '%s': %s", agent.name, message) - return agent diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/bpmn_diagram_processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/bpmn_diagram_processor.py index 34cef279f..8062fc3d6 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/bpmn_diagram_processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/bpmn_diagram_processor.py @@ -1,19 +1,27 @@ """BPMN processing for converting JSON to BUML format. -Returns a ``BPMNModel`` metamodel instance from the WME BPMN diagram JSON envelope. The -algorithm is the standard nodes-first / edges-second pass with a containment pass in -between. +Reads the v4 wire shape (``{nodes, edges}``) natively — mirrors +``json_to_buml/class_diagram_processor.py``. Containment follows the +``parentId`` chain, each BPMN flow kind has its own edge ``type`` (see +``docs/source/migrations/uml-v4-shape.md``), and flows are routed to their +process via ``process_of``. + +``BPMNElement.layout`` / ``BPMNConnectingObject.layout`` are declared opaque +by the metamodel (type-checked as dict-or-None, content never interpreted), +so the converters define the internal stash shape — see +``_layout_dict`` / ``_flow_layout_dict``. Design points: -* **Identity is by object**: WME ids ride in ``element.layout`` so the - converter pair can round-trip them (and the generator can reuse them as XML ids). +* **Identity is by object**: WME ids ride in ``element.layout`` so the converter + pair can round-trip them (and the generator can reuse them as XML ids). Each element and flow also takes its WME id as ``Element.id``, the id a trace refers to it by; the metamodel's own rules never read it. -* **Layout is opaque**: ``BPMNElement.layout`` carries the WME bounds / - path / stash without the metamodel ever interpreting it. -* **Validation is a separate concern**: this processor never calls ``BPMNModel.validate`` - — it only produces a ``BPMNModel``. Callers run validation if they need it. +* **Layout is opaque**: ``BPMNElement.layout`` carries the WME position / size / + points stash without the metamodel ever interpreting it. +* **Validation is a separate concern**: this processor never calls + ``BPMNModel.validate`` — it only produces a ``BPMNModel``. Callers run + validation if they need it. """ import logging @@ -53,64 +61,71 @@ ReflectionMode, ) from besser.utilities.web_modeling_editor.backend.constants.constants import ( - BPMN_DIAGRAM_TYPE, - BPMN_RELATIONSHIP_TYPE, + BPMN_DIAGRAM_TYPES, ) from besser.utilities.web_modeling_editor.backend.services.converters.bpmn_event_mapping import ( parse_event_type, ) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + absolute_bounds, edge_layout, node_data, +) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import EditorIds from besser.utilities.web_modeling_editor.backend.services.exceptions import ConversionError +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + reject_unreadable_model, +) logger = logging.getLogger(__name__) -# --------------------------------------------------------------------------- -# WME element-type → metamodel class dispatch -# --------------------------------------------------------------------------- - +# v4 node `type` (lowerCamelCase, packages/library/lib/nodes/types.ts) -> metamodel class. _EVENT_CLASSES = { - "BPMNStartEvent": StartEvent, - "BPMNIntermediateEvent": IntermediateEvent, - "BPMNEndEvent": EndEvent, + "bpmnStartEvent": StartEvent, + "bpmnIntermediateEvent": IntermediateEvent, + "bpmnEndEvent": EndEvent, } _ACTIVITY_CLASSES = { - "BPMNTask": Task, - "BPMNSubprocess": SubProcess, - "BPMNTransaction": Transaction, - "BPMNCallActivity": CallActivity, + "bpmnTask": Task, + "bpmnSubprocess": SubProcess, + "bpmnTransaction": Transaction, + "bpmnCallActivity": CallActivity, } +# v4 edge `type` -> BUML connecting-object class (versionConverter.ts convertV3EdgeTypeToV4). +_FLOW_CLASS_FOR_EDGE_TYPE = { + "BPMNSequenceFlow": SequenceFlow, + "BPMNMessageFlow": MessageFlow, + "BPMNAssociationFlow": Association, + "BPMNDataAssociationFlow": DataAssociation, +} -def _layout_dict(elem_id: str, elem: dict) -> dict: - """Build the opaque ``layout`` passthrough for a node element. - Stores everything the converter needs to round-trip the WME shape that is *not* part - of the abstract syntax: original id, owner pointer, bounds, and any styling fields. - """ +def _layout_dict(node: dict, raw_by_id: dict) -> dict: + """Opaque layout passthrough for a node: id + parentId + absolute bounds + style keys.""" layout = { - "id": elem_id, - "owner": elem.get("owner"), - "bounds": elem.get("bounds"), + "id": node.get("id"), + "parentId": node.get("parentId"), + "bounds": absolute_bounds(node, raw_by_id), } + data = node_data(node) for style_key in ("fillColor", "strokeColor", "textColor", "highlight"): - if style_key in elem: - layout[style_key] = elem[style_key] + if style_key in data: + layout[style_key] = data[style_key] return layout -def _flow_layout_dict(rel_id: str, rel: dict) -> dict: - """Build the opaque ``layout`` passthrough for a relationship element.""" - return { - "id": rel_id, - "owner": rel.get("owner"), - "bounds": rel.get("bounds"), - "path": rel.get("path"), - "source_direction": (rel.get("source") or {}).get("direction"), - "target_direction": (rel.get("target") or {}).get("direction"), - "isManuallyLayouted": rel.get("isManuallyLayouted", False), - } +def _flow_layout_dict(edge: dict) -> dict: + """Opaque layout passthrough for an edge (flow).""" + layout = edge_layout(edge) + # ``path`` feeds the BPMN generator's BPMNEdge DI waypoints. With no + # ``bounds`` offset in the layout it is read as absolute, so the user's + # routing is kept whenever it starts and ends on the two shapes. + layout["path"] = list(layout["points"]) or None + return layout + + +_AGENT_ROLE_ALIASES = {"worker": "solution", "manager": "supervision"} def _clamp_trust_score(value) -> int: @@ -131,63 +146,53 @@ def _clamp_swarm_size(value) -> int: return max(1, n) -def _build_node(elem: dict): - """Construct the metamodel object for one WME ``elements[id]`` entry. +def _build_node(node: dict): + """Construct the metamodel object for one v4 ``nodes[]`` entry, or ``None`` for + an unknown type. Raises ConversionError for a known type with an unrecognised + enum string. Agentic variants (``data.isAgentic``) build ``AgenticTask`` / + ``AgenticGateway`` / ``AgenticLane``.""" + node_type = node.get("type") + data = node_data(node) + name = data.get("name", "") or "" - Returns ``None`` for unknown types (caller logs and skips). Pool elements are - constructed *with* their ``Process`` so containment in pass 2 has somewhere to land. - - Raises: - ConversionError: if a known WME type carries an unrecognised enum string for one - of its subtype attributes. - """ - elem_type = elem.get("type") - name = elem.get("name", "") or "" - - if elem_type in _ACTIVITY_CLASSES: - cls = _ACTIVITY_CLASSES[elem_type] + if node_type in _ACTIVITY_CLASSES: + cls = _ACTIVITY_CLASSES[node_type] try: - loop = LoopCharacteristics(elem.get("marker", "none") or "none") + loop = LoopCharacteristics(data.get("marker", "none") or "none") except ValueError as exc: raise ConversionError( - f"Unknown BPMN loop marker '{elem.get('marker')}' on element '{name}'." + f"Unknown BPMN loop marker '{data.get('marker')}' on element '{name}'." ) from exc if cls is Task: try: - task_type = TaskType(elem.get("taskType", "default") or "default") + task_type = TaskType(data.get("taskType", "default") or "default") except ValueError as exc: raise ConversionError( - f"Unknown BPMN task type '{elem.get('taskType')}' on Task '{name}'." + f"Unknown BPMN task type '{data.get('taskType')}' on Task '{name}'." ) from exc - if elem.get("isAgentic"): - reflection_value = elem.get("reflectionMode", "none") or "none" + if data.get("isAgentic"): + reflection_value = data.get("reflectionMode", "none") or "none" try: reflection = ReflectionMode(reflection_value) except ValueError as exc: raise ConversionError( f"Unknown reflectionMode '{reflection_value}' on AgenticTask '{name}'." ) from exc - - trust = _clamp_trust_score(elem.get("trustScore", 0)) - agent_ref = elem.get("agentDiagramRef") or None - return AgenticTask( name=name, task_type=task_type, loop_characteristics=loop, reflection_mode=reflection, - trust_score=trust, - agent_diagram_ref=agent_ref, - reflection_reviewer_lane_id=elem.get("reflectionReviewerLaneId") or None, + trust_score=_clamp_trust_score(data.get("trustScore", 0)), + agent_diagram_ref=data.get("agentDiagramRef") or None, + reflection_reviewer_lane_id=data.get("reflectionReviewerLaneId") or None, ) - return Task(name=name, task_type=task_type, loop_characteristics=loop) - # SubProcess / Transaction / CallActivity all take the same args (no task_type). return cls(name=name, loop_characteristics=loop) - if elem_type in _EVENT_CLASSES: - cls = _EVENT_CLASSES[elem_type] - event_type = elem.get("eventType", "default") or "default" + if node_type in _EVENT_CLASSES: + cls = _EVENT_CLASSES[node_type] + event_type = data.get("eventType", "default") or "default" try: direction, definition = parse_event_type(cls, event_type) except ValueError as exc: @@ -196,33 +201,29 @@ def _build_node(elem: dict): ) from exc return cls(name=name, direction=direction, event_definition=definition) - if elem_type == "BPMNGateway": + if node_type == "bpmnGateway": try: - gateway_type = GatewayType(elem.get("gatewayType", "exclusive") or "exclusive") + gateway_type = GatewayType(data.get("gatewayType", "exclusive") or "exclusive") except ValueError as exc: raise ConversionError( - f"Unknown BPMN gateway type '{elem.get('gatewayType')}' on Gateway '{name}'." + f"Unknown BPMN gateway type '{data.get('gatewayType')}' on Gateway '{name}'." ) from exc - if elem.get("isAgentic"): + if data.get("isAgentic"): try: - role = GatewayRole(elem.get("gatewayRole", "diverging") or "diverging") + role = GatewayRole(data.get("gatewayRole", "diverging") or "diverging") except ValueError as exc: raise ConversionError( - f"Unknown gatewayRole '{elem.get('gatewayRole')}' " + f"Unknown gatewayRole '{data.get('gatewayRole')}' " f"on AgenticGateway '{name}'." ) from exc - - trust = _clamp_trust_score(elem.get("trustScore", 0)) - - gov = elem.get("governanceDsl") + gov = data.get("governanceDsl") gov = gov if (isinstance(gov, str) and gov.strip() != "") else None - try: return AgenticGateway( name=name, gateway_type=gateway_type, gateway_role=role, - trust_score=trust, + trust_score=_clamp_trust_score(data.get("trustScore", 0)), governance_dsl=gov, ) except ValueError as exc: @@ -232,62 +233,58 @@ def _build_node(elem: dict): return Gateway(name=name, gateway_type=gateway_type) - if elem_type == "BPMNDataObject": + if node_type == "bpmnDataObject": return DataObject(name=name) - if elem_type == "BPMNDataStore": + if node_type == "bpmnDataStore": return DataStore(name=name) - if elem_type == "BPMNAnnotation": - # WME stores the annotation body in `name`; the metamodel keeps it in `text`. + if node_type == "bpmnAnnotation": return TextAnnotation(name="", text=name) - if elem_type == "BPMNGroup": + if node_type == "bpmnGroup": return Group(name=name) - if elem_type == "BPMNSwimlane": - if elem.get("isAgentic"): - # SEAA'25 «AgenticLane» (paper §4.1 Fig 3a). - role_value = elem.get("role", "solution") or "solution" - # Accept the editor's former role values (worker / manager) transparently. - _ROLE_ALIASES = {"worker": "solution", "manager": "supervision"} - role_value = _ROLE_ALIASES.get(role_value, role_value) + if node_type == "bpmnSwimlane": + # packages/library/lib/nodes/bpmn/BPMNSwimlane.tsx — a lane is a child + # (parentId) of its bpmnPool. + if data.get("isAgentic"): + # «AgenticLane». The editor's former role values (worker / manager) + # are accepted as aliases. + role_value = data.get("role", "solution") or "solution" + role_value = _AGENT_ROLE_ALIASES.get(role_value, role_value) try: role = AgentRole(role_value) except ValueError as exc: raise ConversionError( f"Unknown role '{role_value}' on AgenticLane '{name}'." ) from exc - trust = _clamp_trust_score(elem.get("trustScore", 0)) - # Optional opaque AgentDiagram id. Empty string / absent → None. - # No UUID validation — pass through verbatim. - agent_ref = elem.get("agentDiagramRef") or None - # Swarm size; absent → 1 (single agent). - swarm_size = _clamp_swarm_size(elem.get("multiplicity", 1)) - return AgenticLane(name=name, role=role, trust_score=trust, - agent_diagram_ref=agent_ref, - swarm_size=swarm_size) + return AgenticLane( + name=name, + role=role, + trust_score=_clamp_trust_score(data.get("trustScore", 0)), + # Opaque AgentDiagram id, passed through verbatim; "" -> None. + agent_diagram_ref=data.get("agentDiagramRef") or None, + # Swarm size travels as `multiplicity`; absent -> 1 (single agent). + swarm_size=_clamp_swarm_size(data.get("multiplicity", 1)), + ) return Lane(name=name) - if elem_type == "BPMNPool": - # Build the Pool's Process eagerly so pass 2 containment can attach to it. + if node_type == "bpmnPool": return Participant(name=name, process=Process(name=name)) return None -def _build_flow(rel: dict, source, target): - """Construct the metamodel flow object for one WME ``relationships[id]`` entry. +def _build_flow(edge: dict, source, target): + """Construct the metamodel flow object for one v4 ``edges[]`` entry.""" + edge_data = edge.get("data") or {} + # BPMNDiagramEdge.tsx renders data.label; name kept for parity with every + # other v4 edge type's authoring convention (class associations, StateTransition...). + name = edge_data.get("name") or edge_data.get("label") or "" - Branches on ``flowType``. Wraps ``is_default``: an illegal value (WME source can't - legally carry a default) downgrades to ``False`` with a warning rather than aborting. + flow_cls = _FLOW_CLASS_FOR_EDGE_TYPE.get(edge.get("type")) + if flow_cls is None: + raise ConversionError(f"Unknown BPMN edge type '{edge.get('type')}' on relationship '{name}'.") - Raises: - ConversionError: if ``flowType`` is missing or unknown. - TypeError / ValueError: if endpoint types violate the connecting object's rules - (caller logs and skips). - """ - name = rel.get("name", "") or "" - flow_type = rel.get("flowType") - - if flow_type == "sequence": + if flow_cls is SequenceFlow: flow = SequenceFlow(source=source, target=target, name=name) - if rel.get("isDefault"): + if edge_data.get("isDefault"): try: flow.is_default = True except ValueError as exc: @@ -296,139 +293,119 @@ def _build_flow(rel: dict, source, target): "downgrading to is_default=False.", name, exc, ) return flow - if flow_type == "message": - return MessageFlow(source=source, target=target, name=name) - if flow_type == "association": - return Association(source=source, target=target, name=name) - if flow_type == "data association": - return DataAssociation(source=source, target=target, name=name) - - raise ConversionError(f"Unknown BPMN flowType '{flow_type}' on relationship '{name}'.") + return flow_cls(source=source, target=target, name=name) def _outer_process(container): - """Walk ``SubProcess`` containment up to the enclosing ``Process``, or ``None``.""" while isinstance(container, SubProcess): container = container.container return container if isinstance(container, Process) else None def process_bpmn_diagram(json_data: dict) -> BPMNModel: - """Convert a WME BPMN diagram (JSON) into a ``BPMNModel`` instance. - - Args: - json_data: Dictionary with the standard Apollon ``UMLModel`` envelope; the BPMN - payload sits under ``json_data["model"]`` with ``elements`` (nodes) and - ``relationships`` (flows) maps keyed by id. + """Convert a v4 BPMN diagram (``{nodes, edges}``) into a ``BPMNModel``. + v3-shape input is not supported — mirrors process_class_diagram's contract. Returns: ``BPMNModel``. ``model.collaboration`` is ``None`` for a pool-less diagram and a ``Collaboration`` (with one ``Participant`` per pool) otherwise. Raises: - ConversionError: structural failures (missing ``model`` key, unknown WME element - type with no metamodel mapping, unknown enum strings, unknown ``flowType``). - Non-fatal cases (dangling flow endpoint, illegal ``isDefault``) log and skip. + ConversionError: structural failures (missing ``model`` key, unknown enum + strings, unknown BPMN edge type). Non-fatal cases (dangling flow + endpoint, unknown node type, illegal ``isDefault``) log and skip. """ - model_data = json_data.get("model") - if not model_data: + reject_unreadable_model(json_data, "BPMNDiagram") + title = json_data.get('title') or 'Generated_BPMN_Model' + if json_data.get('model') is None: raise ConversionError("BPMN diagram JSON is missing the 'model' key.") - - if model_data.get("type") and model_data.get("type") != BPMN_DIAGRAM_TYPE: - # Don't reject — WME may not have aligned yet. Log so the mismatch is visible. + model_payload = json_data.get('model') or {} + model_type = model_payload.get('type') + if model_type and model_type not in BPMN_DIAGRAM_TYPES: logger.warning( - "BPMN diagram envelope type is '%s', expected '%s'.", - model_data.get("type"), BPMN_DIAGRAM_TYPE, + "BPMN diagram envelope type is '%s', expected one of %s.", + model_type, BPMN_DIAGRAM_TYPES, ) - elements = model_data.get("elements") or {} - relationships = model_data.get("relationships") or {} - name = json_data.get("title") or "Generated_BPMN_Model" + nodes = model_payload.get('nodes') or [] + edges = model_payload.get('edges') or [] + if not isinstance(nodes, list): + nodes = [] + if not isinstance(edges, list): + edges = [] editor_ids = EditorIds() # --- Pass 1: build node objects (no containment yet) ------------------- - node_by_id: dict = {} - pools: list = [] # (elem_id, Participant) — preserves JSON order + raw_by_id: dict = {n.get("id"): n for n in nodes if n.get("id")} + obj_by_id: dict = {} + pools: list = [] # (node_id, Participant) — preserves JSON order - for elem_id, elem in elements.items(): + for node in nodes: + node_id = node.get("id") try: - obj = _build_node(elem) + obj = _build_node(node) except ConversionError: raise except (TypeError, ValueError) as exc: - raise ConversionError( - f"Could not build BPMN element '{elem_id}': {exc}" - ) from exc + raise ConversionError(f"Could not build BPMN element '{node_id}': {exc}") from exc if obj is None: - logger.warning( - "BPMN element '%s' has unknown type '%s'; skipping.", - elem_id, elem.get("type"), - ) + logger.warning("BPMN node '%s' has unknown type '%s'; skipping.", node_id, node.get("type")) continue - obj.layout = _layout_dict(elem_id, elem) - editor_ids.assign(obj, elem_id) - node_by_id[elem_id] = obj + obj.layout = _layout_dict(node, raw_by_id) + editor_ids.assign(obj, node_id) + obj_by_id[node_id] = obj if isinstance(obj, Participant): - pools.append((elem_id, obj)) + pools.append((node_id, obj)) - # --- Pass 2: containment via the `owner` chain -------------------------- - # `process_of` covers every placed element (FlowNode, Artifact, DataObject) so the - # flow router (Pass 3) can resolve a flow's owning Process via either endpoint. + # --- Pass 2: containment via `parentId` --------------------------------- process_of: dict = {} synthetic_process = None def _ensure_synthetic_process(): nonlocal synthetic_process if synthetic_process is None: - synthetic_process = Process(name=name) + synthetic_process = Process(name=title) return synthetic_process - # Sub-pass 2a: attach Lanes to their pool's Process first, so flow-node placement - # in 2b can route into the correct lane. - for elem_id, obj in node_by_id.items(): + for node_id, obj in obj_by_id.items(): if not isinstance(obj, Lane): continue - owner_id = elements[elem_id].get("owner") - owner_obj = node_by_id.get(owner_id) if owner_id else None - if isinstance(owner_obj, Participant) and owner_obj.process is not None: - owner_obj.process.add_lane(obj) + parent_id = (raw_by_id.get(node_id) or {}).get("parentId") + parent_obj = obj_by_id.get(parent_id) if parent_id else None + if isinstance(parent_obj, Participant) and parent_obj.process is not None: + parent_obj.process.add_lane(obj) else: - logger.warning( - "BPMN Lane '%s' has no Pool owner; orphan lane skipped.", elem_id, - ) + logger.warning("BPMN Lane '%s' has no Pool parent; orphan lane skipped.", node_id) - # Sub-pass 2b: place every other element. Skip Pools (no owner-based containment) and - # Lanes (already done) and DataStores (live on the model, not in a process). - for elem_id, obj in node_by_id.items(): + for node_id, obj in obj_by_id.items(): if isinstance(obj, (Participant, Lane, DataStore)): continue - owner_id = elements[elem_id].get("owner") - owner_obj = node_by_id.get(owner_id) if owner_id else None + parent_id = (raw_by_id.get(node_id) or {}).get("parentId") + parent_obj = obj_by_id.get(parent_id) if parent_id else None target_container = None target_lane = None - if owner_obj is None: + if parent_obj is None: target_container = _ensure_synthetic_process() - elif isinstance(owner_obj, Lane): - target_lane = owner_obj - # The lane was attached to its pool's Process in 2a — find that Process. + elif isinstance(parent_obj, Lane): + target_lane = parent_obj for _, part in pools: if part.process is not None and target_lane in part.process.lanes: target_container = part.process break if target_container is None: target_container = _ensure_synthetic_process() - elif isinstance(owner_obj, Participant): - target_container = owner_obj.process or _ensure_synthetic_process() - elif isinstance(owner_obj, SubProcess): - target_container = owner_obj + elif isinstance(parent_obj, Participant): + target_container = parent_obj.process or _ensure_synthetic_process() + elif isinstance(parent_obj, SubProcess): + target_container = parent_obj else: logger.warning( - "BPMN element '%s' has unexpected owner type '%s'; placing at top level.", - elem_id, type(owner_obj).__name__, + "BPMN element '%s' has unexpected parent type '%s'; placing at top level.", + node_id, type(parent_obj).__name__, ) target_container = _ensure_synthetic_process() @@ -446,15 +423,10 @@ def _ensure_synthetic_process(): outer.add_data_object(obj) process_of[obj] = outer - # Data stores live model-wide (BPMN spec §10.3 — root-level element). - data_stores = {obj for obj in node_by_id.values() if isinstance(obj, DataStore)} + data_stores = {obj for obj in obj_by_id.values() if isinstance(obj, DataStore)} - # --- Build collaboration / processes set ------------------------------- if pools: - collaboration = Collaboration( - name=name, - participants={part for _, part in pools}, - ) + collaboration = Collaboration(name=title, participants={part for _, part in pools}) processes = {part.process for _, part in pools if part.process is not None} else: collaboration = None @@ -462,60 +434,52 @@ def _ensure_synthetic_process(): if synthetic_process is not None: processes.add(synthetic_process) - # --- Pass 3: build flows from `relationships` -------------------------- - for rel_id, rel in relationships.items(): - if rel.get("type") != BPMN_RELATIONSHIP_TYPE: - logger.warning( - "BPMN relationship '%s' has unexpected type '%s'; skipping.", - rel_id, rel.get("type"), - ) + # --- Pass 3: build flows from `edges` ----------------------------------- + for edge in edges: + edge_id = edge.get("id") + edge_type = edge.get("type") + if edge_type not in _FLOW_CLASS_FOR_EDGE_TYPE: + if isinstance(edge_type, str) and edge_type.startswith("BPMN"): + # A BPMN flow we cannot build: fail rather than drop it. + raise ConversionError(f"Unknown BPMN edge type '{edge_type}' on edge '{edge_id}'.") + logger.warning("BPMN edge '%s' has non-flow type '%s'; skipping.", edge_id, edge_type) continue - source = node_by_id.get((rel.get("source") or {}).get("element")) - target = node_by_id.get((rel.get("target") or {}).get("element")) + source = obj_by_id.get(edge.get("source")) + target = obj_by_id.get(edge.get("target")) if source is None or target is None: logger.warning( "BPMN flow '%s' has a dangling endpoint (source=%s, target=%s); skipping.", - rel_id, - (rel.get("source") or {}).get("element"), - (rel.get("target") or {}).get("element"), + edge_id, edge.get("source"), edge.get("target"), ) continue try: - flow = _build_flow(rel, source, target) + flow = _build_flow(edge, source, target) except ConversionError: raise except (TypeError, ValueError) as exc: - logger.warning( - "BPMN flow '%s' could not be built (%s); skipping.", rel_id, exc, - ) + logger.warning("BPMN flow '%s' could not be built (%s); skipping.", edge_id, exc) continue - flow.layout = _flow_layout_dict(rel_id, rel) - editor_ids.assign(flow, rel_id) + flow.layout = _flow_layout_dict(edge) + editor_ids.assign(flow, edge_id) if isinstance(flow, MessageFlow): if collaboration is not None: collaboration.add_message_flow(flow) else: logger.warning( - "BPMN MessageFlow '%s' present but the diagram has no pools; skipping.", - rel_id, + "BPMN MessageFlow '%s' present but the diagram has no pools; skipping.", edge_id, ) continue - # SequenceFlow / Association / DataAssociation: route via either endpoint. endpoint_container = process_of.get(source) or process_of.get(target) if endpoint_container is None: - logger.warning( - "BPMN flow '%s' has no resolvable container; skipping.", rel_id, - ) + logger.warning("BPMN flow '%s' has no resolvable container; skipping.", edge_id) continue if isinstance(flow, SequenceFlow): - # SequenceFlows go into their endpoints' immediate container (Process or - # SubProcess). The metamodel's E2 rule guarantees both endpoints share one. if isinstance(endpoint_container, (Process, SubProcess)): endpoint_container.add_sequence_flow(flow) elif isinstance(flow, Association): @@ -527,9 +491,4 @@ def _ensure_synthetic_process(): if outer is not None: outer.add_data_association(flow) - return BPMNModel( - name=name, - processes=processes, - collaboration=collaboration, - data_stores=data_stores, - ) + return BPMNModel(name=title, processes=processes, collaboration=collaboration, data_stores=data_stores) diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/class_diagram_processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/class_diagram_processor.py index b763d7e25..b64a6b59b 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/class_diagram_processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/class_diagram_processor.py @@ -1,5 +1,8 @@ """ Class diagram processing for converting JSON to BUML format. + +Reads the v4 wire shape (``{nodes, edges}``) natively. See +``docs/source/migrations/uml-v4-shape.md`` for the spec. """ import hashlib @@ -23,9 +26,33 @@ parse_attribute, parse_method, parse_multiplicity, legacy_body_only_to_text, process_ocl_constraints, ) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + absolute_bounds, node_data, +) +from besser.utilities.web_modeling_editor.backend.constants.constants import VALID_PRIMITIVE_TYPES from besser.BUML.notations.ocl.error_handling import BOCLSyntaxError from besser.utilities.utils import parse_iso_timestamp from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.utils import sanitize_name +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + reject_unreadable_model, +) + +# The React Flow frontend creates ``comment`` nodes tethered by +# ``CommentLink`` edges; ``Comments`` / ``Link`` are the legacy v3-flavoured +# spellings still produced by older fixtures. Accept both on read. +COMMENT_NODE_TYPES = ("comment", "Comments") +COMMENT_LINK_TYPES = ("CommentLink", "Link") + +NODE_STYLE_KEYS = ("fillColor", "strokeColor", "textColor", "highlight") + + +def _node_layout(node: dict, nodes_by_id: dict) -> dict: + """Layout stash of a class or enumeration node: absolute bounds (the + package is not re-emitted) and its colours.""" + layout = absolute_bounds(node, nodes_by_id) + data = node_data(node) + layout.update({key: data[key] for key in NODE_STYLE_KEYS if key in data}) + return layout def parse_method_signature_from_code( @@ -81,11 +108,7 @@ def parse_method_signature_from_code( def _build_type_lookup(domain_model: DomainModel) -> dict[str, Union[Class, Enumeration]]: - """Build a name-to-type lookup dict for O(1) type resolution. - - Only includes Class and Enumeration types (the user-defined types that - can appear as attribute types, parameter types, or return types). - """ + """Build a name-to-type lookup dict for O(1) type resolution.""" return { t.name: t for t in domain_model.types @@ -94,13 +117,7 @@ def _build_type_lookup(domain_model: DomainModel) -> dict[str, Union[Class, Enum def _resolve_type(type_name: str, type_lookup: dict[str, Union[Class, Enumeration]]) -> Type: - """Resolve a type name to a metamodel type object. - - Returns the Class/Enumeration from *type_lookup* if found, otherwise - returns a new ``PrimitiveDataType``. Raises ``ConversionError`` with - a descriptive message if the name is neither a known user type nor a - valid primitive. - """ + """Resolve a type name to a metamodel type object.""" resolved = type_lookup.get(type_name) if resolved is not None: return resolved @@ -114,75 +131,105 @@ def _resolve_type(type_name: str, type_lookup: dict[str, Union[Class, Enumeratio ) +def _rows(data: dict, key: str, owner: str) -> list[dict]: + """``data[key]`` as a list of row objects; ``ConversionError`` for any other shape.""" + rows = data.get(key) + if rows is None: + return [] + if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows): + raise ConversionError(f"'{key}' of '{owner}' must be a list of objects.") + return rows + + +def _class_v4_kind(node: dict) -> str: + """Return the v3-flavoured kind for a v4 ``class`` node. + + v4 collapses Class / AbstractClass / Interface / Enumeration to a single + ``class`` node, with ``data.stereotype`` carrying the discriminator. This + helper returns one of ``Class`` / ``AbstractClass`` / ``Interface`` / + ``Enumeration`` so the rest of the processor reads naturally. + """ + data = node_data(node) + stereotype = (data.get("stereotype") or "").strip().lower() + if stereotype == "abstract": + return "AbstractClass" + if stereotype == "interface": + return "Interface" + if stereotype == "enumeration": + return "Enumeration" + if stereotype == "oclconstraint": + return "ClassOCLConstraint" + return "Class" + + def _process_enumerations( - elements: dict[str, Any], + nodes: list[dict], domain_model: DomainModel, layout_positions: dict[str, Any], comment_elements: dict[str, str], ) -> None: - """Process enumeration elements and collect comments from the element map. - - Iterates over *elements*, creates ``Enumeration`` instances for each - enumeration element, adds them to *domain_model*, and records their - layout bounds in *layout_positions*. Comment elements encountered - during iteration are stored in *comment_elements* for later processing. + """Create ``Enumeration`` instances for every enumeration class node and + record their layout bounds. Also collects ``Comments`` nodes for later + processing. """ - for element_id, element in elements.items(): - # Collect comments - if element.get("type") == "Comments": - comment_text = element.get("name", "").strip() - comment_elements[element_id] = comment_text + nodes_by_id = {node.get("id"): node for node in nodes} + for node in nodes: + node_type = node.get("type") or "" + node_id = node.get("id") + data = node_data(node) + # Comments are top-level ``comment`` nodes in v4 (``Comments`` is + # the legacy spelling); the body text lives on ``data.name``. + if node_type in COMMENT_NODE_TYPES: + comment_text = (data.get("name") or "").strip() + comment_elements[node_id] = comment_text continue - if element.get("type") == "Enumeration": - element_name = element.get("name", "").strip() - if not element_name or any(char.isspace() for char in element_name): - raise ConversionError( - f"Invalid enumeration name: '{element_name}'. Names cannot contain whitespace or be empty." - ) + if node_type != "class": + continue + if _class_v4_kind(node) != "Enumeration": + continue - literals = [] - seen_literal_names = set() - for literal_id in element.get("attributes", []): - literal = elements.get(literal_id) - if literal: - literal_name = literal.get("name", "").strip() - if not literal_name: - raise ConversionError( - f"Empty enumeration literal name in '{element_name}'." - ) - if literal_name in seen_literal_names: - raise ConversionError( - f"Duplicate enumeration literal '{literal_name}' in '{element_name}'." - ) - seen_literal_names.add(literal_name) - literal_obj = EnumerationLiteral( - name=literal_name, timestamp=parse_iso_timestamp(literal.get("timestamp")), - id=literal_id, - ) - literals.append(literal_obj) - # Store the ordered list for later use in buml_to_json conversion, - # but pass as set to Enumeration (which requires set internally). - enum = Enumeration( - name=element_name, literals=set(literals), - timestamp=parse_iso_timestamp(element.get("timestamp")), - id=element_id, + element_name = (data.get("name") or "").strip() + if not element_name or any(char.isspace() for char in element_name): + raise ConversionError( + f"Invalid enumeration name: '{element_name}'. Names cannot contain whitespace or be empty." ) - # Preserve insertion order from the JSON for round-trip fidelity. - enum._ordered_literals = list(literals) - # Use add_type() which triggers validation through the setter - try: - domain_model.add_type(enum) - except ValueError as e: - raise ConversionError(str(e)) - # Capture layout bounds for round-trip fidelity - if "bounds" in element: - layout_positions[type_layout_key(enum)] = element["bounds"] + literals = [] + seen_literal_names = set() + for literal in _rows(data, "attributes", element_name): + literal_name = (literal.get("name") or "").strip() + if not literal_name: + raise ConversionError( + f"Empty enumeration literal name in '{element_name}'." + ) + if literal_name in seen_literal_names: + raise ConversionError( + f"Duplicate enumeration literal '{literal_name}' in '{element_name}'." + ) + seen_literal_names.add(literal_name) + literals.append(EnumerationLiteral( + name=literal_name, timestamp=parse_iso_timestamp(literal.get("timestamp")), + id=literal.get("id"), + )) + + enum = Enumeration( + name=element_name, literals=set(literals), + timestamp=parse_iso_timestamp(data.get("timestamp")), + id=node_id, + ) + # Preserve insertion order from the JSON for round-trip fidelity. + enum._ordered_literals = list(literals) + try: + domain_model.add_type(enum) + except ValueError as e: + raise ConversionError(str(e)) + + layout_positions[type_layout_key(enum)] = _node_layout(node, nodes_by_id) def _process_classes( - elements: dict[str, Any], + nodes: list[dict], domain_model: DomainModel, type_lookup: dict[str, Union[Class, Enumeration]], layout_positions: dict[str, Any], @@ -190,224 +237,246 @@ def _process_classes( ) -> tuple[dict[str, Class], dict[str, Method]]: """Create classes with their attributes and methods. - First creates all class shells (without attributes/methods) so that - cross-references between classes resolve correctly, then populates - each class with its attributes and methods in a second pass. - - Returns: - ``(class_id_to_class, method_id_to_method)`` — JSON element id maps - used by downstream OCL routing (``targetMethodId`` resolution) and - by ``buml_to_json`` for round-trip-stable element ids. + Two-pass: shells first (so cross-references resolve), then attributes + and methods. """ class_id_to_class: dict[str, Class] = {} method_id_to_method: dict[str, Method] = {} - # First create all class structures without attributes or methods - for element_id, element in elements.items(): - if element.get("type") in ["Class", "AbstractClass"]: - class_name = element.get("name", "").strip() - if not class_name or any(char.isspace() for char in class_name): - raise ConversionError( - f"Invalid class name: '{class_name}'. Names cannot contain whitespace or be empty." - ) - - is_abstract = element.get("type") == "AbstractClass" - # Handle metadata with description and URI - metadata = None - description = element.get("description") - uri = element.get("uri") - icon = element.get("icon") + nodes_by_id = {node.get("id"): node for node in nodes} - if description or uri or icon: - metadata = Metadata(description=description, uri=uri, icon=icon) - try: - cls = Class( - name=class_name, is_abstract=is_abstract, metadata=metadata, - timestamp=parse_iso_timestamp(element.get("timestamp")), - id=element_id, - ) - # Use add_type() which triggers validation through the setter - domain_model.add_type(cls) - except ValueError as e: - raise ConversionError(str(e)) + # Pass 1: class shells. + for node in nodes: + if node.get("type") != "class": + continue + kind = _class_v4_kind(node) + if kind not in ("Class", "AbstractClass"): + continue - # Map JSON element id -> Class so OCL pre/post can resolve targetMethodId's owner - # and buml_to_json can re-emit the original element id for round-trip stability. - class_id_to_class[element_id] = cls + node_id = node.get("id") + data = node_data(node) + class_name = (data.get("name") or "").strip() + if not class_name or any(char.isspace() for char in class_name): + raise ConversionError( + f"Invalid class name: '{class_name}'. Names cannot contain whitespace or be empty." + ) - # Capture layout bounds for round-trip fidelity - if "bounds" in element: - layout_positions[type_layout_key(cls)] = element["bounds"] + is_abstract = kind == "AbstractClass" + metadata = None + description = data.get("description") + uri = data.get("uri") + icon = data.get("icon") + if description or uri or icon: + metadata = Metadata(description=description, uri=uri, icon=icon) + try: + cls = Class( + name=class_name, is_abstract=is_abstract, metadata=metadata, + timestamp=parse_iso_timestamp(data.get("timestamp")), + id=node_id, + ) + domain_model.add_type(cls) + except ValueError as e: + raise ConversionError(str(e)) + class_id_to_class[node_id] = cls + layout_positions[type_layout_key(cls)] = _node_layout(node, nodes_by_id) - # Rebuild the type lookup now that all class shells have been added, - # so that cross-class references in attributes/methods resolve correctly. + # Rebuild lookup so class-typed cross-references resolve in pass 2. type_lookup = _build_type_lookup(domain_model) - # Now add attributes and methods to classes - for element_id, element in elements.items(): - if element.get("type") in ["Class", "AbstractClass"]: - class_name = element.get("name", "").strip() - # By id, not by name: several placeholder classes ("...") share a name. - cls = class_id_to_class.get(element_id) - - if not cls: - continue # Skip if class wasn't created successfully in first pass - - # Add attributes - attribute_names = set() - for attr_id in element.get("attributes", []): - attr = elements.get(attr_id) - if attr: - # Check for new format (separate visibility and attributeType properties) - if "visibility" in attr and "attributeType" in attr: - # New format - use separate properties - visibility = attr.get("visibility", "public") - name = attr.get("name", "").strip() - attr_type = attr.get("attributeType", "str") - is_optional = attr.get("isOptional", False) - is_id = attr.get("isId", False) - is_external_id = attr.get("isExternalId", False) - is_derived = attr.get("isDerived", False) - default_value = attr.get("defaultValue", None) - else: - # Legacy format - parse from name string - visibility, name, attr_type = parse_attribute(attr.get("name", ""), domain_model, type_lookup=type_lookup) - is_optional = False - is_id = False - is_external_id = False - is_derived = False - default_value = None - - if not name: # Skip if no name was returned + # Pass 2: attributes and methods. + for node in nodes: + if node.get("type") != "class": + continue + kind = _class_v4_kind(node) + if kind not in ("Class", "AbstractClass"): + continue + + data = node_data(node) + class_name = (data.get("name") or "").strip() + # By id, not by name: several placeholder classes ("...") share a name. + cls = class_id_to_class.get(node.get("id")) + if not cls: + continue + + attribute_names: set[str] = set() + for attr in _rows(data, "attributes", class_name): + # v4 attribute rows always carry visibility + attributeType + # explicitly (see uml-v4-shape.md). Legacy "+ name: type" + # inline parsing is no longer needed at this layer; the + # editor migrator normalises it. + visibility = attr.get("visibility", "public") + name = (attr.get("name") or "").strip() + attr_type = attr.get("attributeType") + if attr_type is None: + # Legacy fallback: parse from name string. Mirrors what the + # editor migrator does for very old fixtures, but emit a + # warning-free path for callers that already produce v4 + # rows without ``attributeType``. + visibility, name, attr_type = parse_attribute( + attr.get("name", ""), domain_model, type_lookup=type_lookup, + ) + is_optional = attr.get("isOptional", False) + is_id = attr.get("isId", False) + is_external_id = attr.get("isExternalId", False) + is_derived = attr.get("isDerived", False) + default_value = attr.get("defaultValue") + + if not name: + continue + if name in attribute_names: + raise ConversionError( + f"Duplicate attribute name '{name}' found in class '{class_name}'" + ) + attribute_names.add(name) + + type_obj = _resolve_type(attr_type, type_lookup) + property_ = Property( + name=name, type=type_obj, visibility=visibility, + is_optional=is_optional, is_id=is_id, + is_external_id=is_external_id, is_derived=is_derived, + default_value=default_value, + timestamp=parse_iso_timestamp(attr.get("timestamp")), + id=attr.get("id"), + ) + cls.add_attribute(property_) + + for method in _rows(data, "methods", class_name): + visibility, name, parameters, return_type = parse_method( + method.get("name", ""), domain_model, type_lookup=type_lookup, + ) + + # v4 method rows carry structured fields written by the React + # Flow inspector (``ClassNodeElement`` in + # packages/library/lib/types/nodes/NodeProps.ts): ``visibility``, + # ``parameters`` ([{id, name, parameterType, defaultValue}]) and + # ``returnType``. Prefer those over name-string parsing; the + # legacy "+ name(p: t): r" signature form stays as the fallback + # for older fixtures and imports. + row_visibility = method.get("visibility") + if isinstance(row_visibility, str) and row_visibility.strip(): + visibility = row_visibility.strip() + + structured_params = method.get("parameters") + if isinstance(structured_params, list) and structured_params: + parameters = [] + for param_row in structured_params: + if not isinstance(param_row, dict): continue - if name in attribute_names: - raise ConversionError(f"Duplicate attribute name '{name}' found in class '{class_name}'") - attribute_names.add(name) - - # Resolve the attribute type via O(1) lookup - type_obj = _resolve_type(attr_type, type_lookup) - property_ = Property(name=name, type=type_obj, visibility=visibility, is_optional=is_optional, is_id=is_id, is_external_id=is_external_id, is_derived=is_derived, default_value=default_value, - timestamp=parse_iso_timestamp(attr.get("timestamp")), id=attr_id) - cls.add_attribute(property_) - - # Add methods - for method_id in element.get("methods", []): - method = elements.get(method_id) - if method: - visibility, name, parameters, return_type = parse_method(method.get("name", ""), domain_model, type_lookup=type_lookup) - - # The editor's newer format carries the return type in its own - # `attributeType` property, the way attributes do above, and - # leaves the name bare ("renew()"). Only the signature was - # read, so every such method arrived with type None and the - # agent never saw what an action returns. - # Older saves can hold a signature fragment there ("int): any"); - # an unresolvable value is ignored, as it was before this read. - if not return_type: - declared = method.get("attributeType") or method.get("returnType") or None - if declared: - try: - _resolve_type(declared, type_lookup) - return_type = declared - except ConversionError: - logger.warning( - "Ignoring unresolvable return type %r on method %r", - declared, name, - ) - - # Get the code attribute for the method - method_code = method.get("code", "") - - method_name_is_malformed = ( - isinstance(name, str) - and name.count("(") != name.count(")") - ) - if method_name_is_malformed or (not parameters and method_code): - parsed_from_code = parse_method_signature_from_code(method_code, domain_model, type_lookup=type_lookup) - if parsed_from_code: - parsed_name, parsed_parameters, parsed_return_type = parsed_from_code - if method_name_is_malformed and parsed_name: - name = parsed_name - if not parameters and parsed_parameters: - parameters = parsed_parameters - if not return_type and parsed_return_type: - return_type = parsed_return_type - - # Get implementation type and diagram references - impl_type_str = method.get("implementationType", "none") - if isinstance(impl_type_str, str): - impl_type_str = impl_type_str.strip().lower() - state_machine_id = method.get("stateMachineId", "") - quantum_circuit_id = method.get("quantumCircuitId", "") - neural_network_id = method.get("neuralNetworkId", "") - - # Map string to MethodImplementationType enum - impl_type_map = { - "none": MethodImplementationType.NONE, - "code": MethodImplementationType.CODE, - "bal": MethodImplementationType.BAL, - "state_machine": MethodImplementationType.STATE_MACHINE, - "quantum_circuit": MethodImplementationType.QUANTUM_CIRCUIT, - "neural_network": MethodImplementationType.NEURAL_NETWORK, - } - implementation_type = impl_type_map.get(impl_type_str, MethodImplementationType.NONE) - - # Auto-detect implementation type if not set but code exists - if implementation_type == MethodImplementationType.NONE and method_code: - implementation_type = MethodImplementationType.CODE - - # Create method parameters - method_params = [] - for param in parameters: - param_type_name = param.get('type', 'any') - param_name = param.get('name') - if not param_name: - logger.warning( - "Skipping parameter with missing name in method '%s' of class '%s'.", - name, class_name, - ) - continue - - # Resolve parameter type via O(1) lookup - param_type_obj = _resolve_type(param_type_name, type_lookup) - - param_obj = Parameter( - name=param_name, - type=param_type_obj + param_name = (param_row.get("name") or "").strip() + raw_type = param_row.get("parameterType") or param_row.get("type") or "any" + if isinstance(raw_type, str): + raw_type = raw_type.strip() + raw_type = VALID_PRIMITIVE_TYPES.get(raw_type.lower(), raw_type) + param_dict: dict = {"name": param_name, "type": raw_type or "any"} + if param_row.get("defaultValue") is not None: + param_dict["default"] = param_row["defaultValue"] + parameters.append(param_dict) + + # ``returnType`` is the canonical structured field (the + # inspector mirrors it onto ``attributeType``). v3->v4 migrated + # rows carry the return type *only* on ``attributeType`` + # (versionConverter's ``parseLegacyNameFormat`` path), so + # consult it as a last resort — but only when neither + # ``returnType`` nor the legacy ``: type`` name suffix yielded one. + structured_return = method.get("returnType") + if not (isinstance(structured_return, str) and structured_return.strip()): + fallback_return = method.get("attributeType") + structured_return = fallback_return if not return_type else None + if isinstance(structured_return, str) and structured_return.strip(): + normalized_return = structured_return.strip() + # ``any`` is the frontend's "no explicit return type" + # default — treat it like the absent legacy ``: type`` + # suffix so generators don't grow spurious annotations. + if normalized_return.lower() != "any": + declared = VALID_PRIMITIVE_TYPES.get(normalized_return.lower(), normalized_return) + # A deleted class or an old signature fragment ("int): any") + # must not fail the whole diagram, as on development. + try: + _resolve_type(declared, type_lookup) + return_type = declared + except ConversionError: + logger.warning( + "Ignoring unresolvable return type %r on method %r", normalized_return, name, ) - if 'default' in param: - param_obj.default_value = param['default'] - method_params.append(param_obj) - - # Create method with parameters, return type, code, and implementation type - method_obj = Method( - name=name, - visibility=visibility, - parameters=method_params, - code=method_code, - implementation_type=implementation_type, - timestamp=parse_iso_timestamp(method.get("timestamp")), - id=method_id, + + method_code = method.get("code", "") + method_name_is_malformed = ( + isinstance(name, str) and name.count("(") != name.count(")") + ) + if method_name_is_malformed or (not parameters and method_code): + parsed_from_code = parse_method_signature_from_code( + method_code, domain_model, type_lookup=type_lookup, + ) + if parsed_from_code: + parsed_name, parsed_parameters, parsed_return_type = parsed_from_code + if method_name_is_malformed and parsed_name: + name = parsed_name + if not parameters and parsed_parameters: + parameters = parsed_parameters + if not return_type and parsed_return_type: + return_type = parsed_return_type + + impl_type_str = method.get("implementationType", "none") + if isinstance(impl_type_str, str): + impl_type_str = impl_type_str.strip().lower() + state_machine_id = method.get("stateMachineId", "") + quantum_circuit_id = method.get("quantumCircuitId", "") + neural_network_id = method.get("neuralNetworkId", "") + + impl_type_map = { + "none": MethodImplementationType.NONE, + "code": MethodImplementationType.CODE, + "bal": MethodImplementationType.BAL, + "state_machine": MethodImplementationType.STATE_MACHINE, + "quantum_circuit": MethodImplementationType.QUANTUM_CIRCUIT, + "neural_network": MethodImplementationType.NEURAL_NETWORK, + } + implementation_type = impl_type_map.get(impl_type_str, MethodImplementationType.NONE) + if implementation_type == MethodImplementationType.NONE and method_code: + implementation_type = MethodImplementationType.CODE + + method_params = [] + for param in parameters: + param_type_name = param.get('type', 'any') + param_name = param.get('name') + if not param_name: + logger.warning( + "Skipping parameter with missing name in method '%s' of class '%s'.", + name, class_name, ) + continue + param_type_obj = _resolve_type(param_type_name, type_lookup) + param_obj = Parameter(name=param_name, type=param_type_obj) + if 'default' in param: + param_obj.default_value = param['default'] + method_params.append(param_obj) + + method_obj = Method( + name=name, + visibility=visibility, + parameters=method_params, + code=method_code, + implementation_type=implementation_type, + timestamp=parse_iso_timestamp(method.get("timestamp")), + id=method.get("id"), + ) - # Store diagram references in a separate mapping for later resolution. - # These will be used by project-level processing to link to actual diagrams. - if state_machine_id or quantum_circuit_id or neural_network_id: - method_diagram_refs[(class_name, name)] = { - "stateMachineId": state_machine_id or "", - "quantumCircuitId": quantum_circuit_id or "", - "neuralNetworkId": neural_network_id or "", - } + # Diagram references are resolved later by project-level + # processing (see ``method_nn_linker`` for neural networks). + if state_machine_id or quantum_circuit_id or neural_network_id: + method_diagram_refs[(class_name, name)] = { + "stateMachineId": state_machine_id or "", + "quantumCircuitId": quantum_circuit_id or "", + "neuralNetworkId": neural_network_id or "", + } - # Handle return type via O(1) lookup - if return_type: - method_obj.type = _resolve_type(return_type, type_lookup) + if return_type: + method_obj.type = _resolve_type(return_type, type_lookup) - cls.add_method(method_obj) + cls.add_method(method_obj) - # Track JSON method element id -> Method, so OCL pre/post - # can resolve their targetMethodId and so buml_to_json can - # round-trip the original element id (stable references). - method_id_to_method[method_id] = method_obj + method_id = method.get("id") + if method_id: + method_id_to_method[method_id] = method_obj return class_id_to_class, method_id_to_method @@ -435,35 +504,38 @@ def _dedupe_end_name(name: str, owner_class, reserved: set[str] = frozenset()) - counter += 1 return f"{name}_{counter}" + def _read_end_navigable( - end: dict[str, Any], legacy_default: bool, side: str, rel_id: str, all_warnings: list[str] + edge_data: dict[str, Any], side: str, legacy_default: bool, rel_id: str, all_warnings: list[str] ) -> bool: - """Return the navigability of a relationship end. - - Uses the explicit ``navigable`` boolean when present. When the key is - missing (payload saved before per-end navigability existed) the legacy - default inferred from the relationship type is used. A present but - non-boolean value (e.g. ``"false"`` or ``null``) is invalid: the legacy - default is used and a warning is recorded. + """Return the navigability of one relationship end. + + v4 carries it as ``edge.data.sourceNavigable`` / ``edge.data.targetNavigable`` + (see ``docs/source/migrations/uml-v4-shape.md``). When the key is missing + (payload saved before per-end navigability existed) the legacy default + inferred from the relationship type is used. A present but non-boolean + value (e.g. ``"false"`` or ``null``) is invalid: the legacy default is used + and a warning is recorded. """ - if "navigable" not in end: + key = f"{side}Navigable" + if key not in edge_data: return legacy_default - value = end["navigable"] + value = edge_data[key] if isinstance(value, bool): return value logger.warning( - "Relationship %s: %s.navigable is not a boolean (%r); using %s.", rel_id, side, value, legacy_default + "Relationship %s: %s is not a boolean (%r); using %s.", rel_id, key, value, legacy_default ) all_warnings.append( - f"Relationship '{rel_id}': {side} 'navigable' must be true or false (got {value!r}); " + f"Relationship '{rel_id}': {key} must be true or false (got {value!r}); " f"defaulted it to {'navigable' if legacy_default else 'non-navigable'}." ) return legacy_default def _process_relationships( - relationships: dict[str, Any], - elements: dict[str, Any], + nodes: list[dict], + edges: list[dict], domain_model: DomainModel, class_id_to_class: dict[str, Class], layout_positions: dict[str, Any], @@ -471,106 +543,78 @@ def _process_relationships( comment_links: dict[str, list[str]], all_warnings: list[str], ) -> tuple[dict[str, set[str]], dict[str, BinaryAssociation]]: - """Process associations, generalizations, and link relationships. - - Returns a tuple of (*association_class_candidates*, *association_by_id*) - for downstream association-class processing. - """ - # Store association classes candidates and their links for third pass processing + """Process associations, generalizations, and link edges.""" association_class_candidates: dict[str, set[str]] = {} association_by_id: dict[str, BinaryAssociation] = {} - for rel_id, relationship in relationships.items(): - rel_type = relationship.get("type") - source = relationship.get("source") - target = relationship.get("target") + # Index nodes by id once for O(1) lookups. + nodes_by_id = {n.get("id"): n for n in nodes if n.get("id")} + edge_ids: set[str] = {e.get("id") for e in edges if e.get("id")} - if not rel_type or not source or not target: + for edge in edges: + rel_type = edge.get("type") + source_id = edge.get("source") + target_id = edge.get("target") + rel_id = edge.get("id") + edge_data = edge.get("data") or {} + + if not rel_type or not source_id or not target_id: logger.warning("Skipping relationship %s due to missing data.", rel_id) all_warnings.append(f"Skipped relationship '{rel_id}': missing type, source, or target.") continue - # Skip OCL links -- these are visual-only relationships that connect a - # ClassOCLConstraint element to the class it constrains. The constraint - # data itself is stored in the ClassOCLConstraint element and processed - # separately below; the context class is derived from the OCL expression. + # OCL link is visual-only; constraint data lives on the class node. if rel_type == "ClassOCLLink": continue - # Handle Link (comment links) - if rel_type == "Link": - source_element_id = source.get("element") - target_element_id = target.get("element") - - # Determine which is the comment and which is the target + if rel_type in COMMENT_LINK_TYPES: comment_id = None - target_id = None - - if source_element_id in comment_elements: - comment_id = source_element_id - target_id = target_element_id - elif target_element_id in comment_elements: - comment_id = target_element_id - target_id = source_element_id - - if comment_id and target_id: - if comment_id not in comment_links: - comment_links[comment_id] = [] - comment_links[comment_id].append(target_id) - + target = None + if source_id in comment_elements: + comment_id = source_id + target = target_id + elif target_id in comment_elements: + comment_id = target_id + target = source_id + if comment_id and target: + comment_links.setdefault(comment_id, []).append(target) continue - # Handle ClassLinkRel (association class links) later if rel_type == "ClassLinkRel": - source_element_id = source.get("element") - target_element_id = target.get("element") - - # Check if source is a class and target is a relationship - if source_element_id in elements and target_element_id in relationships: - # Source is a class, target is an association - if source_element_id not in association_class_candidates: - association_class_candidates[source_element_id] = set() - association_class_candidates[source_element_id].add(target_element_id) - - # Check if target is a class and source is a relationship - elif target_element_id in elements and source_element_id in relationships: - # Target is a class, source is an association - if target_element_id not in association_class_candidates: - association_class_candidates[target_element_id] = set() - association_class_candidates[target_element_id].add(source_element_id) - + # ClassLinkRel connects a class node to an association edge. + if source_id in nodes_by_id and target_id in edge_ids: + association_class_candidates.setdefault(source_id, set()).add(target_id) + elif target_id in nodes_by_id and source_id in edge_ids: + association_class_candidates.setdefault(target_id, set()).add(source_id) continue - # Retrieve source and target elements - source_element = elements.get(source.get("element")) - target_element = elements.get(target.get("element")) - - if not source_element or not target_element: - logger.warning("Skipping relationship %s due to missing elements.", rel_id) - all_warnings.append(f"Skipped relationship '{rel_id}': source or target element not found.") + source_node = nodes_by_id.get(source_id) + target_node = nodes_by_id.get(target_id) + if not source_node or not target_node: + logger.warning("Skipping relationship %s due to missing nodes.", rel_id) + all_warnings.append(f"Skipped relationship '{rel_id}': source or target node not found.") continue # By id, not by name: several placeholder classes ("...") share a name. - source_class = class_id_to_class.get(source.get("element")) - target_class = class_id_to_class.get(target.get("element")) - + source_class = class_id_to_class.get(source_id) + target_class = class_id_to_class.get(target_id) if not source_class or not target_class: logger.warning("Skipping relationship %s: classes not found in domain model.", rel_id) all_warnings.append(f"Skipped relationship '{rel_id}': source or target class not in domain model.") continue - # Handle each type of relationship - if rel_type == "ClassBidirectional" or rel_type == "ClassUnidirectional" or rel_type == "ClassComposition" or rel_type == "ClassAggregation" : + if rel_type in ("ClassBidirectional", "ClassUnidirectional", "ClassComposition", "ClassAggregation"): is_composite = rel_type == "ClassComposition" - # Navigability is an explicit per-end boolean (source.navigable / - # target.navigable); this applies to plain associations, - # compositions and aggregations alike. Payloads saved before the - # field existed only carry the relationship type, so fall back to - # the legacy inference (ClassUnidirectional => source non-navigable). + # Navigability is an explicit per-end boolean + # (``sourceNavigable`` / ``targetNavigable``); this applies to + # plain associations, compositions and aggregations alike. + # Payloads saved before the fields existed only carry the + # relationship type, so fall back to the legacy inference + # (legacy ``ClassUnidirectional`` => source non-navigable). source_navigable = _read_end_navigable( - source, rel_type != "ClassUnidirectional", "source", rel_id, all_warnings + edge_data, "source", rel_type != "ClassUnidirectional", rel_id, all_warnings, ) - target_navigable = _read_end_navigable(target, True, "target", rel_id, all_warnings) + target_navigable = _read_end_navigable(edge_data, "target", True, rel_id, all_warnings) # BinaryAssociation rejects a composition whose part end (source; # the composite end is target) is not navigable. Correct such an @@ -598,20 +642,19 @@ def _process_relationships( ) target_navigable = True - source_multiplicity = parse_multiplicity(source.get("multiplicity", "1")) - target_multiplicity = parse_multiplicity(target.get("multiplicity", "1")) + source_multiplicity = parse_multiplicity(edge_data.get("sourceMultiplicity", "1")) + target_multiplicity = parse_multiplicity(edge_data.get("targetMultiplicity", "1")) # Association-end names must be unique per *owning* class, else the # metamodel raises a hard ValueError. The owner of an end is the class # on the opposite side of the end's own type: the source end (typed by - # source_class) is owned by target_class, and vice versa. The frontend - # -- or an LLM assembling a spec-driven model -- can legitimately hand - # us two associations that give one class an end with the same role - # name (e.g. two Loan->Member links both rolled "member"). Suffix such - # collisions deterministically so generation never crashes. Covers both - # explicit roles and the auto-derived (class-name) fallbacks. - source_role = source.get("role") or source_class.name.lower() - target_role = target.get("role") or target_class.name.lower() + # source_class) is owned by target_class, and vice versa. Two + # associations can legitimately give one class an end with the same + # role name (e.g. two Loan->Member links both rolled "member"), so + # suffix such collisions deterministically. Covers both explicit + # roles and the auto-derived (class-name) fallbacks. + source_role = edge_data.get("sourceRole") or source_class.name.lower() + target_role = edge_data.get("targetRole") or target_class.name.lower() source_role = _dedupe_end_name(source_role, target_class) # For a self-association both ends are owned by the same class, so the @@ -624,7 +667,7 @@ def _process_relationships( type=source_class, multiplicity=source_multiplicity, is_navigable=source_navigable, - timestamp=parse_iso_timestamp(source.get("timestamp")), + timestamp=parse_iso_timestamp(edge_data.get("sourceTimestamp")), ) target_property = Property( @@ -633,12 +676,10 @@ def _process_relationships( multiplicity=target_multiplicity, is_navigable=target_navigable, is_composite=is_composite, - timestamp=parse_iso_timestamp(target.get("timestamp")), + timestamp=parse_iso_timestamp(edge_data.get("targetTimestamp")), ) - association_name = relationship.get("name") or f"{source_class.name}_{target_class.name}" - - # Check if association name already exists and add increment if needed + association_name = edge_data.get("name") or f"{source_class.name}_{target_class.name}" existing_assoc_names = {assoc.name for assoc in domain_model.associations} if association_name in existing_assoc_names: counter = 1 @@ -649,53 +690,45 @@ def _process_relationships( association = BinaryAssociation( name=association_name, ends={source_property, target_property}, - timestamp=parse_iso_timestamp(relationship.get("timestamp")), + timestamp=parse_iso_timestamp(edge_data.get("timestamp")), id=rel_id, ) domain_model.associations.add(association) - - # Store the association for association class processing association_by_id[rel_id] = association - # Capture layout bounds for the relationship and its endpoints. # "source_role" records the drawn orientation so BUML -> JSON puts - # each end (and its saved endpoint layout) back on the same side. + # each end (and its saved handles / points) back on the same side. rel_layout: dict[str, Any] = {"source_role": source_role} - if "bounds" in relationship: - rel_layout["bounds"] = relationship["bounds"] - if "path" in relationship: - rel_layout["path"] = relationship["path"] - if "isManuallyLayouted" in relationship: - rel_layout["isManuallyLayouted"] = relationship["isManuallyLayouted"] - # Capture source/target endpoint bounds and directions - if source.get("bounds"): - rel_layout["source_bounds"] = source["bounds"] - if source.get("direction"): - rel_layout["source_direction"] = source["direction"] - if target.get("bounds"): - rel_layout["target_bounds"] = target["bounds"] - if target.get("direction"): - rel_layout["target_direction"] = target["direction"] + if edge_data.get("points"): + rel_layout["path"] = edge_data["points"] + if edge_data.get("isManuallyLayouted") is not None: + rel_layout["isManuallyLayouted"] = edge_data["isManuallyLayouted"] + if edge.get("sourceHandle"): + rel_layout["source_direction"] = edge["sourceHandle"] + if edge.get("targetHandle"): + rel_layout["target_direction"] = edge["targetHandle"] layout_positions[f"rel_{association_name}"] = rel_layout elif rel_type == "ClassInheritance": + # The metamodel crashes on a cycle instead of rejecting it. + if target_class in source_class.all_specializations(): + raise ConversionError( + f"Inheritance cycle: '{source_class.name}' cannot inherit from " + f"'{target_class.name}', which already inherits from it." + ) generalization = Generalization( general=target_class, specific=source_class, - timestamp=parse_iso_timestamp(relationship.get("timestamp")), + timestamp=parse_iso_timestamp(edge_data.get("timestamp")), id=rel_id, ) domain_model.generalizations.add(generalization) - - # Capture layout bounds for the generalization gen_layout: dict[str, Any] = {} - if "bounds" in relationship: - gen_layout["bounds"] = relationship["bounds"] - if "path" in relationship: - gen_layout["path"] = relationship["path"] - if source.get("bounds"): - gen_layout["source_bounds"] = source["bounds"] - if target.get("bounds"): - gen_layout["target_bounds"] = target["bounds"] + if edge_data.get("points"): + gen_layout["path"] = edge_data["points"] + if edge.get("sourceHandle"): + gen_layout["source_direction"] = edge["sourceHandle"] + if edge.get("targetHandle"): + gen_layout["target_direction"] = edge["targetHandle"] if gen_layout: layout_positions[generalization_layout_key(source_class, target_class)] = gen_layout @@ -705,55 +738,37 @@ def _process_relationships( def _process_association_classes( association_class_candidates: dict[str, set[str]], association_by_id: dict[str, BinaryAssociation], - elements: dict[str, Any], + nodes: list[dict], domain_model: DomainModel, class_id_to_class: dict[str, Class], all_warnings: list[str], ) -> None: - """Promote regular classes to association classes where linked. - - For each class that was linked to an association via a ``ClassLinkRel``, - create an ``AssociationClass`` that wraps the original class's attributes - and methods together with the association, then replace the plain class - in *domain_model*. - """ + """Promote regular classes to association classes where linked.""" + nodes_by_id = {n.get("id"): n for n in nodes if n.get("id")} for class_id, association_ids in association_class_candidates.items(): - class_element = elements.get(class_id) - if not class_element: + node = nodes_by_id.get(class_id) + if not node: continue - - class_name = class_element.get("name", "") + class_name = node_data(node).get("name", "") class_obj = class_id_to_class.get(class_id) - if not class_obj: continue - # An association class should only be linked to one association if len(association_ids) > 1: msg = f"Class '{class_name}' is linked to multiple associations. Only using the first one." logger.warning(msg) all_warnings.append(msg) - # Get the first association association_id = next(iter(association_ids)) association = association_by_id.get(association_id) - if not association: continue - # Get attributes and methods from the original class. - # Copy the sets — the Class.attributes setter re-parents each member by - # discarding it from its previous owner's attribute set. If we passed - # ``class_obj.attributes`` directly that owner *is* class_obj, so the - # discard would mutate the same set being iterated and raise - # "set changed size during iteration". attributes = set(class_obj.attributes) methods = set(class_obj.methods) - # Create the association class with attributes and methods # The promoted class is the same diagram element, so it keeps an - # explicit timestamp read from the JSON. A defaulted one is not copied: - # passing it would make it explicit and serializers would emit it. + # explicit timestamp; a defaulted one is not copied (it would become explicit). association_class = AssociationClass( name=class_name, attributes=attributes, @@ -761,20 +776,16 @@ def _process_association_classes( timestamp=class_obj.timestamp if class_obj.has_explicit_timestamp else None, id=class_obj.id, ) - - # Add methods to the association class if they exist if methods: association_class.methods = methods - # Update the domain model - remove the regular class and add the association class domain_model.types.discard(class_obj) domain_model.types.add(association_class) # Re-point everything that still holds the DISCARDED class. Class # compares by identity, so an end left bound to the old object makes # validate() report "referencing type 'X' which is not in the domain - # model" for a class plainly on the canvas, and the editor's auto-fix - # cannot clear it because there is nothing wrong with the diagram. + # model" for a class plainly on the canvas. for assoc in domain_model.associations: for end in assoc.ends: if end.type is class_obj: @@ -794,28 +805,24 @@ def _process_association_classes( def _ocl_box_to_full_text( - element: dict[str, Any], - element_id: str, - elements: dict[str, Any], - relationships: dict[str, Any], - class_id_to_class: dict[str, Class], + ocl_row: dict[str, Any], + owner_class: Optional[Class], method_id_to_method: dict[str, Method], warnings: list[str], on_rejection: Optional[Callable[[str, str], None]] = None, ) -> Optional[str]: - """Coerce a ``ClassOCLConstraint`` element to its canonical full-text form. + """Coerce an OCL constraint row to its canonical full-text form. - The canonical wire shape is the full ``context X (inv|pre|post) ...: - body`` text in ``element['constraint']``. WME projects produced by an - earlier intermediate iteration instead carried a body-only string with - sibling ``kind`` / ``targetMethodId`` / ``constraintName`` fields; for - those, the helper synthesises the canonical text from the metadata so - the rest of the pipeline only has to deal with one shape. + Per the v4 spec, OCL constraints collapse onto the owner class's + ``data.oclConstraints`` array; each row carries an ``expression`` + field with the canonical full text. Legacy body-only fields are + accepted for backward compatibility with hand-authored fixtures. - Returns ``None`` (with a warning appended) when the legacy shape can't - be reconstructed — e.g. unlinked, unknown kind, missing target method. + Rejections are appended to ``warnings`` and, when ``on_rejection`` is + given, also reported as ``(code, reason)`` so the caller can record a + structured conversion issue. """ - raw = element.get("constraint") + raw = ocl_row.get("expression") or ocl_row.get("constraint") if not raw: return None @@ -824,64 +831,44 @@ def reject(code: str, reason: str) -> None: if on_rejection is not None: on_rejection(code, reason) - # Already canonical full text — fast path. if raw.lstrip().lower().startswith("context"): return raw - # Legacy body-only path. Detect by the presence of `kind` (the field - # that earlier iterations stamped onto every box). - legacy_kind = element.get("kind") + legacy_kind = ocl_row.get("kind") if not legacy_kind: - # No header and no legacy metadata: nothing we can do. - reject("unsupported_shape", - f"Warning: OCL constraint {element_id} has no recognisable header " + reject( + "unsupported_shape", + f"Warning: OCL constraint {ocl_row.get('id')!r} has no recognisable header " f"and no legacy 'kind' field; skipping." ) return None if legacy_kind not in ("invariant", "precondition", "postcondition"): - reject("unsupported_shape", - f"Warning: OCL constraint {element_id} has unknown kind {legacy_kind!r}; skipping." - ) - return None - - # Resolve the linked class via the ClassOCLLink relationship. - linked_class_id: Optional[str] = None - for rel in relationships.values(): - if rel.get("type") != "ClassOCLLink": - continue - source_id = (rel.get("source") or {}).get("element") - target_id = (rel.get("target") or {}).get("element") - if source_id == element_id: - linked_class_id = target_id - break - if target_id == element_id: - linked_class_id = source_id - break - if linked_class_id is None: - reject("detached", - f"Warning: legacy body-only OCL constraint {element_id} is not linked to a class; skipping." + reject( + "unsupported_shape", + f"Warning: OCL constraint {ocl_row.get('id')!r} has unknown kind {legacy_kind!r}; skipping." ) return None - linked_class = class_id_to_class.get(linked_class_id) - if linked_class is None: - reject("detached", - f"Warning: legacy body-only OCL constraint {element_id} links to non-class element " - f"{linked_class_id}; skipping." + if owner_class is None: + reject( + "detached", + f"Warning: legacy body-only OCL constraint {ocl_row.get('id')!r} has no owner class; skipping." ) return None method = None if legacy_kind in ("precondition", "postcondition"): - target_method_id = element.get("targetMethodId") + target_method_id = ocl_row.get("targetMethodId") if not target_method_id: - reject("unknown_method", - f"Warning: legacy {legacy_kind} constraint {element_id} has no targetMethodId; skipping." + reject( + "unknown_method", + f"Warning: legacy {legacy_kind} constraint {ocl_row.get('id')!r} has no targetMethodId; skipping." ) return None method = method_id_to_method.get(target_method_id) if method is None: - reject("unknown_method", - f"Warning: legacy {legacy_kind} constraint {element_id} targets missing method " + reject( + "unknown_method", + f"Warning: legacy {legacy_kind} constraint {ocl_row.get('id')!r} targets missing method " f"{target_method_id}; skipping." ) return None @@ -890,18 +877,18 @@ def reject(code: str, reason: str) -> None: return legacy_body_only_to_text( body=raw, kind=legacy_kind, - name=element.get("constraintName"), - context_class=linked_class, + name=ocl_row.get("constraintName") or ocl_row.get("name"), + context_class=owner_class, method=method, ) except ValueError as e: - reject("unsupported_shape", f"Warning: legacy {legacy_kind} constraint {element_id}: {e}") + reject("unsupported_shape", f"Warning: legacy {legacy_kind} constraint {ocl_row.get('id')!r}: {e}") return None def _process_constraints( - elements: dict[str, Any], - relationships: dict[str, Any], + nodes: list[dict], + edges: list[dict], domain_model: DomainModel, all_warnings: list[str], class_id_to_class: dict[str, Class], @@ -910,41 +897,32 @@ def _process_constraints( diagram_id: Optional[str] = None, diagram_title: str = "", ) -> None: - """Parse every ``ClassOCLConstraint`` element and attach the results. - - The textarea holds canonical full OCL text — one or more blocks of - ``context inv [name]: body`` or - ``context ::() pre|post: body``. The parser - routes each block by inspecting the kind keyword and (for pre/post) - the method name extracted from the header. - - Legacy body-only JSON files produced by an intermediate iteration are - transparently lifted to full text via :func:`_ocl_box_to_full_text`. - - Malformed OCL, unresolved methods, and duplicate names are skipped - with a warning rather than aborting conversion. Their original text is - retained as a structured conversion issue, never inserted into executable - constraints or silently treated as an implemented rule. - """ + """Walk every class node's ``data.oclConstraints`` and any free-standing + ``ClassOCLConstraint`` nodes. + + Free-standing nodes are the shape the frontend's palette and templates + produce: a ``ClassOCLConstraint`` node carrying ``data.expression`` + (full ``context ...`` text), tethered to its class via a + ``ClassOCLLink`` edge. The link resolves the owner class for legacy + body-only rows; full-text rows derive the context from the OCL text + itself. + + Malformed OCL, unresolved methods, and duplicate names are skipped with a + warning rather than aborting conversion. Their original text is retained + as a structured conversion issue on ``domain_model.conversion_issues``, + never inserted into executable constraints or silently treated as an + implemented rule.""" conversion_issues: list[dict[str, Any]] = [] domain_model.conversion_issues = conversion_issues - def provenance(element_id: str, element: dict, details: Optional[dict] = None) -> dict: + def provenance(row: dict, owner_class: Optional[Class], details: Optional[dict] = None) -> dict: details = details or {} - original_text = element.get("constraint") or "" + element_id = row.get("id") + original_text = row.get("expression") or row.get("constraint") or "" context = details.get("context") - if context is None: - for rel in relationships.values(): - if rel.get("type") != "ClassOCLLink": - continue - ends = [(rel.get(end) or {}).get("element") for end in ("source", "target")] - if element_id not in ends: - continue - linked = next((class_id_to_class[e] for e in ends if e in class_id_to_class), None) - if linked is not None: - context = linked.name - break - target_method = method_id_to_method.get(element.get("targetMethodId")) + if context is None and owner_class is not None: + context = owner_class.name + target_method = method_id_to_method.get(row.get("targetMethodId")) source = { "diagram_id": diagram_id, "diagram_title": diagram_title or domain_model.name, @@ -959,25 +937,17 @@ def provenance(element_id: str, element: dict, details: Optional[dict] = None) - "source": source, "context": context, "method": details.get("method") or (target_method.name if target_method else None), - "name": details.get("name") or element.get("constraintName"), - "kind": details.get("kind") or element.get("kind"), + "name": details.get("name") or row.get("constraintName") or row.get("name"), + "kind": details.get("kind") or row.get("kind"), "expression": expression, "original_text": original_text, } - # Build ``(class_name, method_name) -> Method`` index for pre/post - # routing. Walks the inheritance chain so a constraint written as - # ``context Sub::base_method() pre: ...`` can still resolve to a - # method declared on a parent class. Direct (own) methods always win - # over inherited ones; the metamodel today guarantees method names - # are unique within a class, but a subclass that overrides a parent - # method also wins via the own-first traversal. + method_by_qualified_name: dict[tuple[str, str], Method] = {} duplicates: set[tuple[str, str]] = set() def _walk_inherited_methods(start: Class): - """Yield the start class's own methods first, then ancestors'.""" seen: set[Class] = set() - # BFS: own → direct parents → grandparents … frontier: list[Class] = [start] while frontier: next_frontier: list[Class] = [] @@ -996,7 +966,6 @@ def _walk_inherited_methods(start: Class): for m in _walk_inherited_methods(cls): key = (cls.name, m.name) if key in method_by_qualified_name: - # Already indexed via own-method or a closer ancestor. if method_by_qualified_name[key] is not m: duplicates.add(key) continue @@ -1008,32 +977,66 @@ def _walk_inherited_methods(start: Class): f"ambiguous. Closest definition wins." ) - # Use a list (not a set) so the iteration order at de-dup time matches - # the order constraints were encountered in ``elements.items()``. With - # a set, "first wins" would silently become "any-wins" on Python - # versions whose set ordering differs from the insertion order. extra_invariants: list[tuple[Any, dict]] = [] counter = 0 - for element_id, element in elements.items(): - if element.get("type") != "ClassOCLConstraint": + + # ClassOCLLink edges tether a free-standing constraint node to the + # class it constrains. Map constraint-node-id -> linked class node id + # so legacy body-only constraint nodes can resolve their owner. + ocl_link_targets: dict[str, str] = {} + for edge in edges: + if edge.get("type") != "ClassOCLLink": + continue + source_id = edge.get("source") + target_id = edge.get("target") + if source_id in class_id_to_class and target_id not in class_id_to_class: + ocl_link_targets.setdefault(target_id, source_id) + elif target_id in class_id_to_class: + ocl_link_targets.setdefault(source_id, target_id) + + # Collected OCL rows: (row_dict, owner_class_or_None). + ocl_rows: list[tuple[dict, Optional[Class]]] = [] + for node in nodes: + node_type = node.get("type") + data = node_data(node) + node_id = node.get("id") + if node_type == "ClassOCLConstraint": + # Free-standing constraint node (palette / template shape). + # Owner class comes from the ClassOCLLink edge when present. + row = dict(data) + row.setdefault("id", node_id) + linked_class_id = ocl_link_targets.get(node_id) + owner_class = class_id_to_class.get(linked_class_id) if linked_class_id else None + ocl_rows.append((row, owner_class)) continue + if node_type != "class": + continue + kind = _class_v4_kind(node) + owner_class = class_id_to_class.get(node_id) + if kind == "ClassOCLConstraint": + # Legacy fallback: a class-typed node with stereotype + # ``oclConstraint`` (older converter output). + row = dict(data) + row.setdefault("id", node_id) + linked_class_id = ocl_link_targets.get(node_id) + if owner_class is None and linked_class_id: + owner_class = class_id_to_class.get(linked_class_id) + ocl_rows.append((row, owner_class)) + continue + # Class / Abstract / Interface / Enumeration: walk their oclConstraints. + for row in data.get("oclConstraints") or []: + ocl_rows.append((row, owner_class)) + for row, owner_class in ocl_rows: text = _ocl_box_to_full_text( - element, element_id, elements, relationships, - class_id_to_class, method_id_to_method, all_warnings, - on_rejection=lambda code, reason: conversion_issues.append({ - **provenance(element_id, element), "code": code, "reason": reason, + row, owner_class, method_id_to_method, all_warnings, + on_rejection=lambda code, reason, row=row, owner_class=owner_class: conversion_issues.append({ + **provenance(row, owner_class), "code": code, "reason": reason, }), ) if not text: continue - - # Optional natural-language explanation, surfaced by the validator - # when a constraint is violated. ``description`` on the JSON element - # acts as the default for every constraint extracted from this box; - # an inline ``--`` comment inside a specific block always wins. - description = element.get("description") - + description = row.get("description") counter += 1 parser_issues: list[dict] = [] source_blocks: dict[int, dict] = {} @@ -1043,33 +1046,27 @@ def _walk_inherited_methods(start: Class): issues=parser_issues, source_blocks=source_blocks, ) except (BOCLSyntaxError, ValueError) as e: - # ``process_ocl_constraints`` already swallows most parse errors - # into the warnings list; this catch handles the residual - # narrow set (header-resolve errors, malformed BOCL the - # inner parser re-raised). Programmer errors (KeyError, - # AttributeError, etc.) deliberately propagate. - reason = f"Warning: Error processing OCL element {element_id}: {e}" + reason = f"Warning: Error processing OCL element {row.get('id')!r}: {e}" all_warnings.append(reason) - conversion_issues.append({**provenance(element_id, element), "code": "parse_error", "reason": reason}) + conversion_issues.append({**provenance(row, owner_class), "code": "parse_error", "reason": reason}) continue all_warnings.extend(warnings) # A box holding a single constraint is that constraint, so it carries - # the box's id and timestamp. Boxes with several blocks are split into - # separate constraints, which keep their own creation times and no id. - box_timestamp = parse_iso_timestamp(element.get("timestamp")) + # the box's id and timestamp; split boxes keep their own creation times and no id. + box_timestamp = parse_iso_timestamp(row.get("timestamp")) if len(routing) == 1: - routing[0][1].id = element_id + routing[0][1].id = row.get("id") if box_timestamp is not None: routing[0][1].timestamp = box_timestamp for issue in parser_issues: conversion_issues.append({ - **provenance(element_id, element, issue), + **provenance(row, owner_class, issue), "code": issue["code"], "reason": issue["reason"], **({"missing_element": issue["missing_element"]} if issue.get("missing_element") else {}), }) for kind, constraint, class_name, method_name in routing: - origin = provenance(element_id, element, source_blocks.get(id(constraint))) + origin = provenance(row, owner_class, source_blocks.get(id(constraint))) try: if kind == "invariant": extra_invariants.append((constraint, origin)) @@ -1085,20 +1082,13 @@ def _walk_inherited_methods(start: Class): continue if kind == "precondition": method.add_pre(constraint) - else: # postcondition + else: method.add_post(constraint) except ValueError as e: reason = f"Warning: Could not attach {kind} '{constraint.name}': {e}" all_warnings.append(reason) conversion_issues.append({**origin, "code": "attachment_error", "reason": reason}) - # Combine with any existing constraints already on the domain model. - # ``DomainModel.constraints`` rejects duplicate names with a ``ValueError``, - # so de-dup by ``constraint.name`` first. Two OCL boxes that happen to - # parse to the same canonical name (whether typed by the user or - # auto-generated by ``process_ocl_constraints``) keep the first - # occurrence and emit a warning for each subsequent collision rather - # than crashing the whole conversion. by_name: dict[str, Any] = {c.name: c for c in domain_model.constraints} for c, origin in extra_invariants: if c.name in by_name and by_name[c.name] is not c: @@ -1115,116 +1105,93 @@ def _walk_inherited_methods(start: Class): def process_class_diagram(json_data: dict[str, Any]) -> DomainModel: - """Process Class Diagram specific elements.""" + """Process a Class Diagram in the v4 wire shape. + + Accepts only the v4 ``{nodes, edges}`` shape. v3-shape input is not + supported on the backend; the editor migrator at + ``packages/library/lib/utils/versionConverter.ts`` is the only place + that lifts v3 to v4 in the system. See + ``docs/source/migrations/uml-v4-shape.md``. + """ + reject_unreadable_model(json_data, "ClassDiagram") title = sanitize_name(json_data.get('title', '')) - domain_model = DomainModel( - title, timestamp=parse_iso_timestamp((json_data.get('model') or {}).get('timestamp')) - ) - # Get elements and OCL constraints from the JSON data - elements = (json_data.get('model') or {}).get('elements', {}) - relationships = (json_data.get('model') or {}).get('relationships', {}) + model_payload = json_data.get('model') or {} + domain_model = DomainModel(title, timestamp=parse_iso_timestamp(model_payload.get('timestamp'))) + nodes = model_payload.get('nodes') or [] + edges = model_payload.get('edges') or [] + if not isinstance(nodes, list): + nodes = [] + if not isinstance(edges, list): + edges = [] - # Collect layout positions from the original JSON for round-trip fidelity. - # Keyed by element name (for classes/enums) or composite key (for relationships). layout_positions: dict[str, Any] = {} - - # Store comments for later processing - comment_elements: dict[str, str] = {} # {comment_id: comment_text} - comment_links: dict[str, list[str]] = {} # {comment_id: [linked_element_ids]} - all_warnings: list[str] = [] # Collect non-fatal warnings for the caller - # Track diagram references for methods (state machine / quantum circuit IDs). - # Keyed by (class_name, method_name) to avoid collisions across classes. + comment_elements: dict[str, str] = {} + comment_links: dict[str, list[str]] = {} + all_warnings: list[str] = [] method_diagram_refs: dict[tuple[str, str], dict[str, str]] = {} - # FIRST PASS: Process all type declarations (enumerations and classes) - _process_enumerations(elements, domain_model, layout_positions, comment_elements) + _process_enumerations(nodes, domain_model, layout_positions, comment_elements) - # Build a name->type lookup dict for O(1) type resolution in the second pass. - # Must happen after enumerations are registered but before classes need - # cross-referencing (the lookup is rebuilt after class shells are added). type_lookup = _build_type_lookup(domain_model) class_id_to_class, method_id_to_method = _process_classes( - elements, domain_model, type_lookup, layout_positions, method_diagram_refs, + nodes, domain_model, type_lookup, layout_positions, method_diagram_refs, ) - # Rebuild lookup after classes have been added so that subsequent helpers - # (e.g., comment processing) can resolve class names. type_lookup = _build_type_lookup(domain_model) - # Process relationships (Associations, Generalizations, and Compositions) association_class_candidates, association_by_id = _process_relationships( - relationships, elements, domain_model, class_id_to_class, layout_positions, + nodes, edges, domain_model, class_id_to_class, layout_positions, comment_elements, comment_links, all_warnings, ) - # THIRD PASS: Process association classes _process_association_classes( association_class_candidates, association_by_id, - elements, domain_model, class_id_to_class, all_warnings, + nodes, domain_model, class_id_to_class, all_warnings, ) - # Stale-role-name detection is DISABLED: the heuristic cannot tell a role - # left behind by an editor rename from a legitimate collection role - # (``tasks`` on ``TodoItem`` vs ``members`` on ``User``), so it flooded - # false positives. The real fix is propagating renames into the - # relationship JSON's ``role`` fields at the editor layer. - - # Process OCL constraints (must run AFTER methods are attached so that - # parse_ocl can resolve method-return-types and property navigation). _process_constraints( - elements, relationships, domain_model, all_warnings, + nodes, edges, domain_model, all_warnings, class_id_to_class, method_id_to_method, diagram_id=json_data.get("id"), diagram_title=json_data.get("title", ""), ) - # Process comments and apply them to class or domain model metadata + # Apply collected comments. + nodes_by_id = {n.get("id"): n for n in nodes if n.get("id")} for comment_id, comment_text in comment_elements.items(): if comment_id in comment_links: - # Comment is linked to specific elements - for linked_element_id in comment_links[comment_id]: - linked_element = elements.get(linked_element_id) - if linked_element: - element_name = linked_element.get("name", "").strip() - # Find the class in the domain model via O(1) lookup - type_obj = type_lookup.get(element_name) - if isinstance(type_obj, Class): - # Add comment to class metadata - if not type_obj.metadata: - type_obj.metadata = Metadata(description=comment_text) + for linked_node_id in comment_links[comment_id]: + linked_node = nodes_by_id.get(linked_node_id) + if not linked_node: + continue + element_name = node_data(linked_node).get("name", "").strip() + type_obj = type_lookup.get(element_name) + if isinstance(type_obj, Class): + if not type_obj.metadata: + type_obj.metadata = Metadata(description=comment_text) + else: + if type_obj.metadata.description: + type_obj.metadata.description += f"\n{comment_text}" else: - # Append to existing description - if type_obj.metadata.description: - type_obj.metadata.description += f"\n{comment_text}" - else: - type_obj.metadata.description = comment_text + type_obj.metadata.description = comment_text else: - # Comment is not linked, add to domain model metadata if not domain_model.metadata: domain_model.metadata = Metadata(description=comment_text) else: - # Append to existing description if domain_model.metadata.description: domain_model.metadata.description += f"\n{comment_text}" else: domain_model.metadata.description = comment_text - # Store the association_by_id mapping for object diagram processing domain_model.association_by_id = association_by_id - - # Store method diagram references for buml_to_json round-trip fidelity. - # Keyed by (class_name, method_name) -> {"stateMachineId": ..., "quantumCircuitId": ..., "neuralNetworkId": ...} + # Keyed by (class_name, method_name) -> + # {"stateMachineId": ..., "quantumCircuitId": ..., "neuralNetworkId": ...} domain_model.method_diagram_refs = method_diagram_refs - # Stash the WME element-id -> Class side-map so project-level cross-diagram - # resolution can match Component.realizes against stable WME ids. Structural - # Class has no `layout`, so this side-channel replaces the Component.layout["id"] - # trick the manifests/realizes resolution uses. + # WME node-id -> Class side-map so project-level cross-diagram resolution can + # match Component.realizes against stable WME ids (structural Class has no `layout`). domain_model._wme_class_index = dict(class_id_to_class) - - # Store layout positions for buml_to_json round-trip fidelity. - # Keyed by element name (classes/enums) or composite key (relationships). domain_model._layout_positions = layout_positions return domain_model diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/component_diagram_processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/component_diagram_processor.py index b0be0c68f..f65688155 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/component_diagram_processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/component_diagram_processor.py @@ -1,8 +1,9 @@ -"""Component diagram processing: WME JSON -> ComponentModel. +"""Component diagram processing: v4 WME JSON (``{nodes, edges}``) -> ComponentModel. -Three-pass walk (nodes, containment, relationships) with a layout side +Three-pass walk (nodes, containment via ``parentId``, edges) with a layout side channel, agentic-profile token resolution, and ``AgenticEdge`` dispatch on the -``ComponentDependency`` wire type. +``ComponentDependency`` edge type. Wire shape: ``docs/source/migrations/uml-v4-shape.md`` +(ComponentDiagram). Element or relationship data the metamodel rejects raises ``ConversionError``; unknown element types and dangling ordinary UML relationships are logged and @@ -34,12 +35,20 @@ Tool, ) from besser.BUML.metamodel.uml_component._stereotypes import tokenise_component_stereotype +from besser.utilities.web_modeling_editor.backend.constants.constants import ( + COMPONENT_REQUIRED_INTERFACE_EDGE_TYPES, +) from besser.utilities.web_modeling_editor.backend.services.converters.component_legacy import ( LEGACY_EDGE_KINDS, drop_legacy_reverse_collaborations, legacy_edge_successor, ) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import EditorIds +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + edge_layout, + node_data, + node_layout, +) from besser.utilities.web_modeling_editor.backend.services.converters.stereotype_tokens import ( _PERMISSION_SUFFIX, agentic_edge_extra_tokens, @@ -51,6 +60,9 @@ from besser.utilities.web_modeling_editor.backend.services.exceptions import ( ConversionError, ) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + reject_unreadable_model, +) logger = logging.getLogger(__name__) @@ -66,18 +78,20 @@ def process_component_diagram(json_data: dict) -> ComponentModel: - """Convert a WME Component diagram (JSON) into a ``ComponentModel``. + """Convert a v4 WME Component diagram into a ``ComponentModel``. Args: - json_data: ``{"title": , "model": {...}}`` envelope. + json_data: ``{"title": , "model": {"nodes": [...], "edges": [...]}}``. Returns: - ComponentModel: assembled metamodel instance. + ComponentModel: an ``AgenticComponentModel`` when the diagram carries any + agentic element, a plain ``ComponentModel`` otherwise. Raises: - ConversionError: structural failures (missing ``model``, unrecoverable - element shape). + ConversionError: structural failures (missing ``model``, an element or + edge the metamodel rejects, a containment cycle). """ + reject_unreadable_model(json_data, "ComponentDiagram") if not isinstance(json_data, dict): raise ConversionError( f"Component diagram payload must be a dict, " @@ -86,78 +100,66 @@ def process_component_diagram(json_data: dict) -> ComponentModel: model_data = json_data.get("model") if not isinstance(model_data, dict): raise ConversionError("Component diagram JSON is missing the 'model' key.") - elements = model_data.get("elements") or {} - relationships = model_data.get("relationships") or {} + nodes = [n for n in (model_data.get("nodes") or []) if isinstance(n, dict)] + edges = [e for e in (model_data.get("edges") or []) if isinstance(e, dict)] name = json_data.get("title") or "Generated_Component_Model" editor_ids = EditorIds() - nodes_by_id: dict = _build_nodes(elements, editor_ids) - _reconstruct_containment(elements, nodes_by_id) - relationships_set = set(_build_relationships(relationships, nodes_by_id, editor_ids)) + objects_by_id = _build_nodes(nodes, editor_ids) + _reconstruct_containment(nodes, objects_by_id) + relationships_set = set(_build_relationships(edges, objects_by_id, editor_ids)) - components = {obj for obj in nodes_by_id.values() if isinstance(obj, Component)} - interfaces = {obj for obj in nodes_by_id.values() if isinstance(obj, Interface)} + components = {obj for obj in objects_by_id.values() if isinstance(obj, Component)} + interfaces = {obj for obj in objects_by_id.values() if isinstance(obj, Interface)} + # Skill / Tool count as agentic-notation vocabulary. is_agentic = any(isinstance(c, (AgenticComponent, Skill, Tool)) for c in components) model_type = AgenticComponentModel if is_agentic else ComponentModel return model_type(name=name, components=components, interfaces=interfaces, relationships=relationships_set) -def _build_nodes(elements: dict, editor_ids: EditorIds) -> dict: - """Pass 1 — create every element object, indexed by WME id.""" - nodes_by_id: dict = {} - for elem_id, elem in elements.items(): - if not isinstance(elem, dict): - raise ConversionError( - f"Component element '{elem_id}' must be an object, " - f"got {type(elem).__name__}." - ) +def _build_nodes(nodes: list, editor_ids: EditorIds) -> dict: + """Pass 1 — create every element object, indexed by node id.""" + nodes_by_id = {n.get("id"): n for n in nodes if n.get("id")} + objects_by_id: dict = {} + for node in nodes: + node_id = node.get("id") try: - obj = _build_component_node(elem_id, elem) + obj = _build_component_node(node_id, node.get("type"), node_data(node)) except (TypeError, ValueError) as exc: raise ConversionError( - f"Could not build Component element '{elem_id}': {exc}" + f"Could not build Component element '{node_id}': {exc}" ) from exc if obj is None: continue - # Stash the layout side channel (opaque to the metamodel). - obj.layout = { - "id": elem_id, - "owner": elem.get("owner"), - "bounds": elem.get("bounds"), - "displayStereotype": elem.get("displayStereotype", True), - "wme_type": elem.get("type"), - } - editor_ids.assign(obj, elem_id) - nodes_by_id[elem_id] = obj - return nodes_by_id - - -def _build_component_node(elem_id: str, elem: dict) -> Optional[ComponentElement]: - """Build a single Component / Subsystem / Skill / Tool / Interface from - a WME element dict. - - Returns ``None`` when the element type is unknown (logs a warning). + obj.layout = node_layout(node, nodes_by_id) + editor_ids.assign(obj, node_id) + objects_by_id[node_id] = obj + return objects_by_id + + +def _build_component_node(node_id: str, node_type: str, data: dict) -> Optional[ComponentElement]: + """Build a Component / Subsystem / Skill / Tool / Interface from a v4 node. + + Returns ``None`` when the node type is unknown (logs a warning). """ - elem_type = elem.get("type") - name = elem.get("name") or "" - stereotype = elem.get("stereotype") or "" + name = data.get("name") or "" + stereotype = data.get("stereotype") or "" - if elem_type == "ComponentInterface": + if node_type == "componentInterface": return Interface(name=name) - if elem_type == "Subsystem": + if node_type == "componentSubsystem": subsystem = Subsystem(name=name) apply_component_stereotype_tokens(subsystem, stereotype) return subsystem - if elem_type == "Component": + if node_type == "component": subtype = parse_component_node_subtype(stereotype) if subtype is not None: # skill/tool/llm/db/rag → the matching Component subclass. obj = _COMPONENT_SUBTYPE_CLASSES[subtype](name=name) elif stereotype_has_agentic_tokens(stereotype): - # An agent-category token promotes a bare Component to - # AgenticComponent. + # An agent-category token promotes a bare Component to AgenticComponent. obj = AgenticComponent(name=name) else: obj = Component(name=name) @@ -165,166 +167,153 @@ def _build_component_node(elem_id: str, elem: dict) -> Optional[ComponentElement # Cross-diagram refs, read as the editor wrote them: realizes -> Class # ids, processModelRefs -> BPMN diagram ids, agentModelRef -> the Agent # diagram id. Resolved at project level. - obj.realizes = elem.get("realizes") or [] - obj.process_model_refs = elem.get("processModelRefs") or [] - obj.agent_model_ref = elem.get("agentModelRef") + obj.realizes = data.get("realizes") or [] + obj.process_model_refs = data.get("processModelRefs") or [] + obj.agent_model_ref = data.get("agentModelRef") or None return obj logger.warning( - "Component element %s has unknown type %r; skipping.", elem_id, elem_type, + "Component element %s has unknown type %r; skipping.", node_id, node_type, ) return None -def _reconstruct_containment(elements: dict, nodes_by_id: dict) -> None: - """Pass 2 — turn WME ``owner`` pointers into ``Subsystem.add_child`` calls. +def _reconstruct_containment(nodes: list, objects_by_id: dict) -> None: + """Pass 2 — turn ``parentId`` pointers into ``Subsystem.add_child`` calls. - A WME element's ``owner`` references another element's id. For - Component-diagram nodes, valid containment is *child -> Subsystem*; any - other shape (component pointing to interface, dangling owner) is logged - and the node stays top-level. A containment cycle raises - ``ConversionError``. + Valid containment is *Component -> Subsystem*; any other shape (an + Interface drawn inside a Subsystem, a dangling parent) is logged and the + element stays top-level. A containment cycle raises ``ConversionError``. """ - for elem_id, elem in elements.items(): - child = nodes_by_id.get(elem_id) - if child is None: - continue - owner_id = elem.get("owner") - if not owner_id: + for node in nodes: + node_id = node.get("id") + child = objects_by_id.get(node_id) + parent_id = node.get("parentId") + if child is None or not parent_id: continue - parent = nodes_by_id.get(owner_id) + parent = objects_by_id.get(parent_id) if parent is None: logger.warning( - "Component element %s references unknown owner %s; treating as root.", - elem_id, owner_id, + "Component element %s references unknown parent %s; treating as root.", + node_id, parent_id, ) continue if not isinstance(parent, Subsystem): logger.warning( - "Component element %s owner %s is %s, not Subsystem; " - "treating as root.", - elem_id, owner_id, type(parent).__name__, + "Component element %s parent %s is %s, not Subsystem; treating as root.", + node_id, parent_id, type(parent).__name__, ) continue if not isinstance(child, Component): - # Interfaces inside a Subsystem are not modelled (the metamodel - # places Interfaces on the model root). Drop the containment - # link; the Interface stays at root level. + # The metamodel places Interfaces on the model root; the drawn + # parent survives in the layout only. logger.warning( "Component element %s of type %s cannot be a child of " "Subsystem %s; staying at root.", - elem_id, type(child).__name__, owner_id, + node_id, type(child).__name__, parent_id, ) continue try: parent.add_child(child) except ValueError as exc: raise ConversionError( - f"Component element '{elem_id}' cannot be nested in '{owner_id}': {exc}" + f"Component element '{node_id}' cannot be nested in '{parent_id}': {exc}" ) from exc -def _build_relationships(relationships: dict, nodes_by_id: dict, editor_ids: EditorIds) -> list: +def _build_relationships(edges: list, objects_by_id: dict, editor_ids: EditorIds) -> list: """Pass 3: build relationships after all referenced elements exist.""" out: list = [] dangling_ownership = [] - for rel_id, rel in relationships.items(): - if not isinstance(rel, dict): - raise ConversionError( - f"Component relationship '{rel_id}' must be an object, " - f"got {type(rel).__name__}." - ) + for edge in edges: + edge_id = edge.get("id") try: - obj = _build_component_relationship(rel_id, rel, nodes_by_id) + obj = _build_component_relationship(edge, objects_by_id) except (TypeError, ValueError) as exc: raise ConversionError( - f"Could not build Component relationship '{rel_id}': {exc}" + f"Could not build Component relationship '{edge_id}': {exc}" ) from exc if obj is None: - if rel.get("type") in ("ComponentInterfaceProvided", "ComponentInterfaceRequired"): - dangling_ownership.append((rel_id, rel)) + if _is_interface_edge(edge.get("type")): + dangling_ownership.append(edge) continue - obj.layout = { - "id": rel_id, - "owner": rel.get("owner"), - "bounds": rel.get("bounds"), - "path": rel.get("path"), - "source_direction": (rel.get("source") or {}).get("direction"), - "target_direction": (rel.get("target") or {}).get("direction"), - "isManuallyLayouted": rel.get("isManuallyLayouted", False), - "wme_type": rel.get("type"), - } - editor_ids.assign(obj, rel_id) + layout = edge_layout(edge) + layout["type"] = edge.get("type") + obj.layout = layout + editor_ids.assign(obj, edge_id) out.append(obj) if dangling_ownership: # Skipping one of these links could turn an ambiguous dependency into shorthand. - capabilities = [edge for edge in out if isinstance(edge, AgenticEdge) - and edge.kind in (AgenticEdgeKind.KNOWS, AgenticEdgeKind.USES)] - owners = {("ComponentInterfaceProvided", edge.target) for edge in capabilities} - owners.update(("ComponentInterfaceRequired", edge.source) for edge in capabilities) - for rel_id, rel in dangling_ownership: - owner = nodes_by_id.get((rel.get("source") or {}).get("element")) - if (rel["type"], owner) in owners: - target_id = (rel.get("target") or {}).get("element") - raise ConversionError(f"Component relationship '{rel_id}' on '{owner.name}' " - f"references missing capability interface '{target_id}'.") + capabilities = [rel for rel in out if isinstance(rel, AgenticEdge) + and rel.kind in (AgenticEdgeKind.KNOWS, AgenticEdgeKind.USES)] + owners = {(True, rel.target) for rel in capabilities} + owners.update((False, rel.source) for rel in capabilities) + for edge in dangling_ownership: + owner = objects_by_id.get(edge.get("source")) + if (edge.get("type") == "ComponentProvidedInterface", owner) in owners: + raise ConversionError(f"Component relationship '{edge.get('id')}' on '{owner.name}' " + f"references missing capability interface '{edge.get('target')}'.") return drop_legacy_reverse_collaborations(out) -def _build_component_relationship(rel_id: str, rel: dict, nodes_by_id: dict) -> Optional[ComponentRelationship]: - """Build one relationship object from a WME edge dict. +def _is_interface_edge(edge_type) -> bool: + return edge_type == "ComponentProvidedInterface" or edge_type in COMPONENT_REQUIRED_INTERFACE_EDGE_TYPES + + +def _build_component_relationship(edge: dict, objects_by_id: dict) -> Optional[ComponentRelationship]: + """Build one relationship object from a v4 edge. - Branches on ``rel["type"]`` and (for ``ComponentDependency``) on the - agentic-edge kind extracted from the stereotype. A plain relationship keeps - its stereotype (e.g. «use») verbatim in ``stereotypes``; an AgenticEdge - keeps the tokens besides its kind. + Branches on the edge ``type`` and (for ``ComponentDependency``) on the + agentic-edge kind in ``data.stereotype``. A plain relationship keeps its + stereotype (e.g. «use») verbatim in ``stereotypes``; an AgenticEdge keeps + the tokens besides its kind. ``data.interfaceBinding`` and + ``data.collaborationDirection`` set the AgenticEdge's binding and direction. """ - rel_type = rel.get("type") - name = rel.get("name") or "" - stereotype = rel.get("stereotype") or "" + edge_id = edge.get("id") + edge_type = edge.get("type") + data = edge.get("data") if isinstance(edge.get("data"), dict) else {} + name = data.get("name") or data.get("label") or "" + stereotype = data.get("stereotype") or "" if not isinstance(stereotype, str): raise TypeError("stereotype must be a string.") - if rel_type == "ComponentDependency": - stereotype = _migrate_legacy_edge_kind(rel_id, stereotype, rel, nodes_by_id) + if edge_type == "ComponentDependency": + stereotype = _migrate_legacy_edge_kind(edge_id, stereotype, edge, objects_by_id) free_form = stereotype.split() - kind = parse_agentic_edge_kind(stereotype) if rel_type == "ComponentDependency" else None + kind = parse_agentic_edge_kind(stereotype) if edge_type == "ComponentDependency" else None if kind is not None and _PERMISSION_SUFFIX.search(stereotype): # Permissions were retired; the editor strips the suffix when it loads the edge. logger.warning("Component relationship %s: dropping the retired permission suffix from %r.", - rel_id, stereotype) + edge_id, stereotype) stereotype = _PERMISSION_SUFFIX.sub(" ", stereotype) - if "interfaceBinding" in rel and kind is None: + if "interfaceBinding" in data and kind is None: raise ValueError("interfaceBinding belongs on a KNOWS or USES dependency.") collaboration_direction = None - if "collaborationDirection" in rel: + if "collaborationDirection" in data: if kind is not AgenticEdgeKind.COLLABORATES: raise ValueError("collaborationDirection belongs on a COLLABORATES dependency.") try: - collaboration_direction = CollaborationDirection(rel["collaborationDirection"]) + collaboration_direction = CollaborationDirection(data["collaborationDirection"]) except ValueError as exc: raise ValueError("collaborationDirection must be 'directed' or 'reciprocal'.") from exc - source_ref, target_ref = rel.get("source") or {}, rel.get("target") or {} - if not isinstance(source_ref, dict) or not isinstance(target_ref, dict): - raise TypeError("source and target must be objects with element IDs.") - source_id, target_id = source_ref.get("element"), target_ref.get("element") - source, target = nodes_by_id.get(source_id), nodes_by_id.get(target_id) + source_id, target_id = edge.get("source"), edge.get("target") + source, target = objects_by_id.get(source_id), objects_by_id.get(target_id) if source is None or target is None: detail = f"dangling endpoint(s) (source={source_id}, target={target_id})" if kind is not None: raise ValueError(detail) - logger.warning("Component relationship %s has %s; skipping.", rel_id, detail) + logger.warning("Component relationship %s has %s; skipping.", edge_id, detail) return None - if rel_type == "ComponentInterfaceProvided": + if edge_type == "ComponentProvidedInterface": return InterfaceProvided(source=source, target=target, name=name, stereotypes=free_form) - if rel_type == "ComponentInterfaceRequired": + if edge_type in COMPONENT_REQUIRED_INTERFACE_EDGE_TYPES: return InterfaceRequired(source=source, target=target, name=name, stereotypes=free_form) - if rel_type == "ComponentDependency": + if edge_type == "ComponentDependency": if kind is None: return ComponentDependency(source=source, target=target, name=name, stereotypes=free_form) @@ -332,19 +321,19 @@ def _build_component_relationship(rel_id: str, rel: dict, nodes_by_id: dict) -> source=source, target=target, kind=kind, name=name, stereotypes=agentic_edge_extra_tokens(stereotype, kind), - interface_binding=(_resolve_interface_binding(rel["interfaceBinding"], nodes_by_id) - if "interfaceBinding" in rel else None), + interface_binding=(_resolve_interface_binding(data["interfaceBinding"], objects_by_id) + if "interfaceBinding" in data else None), collaboration_direction=collaboration_direction, ) logger.warning( "Component relationship %s has unknown type %r; skipping.", - rel_id, rel_type, + edge_id, edge_type, ) return None -def _migrate_legacy_edge_kind(rel_id: str, stereotype: str, rel: dict, nodes_by_id: dict) -> str: +def _migrate_legacy_edge_kind(edge_id: str, stereotype: str, edge: dict, objects_by_id: dict) -> str: """Rename a retired «has» / «revises» token whose endpoints fit its successor kind. «has» (agent -> skill) became «knows»; «revises» became «submits», which @@ -353,30 +342,27 @@ def _migrate_legacy_edge_kind(rel_id: str, stereotype: str, rel: dict, nodes_by_ """ tokens = tokenise_component_stereotype(stereotype) legacy = next((token for token in tokens if token in LEGACY_EDGE_KINDS), None) - source_ref, target_ref = rel.get("source"), rel.get("target") - if legacy is None or parse_agentic_edge_kind(stereotype) is not None or not ( - isinstance(source_ref, dict) and isinstance(target_ref, dict) - ): + if legacy is None or parse_agentic_edge_kind(stereotype) is not None: return stereotype - source, target = nodes_by_id.get(source_ref.get("element")), nodes_by_id.get(target_ref.get("element")) + source, target = objects_by_id.get(edge.get("source")), objects_by_id.get(edge.get("target")) successor = legacy_edge_successor(legacy, source, target) if successor is None: return stereotype logger.warning("Component relationship %s: reading the retired kind %r as %r.", - rel_id, legacy, successor.value) + edge_id, legacy, successor.value) return " ".join(successor.value if token == legacy else token for token in tokens) -def _resolve_interface_binding(binding, nodes_by_id: dict) -> tuple[Interface, Interface]: - """Resolve the required and provided interface element IDs of a dependency.""" +def _resolve_interface_binding(binding, objects_by_id: dict) -> tuple[Interface, Interface]: + """Resolve the required and provided interface node IDs of a dependency.""" if not isinstance(binding, dict): raise TypeError("interfaceBinding must be an object with required and provided interface IDs.") required_id = binding.get("required") provided_id = binding.get("provided") if not isinstance(required_id, str) or not isinstance(provided_id, str): raise TypeError("interfaceBinding must specify both required and provided interface IDs.") - required = nodes_by_id.get(required_id) - provided = nodes_by_id.get(provided_id) + required = objects_by_id.get(required_id) + provided = objects_by_id.get(provided_id) if not isinstance(required, Interface) or not isinstance(provided, Interface): - raise ValueError("interfaceBinding required and provided IDs must refer to ComponentInterface elements.") + raise ValueError("interfaceBinding required and provided IDs must refer to componentInterface nodes.") return required, provided diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/deployment_diagram_processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/deployment_diagram_processor.py index dbc17b56a..7795a0e14 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/deployment_diagram_processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/deployment_diagram_processor.py @@ -1,12 +1,13 @@ -"""Deployment diagram processing: WME JSON -> DeploymentModel. +"""Deployment diagram processing: v4 WME JSON (``{nodes, edges}``) -> DeploymentModel. Three-pass walk: build nodes / artifacts / interfaces, rebuild containment from -the ``owner`` chain, then build relationships. The editor's -``DeploymentComponent`` element becomes a ``DeploymentComponent`` (an -``Artifact`` subclass the generators never deploy), the multiplicity is parsed -from the artifact name (``"Coder [3]"``), and ``DeploymentAssociation`` is -discriminated on its endpoint types (Artifact -> Node is a -``DeploymentRelation``, Node <-> Node a ``CommunicationPath``). +the ``parentId`` chain, then build relationships. The editor's +``deploymentComponent`` node becomes a ``DeploymentComponent`` (an ``Artifact`` +subclass the generators never deploy), the multiplicity is parsed from the +artifact name (``"Coder [3]"``), and ``DeploymentAssociation`` is discriminated +on its endpoint types (Artifact -> Node is a ``DeploymentRelation``, +Node <-> Node a ``CommunicationPath``). Wire shape: +``docs/source/migrations/uml-v4-shape.md`` (DeploymentDiagram). Element or relationship data the metamodel rejects raises ``ConversionError``; unknown element types and dangling relationship endpoints are logged and @@ -29,6 +30,14 @@ InterfaceRequired, Node, ) +from besser.utilities.web_modeling_editor.backend.constants.constants import ( + DEPLOYMENT_REQUIRED_INTERFACE_EDGE_TYPES, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + edge_layout, + node_data, + node_layout, +) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import EditorIds from besser.utilities.web_modeling_editor.backend.services.converters.multiplicity_format import ( parse_from_name, @@ -40,15 +49,18 @@ from besser.utilities.web_modeling_editor.backend.services.exceptions import ( ConversionError, ) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + reject_unreadable_model, +) logger = logging.getLogger(__name__) def process_deployment_diagram(json_data: dict) -> DeploymentModel: - """Convert a WME Deployment diagram (JSON) into a ``DeploymentModel``. + """Convert a v4 WME Deployment diagram into a ``DeploymentModel``. Args: - json_data: ``{"title": , "model": {...}}`` envelope. + json_data: ``{"title": , "model": {"nodes": [...], "edges": [...]}}``. Returns: DeploymentModel: assembled metamodel instance. @@ -57,6 +69,7 @@ def process_deployment_diagram(json_data: dict) -> DeploymentModel: ConversionError: structural failures (missing ``model``, an element or relationship the metamodel rejects, a containment cycle). """ + reject_unreadable_model(json_data, "DeploymentDiagram") if not isinstance(json_data, dict): raise ConversionError( f"Deployment diagram payload must be a dict, " @@ -65,23 +78,23 @@ def process_deployment_diagram(json_data: dict) -> DeploymentModel: model_data = json_data.get("model") if not isinstance(model_data, dict): raise ConversionError("Deployment diagram JSON is missing the 'model' key.") - elements = model_data.get("elements") or {} - relationships = model_data.get("relationships") or {} + nodes = [n for n in (model_data.get("nodes") or []) if isinstance(n, dict)] + edges = [e for e in (model_data.get("edges") or []) if isinstance(e, dict)] name = json_data.get("title") or "Generated_Deployment_Model" # Elements and relationships take their editor id: the id a trace refers to them by. editor_ids = EditorIds() - nodes_by_id, parsed_multiplicities = _build_nodes(elements, editor_ids) - owner_links = _reconstruct_containment(elements, nodes_by_id) + objects_by_id, parsed_multiplicities = _build_nodes(nodes, editor_ids) + owner_links = _reconstruct_containment(nodes, objects_by_id) relationship_objects = _build_relationships( - relationships, nodes_by_id, parsed_multiplicities, owner_links, editor_ids, + edges, objects_by_id, parsed_multiplicities, owner_links, editor_ids, ) - root_nodes = {obj for obj in nodes_by_id.values() + root_nodes = {obj for obj in objects_by_id.values() if isinstance(obj, Node) and obj.parent is None} - root_artifacts = {obj for obj in nodes_by_id.values() + root_artifacts = {obj for obj in objects_by_id.values() if isinstance(obj, Artifact) and obj.parent is None} - interfaces = {obj for obj in nodes_by_id.values() if isinstance(obj, Interface)} + interfaces = {obj for obj in objects_by_id.values() if isinstance(obj, Interface)} return DeploymentModel( name=name, @@ -92,191 +105,169 @@ def process_deployment_diagram(json_data: dict) -> DeploymentModel: ) -def _build_nodes(elements: dict, editor_ids: EditorIds) -> tuple: - """Pass 1 — create every element object, indexed by WME id. +def _build_nodes(nodes: list, editor_ids: EditorIds) -> tuple: + """Pass 1 — create every element object, indexed by node id. - Returns ``(nodes_by_id, parsed_multiplicities)`` — the second map keys - artifact WME-ids to the ``Multiplicity`` parsed from their names, so + Returns ``(objects_by_id, parsed_multiplicities)`` — the second map keys + artifact node ids to the ``Multiplicity`` parsed from their names, so Pass 3 can apply it on ``DeploymentRelation`` construction. """ - nodes_by_id: dict = {} + nodes_by_id = {n.get("id"): n for n in nodes if n.get("id")} + objects_by_id: dict = {} parsed_multiplicities: dict = {} - for elem_id, elem in elements.items(): - if not isinstance(elem, dict): - raise ConversionError( - f"Deployment element '{elem_id}' must be an object, " - f"got {type(elem).__name__}." - ) + for node in nodes: + node_id = node.get("id") + data = node_data(node) try: - obj, parsed_mult = _build_deployment_node(elem_id, elem) + obj, parsed_mult = _build_deployment_node(node_id, node.get("type"), data) except (TypeError, ValueError) as exc: raise ConversionError( - f"Could not build Deployment element '{elem_id}': {exc}" + f"Could not build Deployment element '{node_id}': {exc}" ) from exc if obj is None: continue if parsed_mult is not None: - parsed_multiplicities[elem_id] = parsed_mult - layout = { - "id": elem_id, - "owner": elem.get("owner"), - "bounds": elem.get("bounds"), - "displayStereotype": elem.get("displayStereotype", True), - "wme_type": elem.get("type"), - } + parsed_multiplicities[node_id] = parsed_mult + layout = node_layout(node, nodes_by_id) # Keep the raw name so the converter restores the exact string when # the parsed multiplicity is the default (e.g. "Coder [1]"). - raw_name = elem.get("name") or "" + raw_name = data.get("name") or "" if parsed_mult is not None and raw_name != obj.name: layout["original_name"] = raw_name obj.layout = layout - editor_ids.assign(obj, elem_id) - nodes_by_id[elem_id] = obj - return nodes_by_id, parsed_multiplicities + editor_ids.assign(obj, node_id) + objects_by_id[node_id] = obj + return objects_by_id, parsed_multiplicities -def _build_deployment_node(elem_id: str, elem: dict) -> tuple: +def _build_deployment_node(node_id: str, node_type: str, data: dict) -> tuple: """Build a single Node / Artifact / DeploymentComponent / Interface. Returns ``(obj, parsed_multiplicity)``. ``manifests`` (ids of the Components an Artifact manifests) and ``agentModelRef`` (the Agent diagram - an Artifact deploys) are read from the element as the editor wrote them. + an Artifact deploys) are read from ``data`` as the editor wrote them. """ - elem_type = elem.get("type") - raw_name = elem.get("name") or "" - stereotype = elem.get("stereotype") or "" + raw_name = data.get("name") or "" + stereotype = data.get("stereotype") or "" - if elem_type == "DeploymentNode": + if node_type == "deploymentNode": node = Node(name=raw_name) apply_node_stereotype_tokens(node, stereotype) return node, None - if elem_type == "DeploymentInterface": + if node_type == "deploymentInterface": return Interface(name=raw_name), None - if elem_type in ("DeploymentArtifact", "DeploymentComponent"): - artifact_class = Artifact if elem_type == "DeploymentArtifact" else DeploymentComponent + if node_type in ("deploymentArtifact", "deploymentComponent"): + artifact_class = Artifact if node_type == "deploymentArtifact" else DeploymentComponent clean_name, mult = parse_from_name(raw_name) artifact = artifact_class( name=clean_name, - manifests=elem.get("manifests") or [], - agent_model_ref=elem.get("agentModelRef"), + manifests=data.get("manifests") or [], + agent_model_ref=data.get("agentModelRef") or None, ) apply_artifact_stereotype_tokens(artifact, stereotype) return artifact, mult logger.warning( - "Deployment element %s has unknown type %r; skipping.", elem_id, elem_type, + "Deployment element %s has unknown type %r; skipping.", node_id, node_type, ) return None, None -def _reconstruct_containment(elements: dict, nodes_by_id: dict) -> dict: - """Pass 2 — turn WME ``owner`` pointers into nested object containment. +def _reconstruct_containment(nodes: list, objects_by_id: dict) -> dict: + """Pass 2 — turn ``parentId`` pointers into nested object containment. - Returns ``{artifact_id: node_id}`` for every artifact-on-node owner link, + Returns ``{artifact_id: node_id}`` for every artifact-on-node parent link, so Pass 3 can deduplicate against explicit ``DeploymentAssociation`` - edges (an owner link and an explicit edge express the same deployment; + edges (a parent link and an explicit edge express the same deployment; only one ``DeploymentRelation`` is emitted). """ owner_links: dict = {} - for elem_id, elem in elements.items(): - child = nodes_by_id.get(elem_id) - if child is None: + for node in nodes: + node_id = node.get("id") + child = objects_by_id.get(node_id) + parent_id = node.get("parentId") + if child is None or not parent_id: continue - owner_id = elem.get("owner") - if not owner_id: - continue - parent = nodes_by_id.get(owner_id) + parent = objects_by_id.get(parent_id) if parent is None: logger.warning( - "Deployment element %s references unknown owner %s; " - "treating as root.", - elem_id, owner_id, + "Deployment element %s references unknown parent %s; treating as root.", + node_id, parent_id, ) continue if isinstance(child, Artifact) and isinstance(parent, Node): parent.add_artifact(child) - owner_links[elem_id] = owner_id + owner_links[node_id] = parent_id elif isinstance(child, Node) and isinstance(parent, Node): try: parent.add_nested_node(child) except ValueError as exc: raise ConversionError( - f"Deployment node '{elem_id}' cannot be nested in '{owner_id}': {exc}" + f"Deployment node '{node_id}' cannot be nested in '{parent_id}': {exc}" ) from exc elif isinstance(child, Interface): - # Interfaces live on the model root; the drawn owner is layout only - # (kept in ``layout["owner"]``). + # Interfaces live on the model root; the drawn parent is layout only + # (kept in ``layout["parentId"]``). continue else: logger.warning( "Deployment element %s of type %s cannot be a child of " "type %s; staying at root.", - elem_id, type(child).__name__, type(parent).__name__, + node_id, type(child).__name__, type(parent).__name__, ) return owner_links -def _build_relationships(relationships: dict, nodes_by_id: dict, +def _build_relationships(edges: list, objects_by_id: dict, parsed_multiplicities: dict, owner_links: dict, editor_ids: EditorIds) -> list: """Pass 3 — build relationship objects, discriminating ``DeploymentAssociation`` by endpoint type, applying parsed multiplicity - on ``DeploymentRelation``, and deduplicating against owner links. + on ``DeploymentRelation``, and deduplicating against parent links. """ out: list = [] explicit_artifact_on_node: set = set() # (artifact_id, node_id) pairs - for rel_id, rel in relationships.items(): - if not isinstance(rel, dict): - raise ConversionError( - f"Deployment relationship '{rel_id}' must be an object, " - f"got {type(rel).__name__}." - ) - source_id = (rel.get("source") or {}).get("element") - target_id = (rel.get("target") or {}).get("element") - source = nodes_by_id.get(source_id) - target = nodes_by_id.get(target_id) + for edge in edges: + edge_id = edge.get("id") + source_id = edge.get("source") + target_id = edge.get("target") + source = objects_by_id.get(source_id) + target = objects_by_id.get(target_id) if source is None or target is None: logger.warning( "Deployment relationship %s has dangling endpoint(s) " "(source=%s, target=%s); skipping.", - rel_id, source_id, target_id, + edge_id, source_id, target_id, ) continue try: obj = _build_deployment_relationship( - rel_id, rel, source, target, source_id, parsed_multiplicities, + edge, source, target, parsed_multiplicities.get(source_id), ) except (TypeError, ValueError) as exc: raise ConversionError( - f"Could not build Deployment relationship '{rel_id}': {exc}" + f"Could not build Deployment relationship '{edge_id}': {exc}" ) from exc if obj is None: continue if isinstance(obj, DeploymentRelation): explicit_artifact_on_node.add((source_id, target_id)) - obj.layout = { - "id": rel_id, - "owner": rel.get("owner"), - "bounds": rel.get("bounds"), - "path": rel.get("path"), - "source_direction": (rel.get("source") or {}).get("direction"), - "target_direction": (rel.get("target") or {}).get("direction"), - "isManuallyLayouted": rel.get("isManuallyLayouted", False), - "wme_type": rel.get("type"), - "wme_origin": "association", - } - editor_ids.assign(obj, rel_id) + layout = edge_layout(edge) + layout["type"] = edge.get("type") + layout["wme_origin"] = "association" + obj.layout = layout + editor_ids.assign(obj, edge_id) out.append(obj) - # Synthesise DeploymentRelation for owner-link artifact-on-node pairs + # Synthesise DeploymentRelation for parent-link artifact-on-node pairs # that did NOT also have an explicit DeploymentAssociation. for artifact_id, node_id in owner_links.items(): if (artifact_id, node_id) in explicit_artifact_on_node: continue rel = DeploymentRelation( - source=nodes_by_id[artifact_id], target=nodes_by_id[node_id], + source=objects_by_id[artifact_id], target=objects_by_id[node_id], multiplicity=parsed_multiplicities.get(artifact_id), ) rel.layout = {"wme_origin": "owner"} @@ -286,44 +277,44 @@ def _build_relationships(relationships: dict, nodes_by_id: dict, def _build_deployment_relationship( - rel_id: str, rel: dict, source, target, - source_id: str, parsed_multiplicities: dict, + edge: dict, source, target, source_multiplicity, ) -> Optional[DeploymentRelationship]: - """Build one relationship object from a WME edge dict. + """Build one relationship object from a v4 edge. - Branches on ``rel["type"]`` and, for ``DeploymentAssociation``, on the - endpoint types. The free-form ``stereotype`` string is kept as the + Branches on the edge ``type`` and, for ``DeploymentAssociation``, on the + endpoint types. The free-form ``data.stereotype`` string is kept as the relationship's ``stereotypes`` (whitespace-separated) so it round-trips. """ - rel_type = rel.get("type") - name = rel.get("name") or "" - stereotypes = (rel.get("stereotype") or "").split() + edge_type = edge.get("type") + data = edge.get("data") if isinstance(edge.get("data"), dict) else {} + name = data.get("name") or data.get("label") or "" + stereotypes = (data.get("stereotype") or "").split() - if rel_type == "DeploymentDependency": + if edge_type == "DeploymentDependency": return DeploymentDependency(source=source, target=target, name=name, stereotypes=stereotypes) - if rel_type == "DeploymentInterfaceProvided": + if edge_type == "DeploymentProvidedInterface": return InterfaceProvided(source=source, target=target, name=name, stereotypes=stereotypes) - if rel_type == "DeploymentInterfaceRequired": + if edge_type in DEPLOYMENT_REQUIRED_INTERFACE_EDGE_TYPES: return InterfaceRequired(source=source, target=target, name=name, stereotypes=stereotypes) - if rel_type == "DeploymentAssociation": + if edge_type == "DeploymentAssociation": if isinstance(source, Artifact) and isinstance(target, Node): return DeploymentRelation( source=source, target=target, name=name, stereotypes=stereotypes, - multiplicity=parsed_multiplicities.get(source_id), + multiplicity=source_multiplicity, ) if isinstance(source, Node) and isinstance(target, Node): return CommunicationPath(source=source, target=target, name=name, stereotypes=stereotypes) raise ConversionError( - f"DeploymentAssociation '{rel_id}' must connect Artifact -> Node or " + f"DeploymentAssociation '{edge.get('id')}' must connect Artifact -> Node or " f"Node -> Node, got {type(source).__name__} -> {type(target).__name__}." ) logger.warning( "Deployment relationship %s has unknown type %r; skipping.", - rel_id, rel_type, + edge.get("id"), edge_type, ) return None diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/gui_processors/processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/gui_processors/processor.py index 881633582..368df2479 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/gui_processors/processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/gui_processors/processor.py @@ -174,6 +174,37 @@ def is_traced_component(component: Dict[str, Any]) -> bool: return not comp_type and component.get("tagName") in INPUT_COMPONENT_TYPES +def _element_name(element): + """Return the display name of a class-model element. + + v4 nodes keep the name on ``node.data.name``; legacy v3-style element + dicts keep it at the top level. Returns ``None`` when unresolvable. + """ + if not isinstance(element, dict): + return None + data = element.get("data") + if isinstance(data, dict) and data.get("name") is not None: + return data.get("name") + return element.get("name") + + +def _find_method_row(class_element, method_id): + """Return the method row with the given id from a class element. + + v4 collapses method rows onto the class node's ``data.methods`` array, + so method-row ids are NOT top-level node ids. Accepts both the v4 node + shape (rows under ``data``) and legacy dicts (rows at the top level). + """ + if not isinstance(class_element, dict) or not method_id: + return None + data = class_element.get("data") + container = data if isinstance(data, dict) else class_element + for row in container.get("methods") or []: + if isinstance(row, dict) and row.get("id") == method_id: + return row + return None + + def process_gui_diagram(gui_diagram, class_model, domain_model): """ Main entry point: Converts GrapesJS JSON and domain_model into a GUIModel instance. @@ -725,7 +756,7 @@ def resolve_class(class_ref): if not domain_model or not class_ref: return None class_el = get_element_by_id(class_model, class_ref) - class_name = class_el.get('name') if class_el else class_ref + class_name = (_element_name(class_el) if class_el else None) or class_ref return domain_model.get_class_by_name(class_name) # Post-processing: Resolve Action and Button class references @@ -739,13 +770,20 @@ def resolve_action_references(elements): method_class_id = getattr(element, '_method_class_id') method_id = getattr(element, '_method_id') - # Step 1: Get the class and method elements from class_model (JSON) by ID + # Step 1: Get the class node from class_model (JSON) by ID method_class_el = get_element_by_id(class_model, method_class_id) - method_el = get_element_by_id(class_model, method_id) - # Step 2: Extract the names from the JSON elements - method_class_name = method_class_el.get('name') if method_class_el else None - method_name_raw = method_el.get('name') if method_el else None + # Step 2: Extract the names. v4 stores the class name on + # ``node.data.name`` and method rows inside the class + # node's ``data.methods`` (row ids are not node ids). + method_class_name = _element_name(method_class_el) + method_row = _find_method_row(method_class_el, method_id) + if method_row is not None: + method_name_raw = method_row.get('name') + else: + # Legacy fallback: method as its own top-level element. + method_el = get_element_by_id(class_model, method_id) + method_name_raw = _element_name(method_el) # Clean the method name to remove visibility, parameters, and type annotations method_name = clean_method_name(method_name_raw) if method_name_raw else None diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/gui_processors/utils.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/gui_processors/utils.py index f0a36eb25..440ef27ce 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/gui_processors/utils.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/gui_processors/utils.py @@ -130,10 +130,28 @@ def get_element_by_id(class_model, element_id): if isinstance(class_model, dict): if element_id in class_model: return class_model[element_id] - # If this is a full diagram dict, look under 'elements' - if 'elements' in class_model and isinstance(class_model['elements'], dict): - if element_id in class_model['elements']: - return class_model['elements'][element_id] + + # v4 wire shape: full diagram dict with nodes list. Class nodes keep + # their name on ``data.name`` and their attribute / method rows under + # ``data.attributes`` / ``data.methods`` (rows are not nodes), so the + # callers' v3-era ``element.get('name')`` lookups get a copy of the + # node with ``name`` hoisted, and row ids resolve to the row itself. + nodes = class_model.get('nodes') + if isinstance(nodes, list): + for node in nodes: + if isinstance(node, dict) and node.get('id') == element_id: + data = node.get('data') + if isinstance(data, dict) and 'name' not in node and 'name' in data: + return {**node, 'name': data.get('name')} + return node + for node in nodes: + data = node.get('data') if isinstance(node, dict) else None + if not isinstance(data, dict): + continue + for row_key in ('attributes', 'methods'): + for row in data.get(row_key) or []: + if isinstance(row, dict) and row.get('id') == element_id: + return row # List format if isinstance(class_model, list): diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/nn_diagram_processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/nn_diagram_processor.py index c798a0131..e05be9024 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/nn_diagram_processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/nn_diagram_processor.py @@ -1,8 +1,10 @@ """ -NN diagram processing for converting JSON to BUML format. +NN diagram processing for converting v4 JSON to BUML format. -This module converts Neural Network diagram JSON from the web editor -to BESSER's B-UML NN metamodel (NN, Layer, TensorOp, Configuration). +Reads the v4 wire shape (``{nodes, edges}``) natively. Each layer node +stores its attributes inline as ``data.attributes: dict[str, str]`` per +the spec at ``docs/source/migrations/uml-v4-shape.md`` — there are no +separate ``*Attribute*Layer*`` child elements in v4. """ import ast @@ -31,15 +33,18 @@ TensorOp, ) from besser.utilities.buml_code_builder.nn_explicit_attrs import mark_explicit +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + node_data, +) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import EditorIds from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.utils import ( sanitize_name, ) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + reject_unreadable_model, +) -# Keep these aligned with the whitelists the NN metamodel setters enforce -# (besser/BUML/metamodel/nn/neural_network.py). Re-asserting them here lets -# us raise a user-facing error that names the diagram element, before the -# raw metamodel ValueError (which knows nothing about which layer failed). +# Keep these aligned with the whitelists the NN metamodel setters enforce. _ALLOWED_POOLING_TYPES = ( 'average', 'adaptive_average', 'max', 'adaptive_max', 'global_average', 'global_max', @@ -56,84 +61,11 @@ _CONV_EXPECTED_DIMS = {'Conv1D': 1, 'Conv2D': 2, 'Conv3D': 3} -def _get_attr_by_name(element: dict, attr_name: str, elements: dict, default=None): - """Get an attribute value by its attributeName field (used for dataset elements).""" - for attr_id in element.get('attributes', []): - attr_el = elements.get(attr_id, {}) - if attr_el.get('attributeName') == attr_name: - return attr_el.get('value', default) - return default - - -def create_dataset(element: dict, elements: dict) -> Dataset: - """Create a Dataset (and optional Image) from a TrainingDataset/TestDataset element.""" - name = _get_attr_by_name(element, 'name', elements) - if not name: - raise ValueError("Dataset missing mandatory 'name' attribute") - path_data = _get_attr_by_name(element, 'path_data', elements) - if not path_data: - raise ValueError("Dataset missing mandatory 'path_data' attribute") - - task_type = _get_attr_by_name(element, 'task_type', elements) or None - if task_type is not None and task_type not in _ALLOWED_TASK_TYPES: - raise ValueError( - f"Dataset '{name}' has invalid task_type '{task_type}'. " - f"Allowed values: {', '.join(_ALLOWED_TASK_TYPES)}." - ) - input_format = _get_attr_by_name(element, 'input_format', elements) or None - if input_format is not None and input_format not in _ALLOWED_INPUT_FORMATS: - raise ValueError( - f"Dataset '{name}' has invalid input_format '{input_format}'. " - f"Allowed values: {', '.join(_ALLOWED_INPUT_FORMATS)}." - ) - - # Reconstruct Image whenever shape/normalize attributes are present, - # matching the converter's emission rule (which emits shape/normalize - # whenever dataset.image is not None, independent of input_format). The - # old "only when input_format == 'images'" guard dropped images on any - # round-trip of a hand-authored BUML Dataset with a non-'images' format. - image = None - shape_raw = _get_attr_by_name(element, 'shape', elements) - normalize_raw = _get_attr_by_name(element, 'normalize', elements) - # Treat empty strings as absent (user cleared the field). Otherwise the - # fall-through path below would attach a default Image(shape=[256,256]) - # to a Dataset the user didn't intend to have one. - shape_present = shape_raw is not None and shape_raw != '' - normalize_present = normalize_raw is not None and str(normalize_raw) != '' - if shape_present or normalize_present or input_format == 'images': - if shape_raw is None or shape_raw == '': - # Documented default; downstream generators treat it as "user - # didn't specify". Keep as-is to avoid breaking existing models - # that rely on the fallback. - shape = [256, 256] - elif isinstance(shape_raw, (list, tuple)): - shape = list(shape_raw) - else: - try: - shape = ast.literal_eval(str(shape_raw)) - except (ValueError, SyntaxError) as exc: - raise ValueError( - f"Dataset '{name}' has malformed 'shape' attribute " - f"{shape_raw!r}: expected a list like [32, 32, 3]" - ) from exc - if not isinstance(shape, (list, tuple)): - raise ValueError( - f"Dataset '{name}' 'shape' attribute must be a list " - f"(got {type(shape).__name__})" - ) - shape = list(shape) - normalize = str(normalize_raw).lower() == 'true' if normalize_raw is not None else False - image = Image(shape=shape, normalize=normalize) - - return Dataset(name=name, path_data=path_data, task_type=task_type, - input_format=input_format, image=image) - - -# Map the `attr_key` prefix used at call sites (e.g. 'NameAttribute', -# 'KernelDimAttribute') to the `attributeName` field emitted by the -# frontend/converter (e.g. 'name', 'kernel_dim'). Using the `attributeName` -# field rather than a substring match on `type` avoids collisions between -# attributes whose type names share a prefix/suffix. +# v4: layer attributes live as a snake_case dict on ``data.attributes``. +# This mapping translates the legacy "Attribute" prefix used at call +# sites into the v4 dict key. Kept verbatim for source-level compatibility +# with the existing ``get_element_attribute(node, 'NameAttribute', ...)`` +# style call pattern. _ATTR_KEY_TO_NAME = { 'NameAttribute': 'name', 'KernelDimAttribute': 'kernel_dim', @@ -152,7 +84,7 @@ def create_dataset(element: dict, elements: dict) -> Dataset: 'InputVarAttribute': 'input_var', 'OutputVarAttribute': 'output_var', 'PoolingTypeAttribute': 'pooling_type', - 'DimensionAttribute': 'dimension', + 'DimensionAttribute': 'dimension', # see _LAYER_KIND_PREFIX for qualified-slug disambiguation 'OutputDimAttribute': 'output_dim', 'HiddenSizeAttribute': 'hidden_size', 'InputSizeAttribute': 'input_size', @@ -218,51 +150,68 @@ def create_dataset(element: dict, elements: dict) -> Dataset: 'MetricsAttribute': 'metrics', 'WeightDecayAttribute': 'weight_decay', 'MomentumAttribute': 'momentum', + 'PathDataAttribute': 'path_data', + 'TaskTypeAttribute': 'task_type', + 'InputFormatAttribute': 'input_format', + 'ShapeAttribute': 'shape', + 'NormalizeAttribute': 'normalize', } -def get_element_attribute(element: dict, attr_key: str, elements: dict, default=None): - """ - Get an attribute value from an element's attribute children. - - Lookup is done via the `attributeName` field emitted by the frontend (which - is stable across layer types), with an exact-prefix fallback on `type` - (e.g. 'NameAttributeConv2D' starts with 'NameAttribute'). Substring - matching is deliberately avoided to prevent collisions between attributes - whose type names share segments (e.g. 'NameAttribute' vs - 'NameModuleInputAttribute'). - - Args: - element: The parent element - attr_key: The attribute suffix to look for (e.g., 'NameAttribute') - elements: All elements dictionary - default: Default value if not found - - Returns: - The attribute value or default +# Some attribute slugs collide across layer kinds (e.g. `dimension` exists on +# both PoolingLayer and BatchNormalizationLayer with different semantics). +# The frontend disambiguates via `qualifySlug(layerKind, slug)` → +# `.`. Mirror the same mapping here so v4 inputs round-trip. +_COLLIDING_SLUGS = frozenset({'dimension'}) +_LAYER_KIND_PREFIX = { + 'PoolingLayer': 'pooling', + 'BatchNormalizationLayer': 'batch_normalization', +} + + +def get_element_attribute(node: dict, attr_key: str, elements_or_default=None, default=None): + """Read a layer attribute. + + Production code passes a v4 node and reads from + ``node.data.attributes`` (a dict). The legacy three-arg form + ``(element, attr_key, elements)`` is preserved for targeted unit + tests at ``tests/utilities/web_modeling_editor/converters/nn/`` that + pass v3 element + elements dicts directly. """ - attribute_name = _ATTR_KEY_TO_NAME.get(attr_key) - attribute_ids = element.get('attributes', []) - - for attr_id in attribute_ids: - attr_element = elements.get(attr_id, {}) - - # Preferred: match by `attributeName` (set consistently by the converter). - if attribute_name is not None and attr_element.get('attributeName') == attribute_name: - return attr_element.get('value', default) - - # Fallback for legacy payloads that only carry `type`: require an - # exact prefix match so 'NameAttribute' doesn't pick up - # 'NameModuleInputAttributeConv2D'. - attr_type = attr_element.get('type', '') - if attr_type.startswith(attr_key): - # Reject partial matches where the next char isn't the layer-suffix - # boundary (e.g. 'NameAttributeExtra' should not match 'NameAttribute'). - rest = attr_type[len(attr_key):] - if rest == '' or rest[0].isupper(): - return attr_element.get('value', default) + name = _ATTR_KEY_TO_NAME.get(attr_key) + # Distinguish the two call forms by whether the third arg is a dict. + if isinstance(elements_or_default, dict): + elements = elements_or_default + if name is not None: + for attr_id in (node or {}).get('attributes', []) or []: + attr_el = elements.get(attr_id, {}) + if attr_el.get('attributeName') == name: + return attr_el.get('value', default) + # Legacy fallback: prefix-match on type with boundary check. + for attr_id in (node or {}).get('attributes', []) or []: + attr_el = elements.get(attr_id, {}) + attr_type = attr_el.get('type', '') + if attr_type.startswith(attr_key): + rest = attr_type[len(attr_key):] + if rest == '' or rest[0].isupper(): + return attr_el.get('value', default) + return default - return default + # v4 form. + if name is None: + return elements_or_default if elements_or_default is not None else default + data = node_data(node) + attrs = data.get("attributes") or {} + if not isinstance(attrs, dict): + return elements_or_default if elements_or_default is not None else default + fallback = elements_or_default if elements_or_default is not None else default + if name in _COLLIDING_SLUGS: + prefix = _LAYER_KIND_PREFIX.get((node or {}).get('type', '')) + if prefix is not None: + qualified = f'{prefix}.{name}' + if qualified in attrs: + return attrs[qualified] + return attrs.get(name, fallback) def _coerce_list_item(item, prefer_int: bool = False): @@ -342,33 +291,17 @@ def parse_structured_literal(value, owner: str, field: str, expected: str): def parse_tuple_or_int(value, default=None): - """ - Parse a value that could be an int, tuple, or list string. - - Args: - value: The value to parse (could be "3", "(3, 3)", "[3]", "3,3", etc.) - default: Default value if parsing fails - - Returns: - int, tuple of ints, or list of ints (for list notation) - """ + """Parse a value that could be an int, tuple, or list string.""" if value is None: return default - if isinstance(value, (int, float)): return int(value) - if isinstance(value, (tuple, list)): return value - if isinstance(value, str): value = value.strip() - - # Handle empty string if not value: return default - - # Check if it's a list notation [...] if value.startswith('[') and value.endswith(']'): inner = value[1:-1].strip() if not inner: @@ -377,10 +310,7 @@ def parse_tuple_or_int(value, default=None): try: return [int(p) for p in parts] except ValueError: - # Try as strings if not ints return parts - - # Check if it's a tuple notation (...) if value.startswith('(') and value.endswith(')'): inner = value[1:-1].strip() if not inner: @@ -390,21 +320,16 @@ def parse_tuple_or_int(value, default=None): return tuple(int(p) for p in parts) except ValueError: return default - - # Try to parse as int try: return int(value) except ValueError: pass - - # Try to parse as comma-separated values if ',' in value: parts = [p.strip() for p in value.split(',') if p.strip()] try: return tuple(int(p) for p in parts) except ValueError: return default - return default @@ -420,14 +345,7 @@ def parse_bool(value, default=False): def parse_float(value, default=None): - """Parse a value as float. - - Raises ``ValueError`` on a non-empty, non-parseable string so a user - typing ``"0,5"`` (European decimal) or ``"abc"`` sees an actionable - error instead of the attribute silently falling back to the default. - Empty strings and ``None`` still yield the default (means "no user - input"), matching the old contract used by optional attributes. - """ + """Parse a value as float.""" if value is None: return default if isinstance(value, str): @@ -444,10 +362,6 @@ def parse_float(value, default=None): try: return float(value) except TypeError as exc: - # Non-string, non-numeric payload (list/dict/etc. from a broken - # frontend). Surface a clear error rather than silently returning - # the default — the mandatory-attribute check would otherwise - # fire with a misleading "missing" message. raise ValueError( f"{type(value).__name__} value is not a valid number " f"— expected a float" @@ -457,47 +371,25 @@ def parse_float(value, default=None): def parse_list_of_ints(value, default=None): - """ - Parse a value and ensure it returns a List[int]. - - The metamodel expects kernel_dim, stride_dim etc. to be List[int]. - - Args: - value: The value to parse (could be "[3]", "(3, 3)", "3", 3, [3], etc.) - default: Default value if parsing fails (should be a list like [3]) - - Returns: - List[int]: The parsed value as a list of integers - """ + """Parse a value and ensure it returns a List[int].""" if value is None: return default - - # If already a list, ensure all elements are ints if isinstance(value, list): try: return [int(v) for v in value] except (ValueError, TypeError): return default - - # If tuple, convert to list if isinstance(value, tuple): try: return [int(v) for v in value] except (ValueError, TypeError): return default - - # If single int, wrap in list if isinstance(value, (int, float)): return [int(value)] - if isinstance(value, str): value = value.strip() - - # Handle empty string if not value: return default - - # Check if it's a list notation [...] if value.startswith('[') and value.endswith(']'): inner = value[1:-1].strip() if not inner: @@ -507,8 +399,6 @@ def parse_list_of_ints(value, default=None): return [int(p) for p in parts] except ValueError: return default - - # Check if it's a tuple notation (...) if value.startswith('(') and value.endswith(')'): inner = value[1:-1].strip() if not inner: @@ -518,82 +408,128 @@ def parse_list_of_ints(value, default=None): return [int(p) for p in parts] except ValueError: return default - - # Try to parse as single int try: return [int(value)] except ValueError: pass - - # Try to parse as comma-separated values if ',' in value: parts = [p.strip() for p in value.split(',') if p.strip()] try: return [int(p) for p in parts] except ValueError: return default - return default def parse_dimension(value, default=None): - """ - Parse a dimension value and return the string format "1D", "2D", or "3D". - - The metamodel expects dimension as a string like "1D", "2D", "3D". - - Args: - value: The value to parse (could be "1D", "2D", "3D", "1d", "2d", "3d", 1, 2, 3, etc.) - default: Default value if parsing fails (None for mandatory attributes) - - Returns: - str: The dimension as a string ("1D", "2D", or "3D"), or None if invalid - """ + """Parse a dimension value and return the string format "1D", "2D", or "3D".""" if value is None: return default - - # If already an integer, convert to string format if isinstance(value, int): if value in (1, 2, 3): return f"{value}D" return default - if isinstance(value, str): value = value.strip().upper() - # Already in correct format if value in ('1D', '2D', '3D'): return value - # Try parsing as integer try: dim = int(value) if dim in (1, 2, 3): return f"{dim}D" except ValueError: pass - return default -def process_nn_diagram(json_data): +def _get_dataset_attr(node_or_element: dict, key: str, default=None, elements: dict = None): + """Read a dataset attribute. + + For a v4 node, reads from ``data.attributes`` (a dict). When the + legacy two-argument form (``element, elements``) is used, walks + ``element.attributes`` (a list of ids) and matches by ``attributeName``. + The two-arg form is retained only to keep targeted unit tests for + ``create_dataset(element, elements)`` working without rewriting the + fixtures. """ - Process NN Diagram JSON and return an NN model. - - This function: - 1. Identifies all NNContainers and creates separate NN objects for each - 2. Parses layers/TensorOps within each container - 3. Uses NNNext relationships to determine layer ordering within each container - 4. Handles NNReference elements by using add_sub_nn() to reference other NNs - 5. Returns the main NN model (with sub_nns for referenced containers) - - Args: - json_data: The JSON data from the frontend. Can be in two formats: - 1. Diagram format: {"title": "...", "model": {"elements": {...}}} - 2. Project format: {"project": {"diagrams": {"NNDiagram": {"model": {...}}}}} - - Returns: - NN: A B-UML NN model (main NN with sub_nns for referenced containers) + if elements is not None: + for attr_id in (node_or_element or {}).get('attributes', []) or []: + attr_el = elements.get(attr_id, {}) + if attr_el.get('attributeName') == key: + return attr_el.get('value', default) + return default + data = node_data(node_or_element) + attrs = data.get("attributes") or {} + if not isinstance(attrs, dict): + return default + return attrs.get(key, default) + + +def create_dataset(node_or_element: dict, elements: dict = None) -> Dataset: + """Create a Dataset (and optional Image). + + Production code passes a single v4 node. Legacy unit tests at + ``tests/utilities/web_modeling_editor/converters/nn/`` build minimal + v3 element + elements dicts and call ``create_dataset(element, + elements)``; the two-arg form is preserved for that purpose only. """ - # Handle both project format and diagram format + def _attr(key, default=None): + return _get_dataset_attr(node_or_element, key, default=default, elements=elements) + + name = _attr('name') + if not name: + raise ValueError("Dataset missing mandatory 'name' attribute") + path_data = _attr('path_data') + if not path_data: + raise ValueError("Dataset missing mandatory 'path_data' attribute") + + task_type = _attr('task_type') or None + if task_type is not None and task_type not in _ALLOWED_TASK_TYPES: + raise ValueError( + f"Dataset '{name}' has invalid task_type '{task_type}'. " + f"Allowed values: {', '.join(_ALLOWED_TASK_TYPES)}." + ) + input_format = _attr('input_format') or None + if input_format is not None and input_format not in _ALLOWED_INPUT_FORMATS: + raise ValueError( + f"Dataset '{name}' has invalid input_format '{input_format}'. " + f"Allowed values: {', '.join(_ALLOWED_INPUT_FORMATS)}." + ) + + image = None + shape_raw = _attr('shape') + normalize_raw = _attr('normalize') + shape_present = shape_raw is not None and shape_raw != '' + normalize_present = normalize_raw is not None and str(normalize_raw) != '' + if shape_present or normalize_present or input_format == 'images': + if shape_raw is None or shape_raw == '': + shape = [256, 256] + elif isinstance(shape_raw, (list, tuple)): + shape = list(shape_raw) + else: + try: + shape = ast.literal_eval(str(shape_raw)) + except (ValueError, SyntaxError) as exc: + raise ValueError( + f"Dataset '{name}' has malformed 'shape' attribute " + f"{shape_raw!r}: expected a list like [32, 32, 3]" + ) from exc + if not isinstance(shape, (list, tuple)): + raise ValueError( + f"Dataset '{name}' 'shape' attribute must be a list " + f"(got {type(shape).__name__})" + ) + shape = list(shape) + normalize = str(normalize_raw).lower() == 'true' if normalize_raw is not None else False + image = Image(shape=shape, normalize=normalize) + + return Dataset(name=name, path_data=path_data, task_type=task_type, + input_format=input_format, image=image) + + +def process_nn_diagram(json_data): + """Process a v4 NN Diagram JSON and return an NN model.""" + reject_unreadable_model(json_data, "NNDiagram") if 'project' in json_data: project_data = json_data.get('project', {}) diagrams = project_data.get('diagrams', {}) @@ -603,7 +539,6 @@ def process_nn_diagram(json_data): raise ValueError("Project contains no NNDiagram entries") nn_diagram_data = nn_diagram_data[0] elif isinstance(nn_diagram_data, dict): - # Legacy single-diagram shape: use as-is. pass else: raise ValueError( @@ -620,132 +555,110 @@ def process_nn_diagram(json_data): title = sanitize_name(title) - elements = model_data.get('elements', {}) - relationships = model_data.get('relationships', {}) + nodes = (model_data or {}).get('nodes') or [] + edges = (model_data or {}).get('edges') or [] + if not isinstance(nodes, list): + nodes = [] + if not isinstance(edges, list): + edges = [] # Networks (containers), layers, tensor ops and datasets take the id of the editor element they # are built from: the id a trace refers to them by. editor_ids = EditorIds() - # Step 1: Identify all NNContainers and their names + attributes - containers = {} # container_id -> (container_name, input_var, return_vars) - container_by_name = {} # container_name -> container_id - for elem_id, elem in elements.items(): - if elem.get('type') == 'NNContainer': - name = sanitize_name(elem.get('name', 'Neural_Network')) - input_var = elem.get('input_var') - return_vars = elem.get('return_vars') - containers[elem_id] = (name, input_var, return_vars) - container_by_name[name] = elem_id - - # Step 2: Identify NNReference elements and what they reference - nn_references = {} # element_id -> referenced_container_name - for elem_id, elem in elements.items(): - if elem.get('type') == 'NNReference': - ref_name = sanitize_name(elem.get('referencedNN', elem.get('name', ''))) - nn_references[elem_id] = ref_name - - # Step 3: Group layers/tensorops by their owner container - # Also track elements without owner (global Configuration) - layers_by_container = {cid: {} for cid in containers} # container_id -> {elem_id -> layer} + # Step 1: identify all NNContainer nodes, with their optional + # ``data.input_var`` / ``data.return_vars`` (the NN's forward signature). + containers = {} # container_id -> name + container_io = {} # container_id -> (input_var, return_vars_str) + for node in nodes: + if node.get('type') == 'NNContainer': + data = node_data(node) + containers[node.get('id')] = sanitize_name(data.get('name', 'Neural_Network')) + container_io[node.get('id')] = ( + _container_input_var(data.get('input_var')), + _container_return_vars(data.get('return_vars')), + ) + + # Step 2: identify NNReference nodes. + # ``referenceTarget`` is the referenced container's node id (what the + # editor stores) or, in older payloads and backend output, its name. + nn_references = {} # node_id -> referenced_container_name + for node in nodes: + if node.get('type') == 'NNReference': + data = node_data(node) + target = data.get('referenceTarget') or data.get('name', '') + if target in containers: + ref_name = containers[target] + else: + ref_name = sanitize_name(target) + nn_references[node.get('id')] = ref_name + + # Step 3: group layers / tensorops by parent container. + layers_by_container = {cid: {} for cid in containers} tensor_ops_by_container = {cid: {} for cid in containers} - refs_by_container = {cid: [] for cid in containers} # container_id -> [(elem_id, ref_name)] + refs_by_container = {cid: [] for cid in containers} configuration = None - for element_id, element in elements.items(): - element_type = element.get('type', '') - owner_id = element.get('owner') + layer_factories = { + 'Conv1DLayer': lambda n: _create_conv_layer(n, Conv1D, [1]), + 'Conv2DLayer': lambda n: _create_conv_layer(n, Conv2D, [1, 1]), + 'Conv3DLayer': lambda n: _create_conv_layer(n, Conv3D, [1, 1, 1]), + 'PoolingLayer': create_pooling_layer, + 'RNNLayer': lambda n: _create_rnn_like_layer(n, SimpleRNNLayer), + 'LSTMLayer': lambda n: _create_rnn_like_layer(n, LSTMLayer), + 'GRULayer': lambda n: _create_rnn_like_layer(n, GRULayer), + 'LinearLayer': create_linear_layer, + 'FlattenLayer': create_flatten_layer, + 'EmbeddingLayer': create_embedding_layer, + 'DropoutLayer': create_dropout_layer, + 'LayerNormalizationLayer': create_layer_norm_layer, + 'BatchNormalizationLayer': create_batch_norm_layer, + } - # Skip attribute elements - if 'Attribute' in element_type: - continue + for node in nodes: + node_id = node.get('id') + node_type = node.get('type', '') or '' + parent_id = node.get('parentId') - # Skip containers themselves - if element_type == 'NNContainer': + if node_type == 'NNContainer': continue - - # Handle NNReference - if element_type == 'NNReference': - if owner_id and owner_id in containers: - ref_name = nn_references.get(element_id) - refs_by_container[owner_id].append((element_id, ref_name)) + if node_type == 'NNReference': + if parent_id and parent_id in containers: + refs_by_container[parent_id].append((node_id, nn_references.get(node_id))) continue - - # Handle Configuration (global, no owner) - if element_type == 'Configuration': - configuration = create_configuration(element, elements) + if node_type == 'Configuration': + configuration = create_configuration(node) continue - # Create layer or tensor_op layer = None tensor_op = None - - if element_type == 'Conv1DLayer': - layer = create_conv1d_layer(element, elements) - elif element_type == 'Conv2DLayer': - layer = create_conv2d_layer(element, elements) - elif element_type == 'Conv3DLayer': - layer = create_conv3d_layer(element, elements) - elif element_type == 'PoolingLayer': - layer = create_pooling_layer(element, elements) - elif element_type == 'RNNLayer': - layer = create_rnn_layer(element, elements) - elif element_type == 'LSTMLayer': - layer = create_lstm_layer(element, elements) - elif element_type == 'GRULayer': - layer = create_gru_layer(element, elements) - elif element_type == 'LinearLayer': - layer = create_linear_layer(element, elements) - elif element_type == 'FlattenLayer': - layer = create_flatten_layer(element, elements) - elif element_type == 'EmbeddingLayer': - layer = create_embedding_layer(element, elements) - elif element_type == 'DropoutLayer': - layer = create_dropout_layer(element, elements) - elif element_type == 'LayerNormalizationLayer': - layer = create_layer_norm_layer(element, elements) - elif element_type == 'BatchNormalizationLayer': - layer = create_batch_norm_layer(element, elements) - elif element_type == 'TensorOp': - tensor_op = create_tensor_op(element, elements) - - # Add to appropriate container - if owner_id and owner_id in containers: - editor_ids.assign(layer or tensor_op, element_id) + factory = layer_factories.get(node_type) + if factory is not None: + layer = factory(node) + elif node_type == 'TensorOp': + tensor_op = create_tensor_op(node) + + if parent_id and parent_id in containers: + editor_ids.assign(layer or tensor_op, node_id) if layer: - layers_by_container[owner_id][element_id] = layer + layers_by_container[parent_id][node_id] = layer if tensor_op: - tensor_ops_by_container[owner_id][element_id] = tensor_op - - # Step 4: Build NNNext adjacency lists (per container) - outgoing_connections = {} # source_id -> [target_ids] - incoming_connections = {} # target_id -> [source_ids] - - for rel in relationships.values(): - rel_type = rel.get('type', '') - if rel_type == 'NNNext': - source_id = rel.get('source', {}).get('element') - target_id = rel.get('target', {}).get('element') - - if source_id and target_id: - if source_id not in outgoing_connections: - outgoing_connections[source_id] = [] - outgoing_connections[source_id].append(target_id) - - if target_id not in incoming_connections: - incoming_connections[target_id] = [] - incoming_connections[target_id].append(source_id) + tensor_ops_by_container[parent_id][node_id] = tensor_op - # Step 5: Create NN objects for each container - nn_by_name = {} # container_name -> NN object + # Step 4: NNNext adjacency. + outgoing_connections = {} + incoming_connections = {} + for edge in edges: + if edge.get('type') != 'NNNext': + continue + source_id = edge.get('source') + target_id = edge.get('target') + if source_id and target_id: + outgoing_connections.setdefault(source_id, []).append(target_id) + incoming_connections.setdefault(target_id, []).append(source_id) - # First, create NNs for containers that are referenced (no NNReference pointing to them) - # These are "standalone" sub-networks + # Step 5: create NNs per container in dependency order. referenced_names = set(nn_references.values()) - - # Build a reference graph (container_name -> set of referenced container_names) - # so we can order containers by dependency: referenced containers must be - # created before the containers that reference them, at any depth. - name_by_id = {cid: cdata[0] for cid, cdata in containers.items()} # cid -> name + name_by_id = dict(containers.items()) ref_graph = {cname: set() for cname in name_by_id.values()} for c_id, refs in refs_by_container.items(): c_name = name_by_id.get(c_id) @@ -755,9 +668,6 @@ def process_nn_diagram(json_data): if ref_name: ref_graph[c_name].add(ref_name) - # Depth-first post-order traversal: emits each container after all its - # transitive dependencies. GRAY coloring detects any cycle (direct or - # through intermediaries) and surfaces a clear error listing the chain. _white, _gray, _black = 0, 1, 2 color = {cname: _white for cname in name_by_id.values()} dep_order: list = [] @@ -773,7 +683,7 @@ def _visit_container(name: str, path: list) -> None: return color[name] = _gray for dep in sorted(ref_graph.get(name, ())): - if dep in color: # ignore references that don't resolve (handled later) + if dep in color: _visit_container(dep, path + [name]) color[name] = _black dep_order.append(name) @@ -785,27 +695,21 @@ def _visit_container(name: str, path: list) -> None: name_to_id = {cname: cid for cid, cname in name_by_id.items()} container_order = [(name_to_id[cname], cname) for cname in dep_order] - for container_id in [cid for cid, _ in container_order]: - container_name, input_var, return_vars = containers[container_id] - # Convert return_vars list to comma-separated string (metamodel expects string) - return_vars_str = ", ".join(return_vars) if return_vars else None - nn = NN(name=container_name, input_var=input_var, return_vars=return_vars_str) + nn_by_name = {} + for container_id, container_name in container_order: + input_var, return_vars = container_io.get(container_id, (None, None)) + nn = NN(name=container_name, input_var=input_var, return_vars=return_vars) editor_ids.assign(nn, container_id) nn_by_name[container_name] = nn - # Get all modules (layers + tensor_ops + refs) for this container container_layers = layers_by_container[container_id] container_tensor_ops = tensor_ops_by_container[container_id] container_refs = refs_by_container[container_id] - # Build set of all module IDs in this container (including refs) all_module_ids = (set(container_layers.keys()) | - set(container_tensor_ops.keys()) | - {ref_id for ref_id, _ in container_refs}) + set(container_tensor_ops.keys()) | + {ref_id for ref_id, _ in container_refs}) - # Topologically sort modules based on NNNext within this container. - # Tie-break by module name so two zero-in-degree starts produce a - # user-legible ordering instead of a UUID-alphabetic one. module_name_by_id = {} for mid, layer in container_layers.items(): module_name_by_id[mid] = getattr(layer, 'name', '') or '' @@ -813,13 +717,11 @@ def _visit_container(name: str, path: list) -> None: module_name_by_id[mid] = getattr(top, 'name', '') or '' for rid, rname in container_refs: module_name_by_id[rid] = rname or '' + ordered_modules = topological_sort( all_module_ids, outgoing_connections, name_by_id=module_name_by_id, ) - # At most one module may have no incoming NNNext edge (the entry point). - # Multiple zero-in-degree modules indicate disconnected pieces in the - # container, which would silently produce dead nodes in the generated code. roots = [mid for mid in all_module_ids if not incoming_connections.get(mid)] if len(roots) > 1: @@ -832,7 +734,6 @@ def _visit_container(name: str, path: list) -> None: f"after the entry point must be connected via NNNext." ) - # Add modules in order container_refs_dict = dict(container_refs) for module_id in ordered_modules: if module_id in container_layers: @@ -840,12 +741,11 @@ def _visit_container(name: str, path: list) -> None: elif module_id in container_tensor_ops: nn.add_tensor_op(container_tensor_ops[module_id]) elif module_id in container_refs_dict: - # This is an NNReference - add the referenced NN as sub_nn ref_name = container_refs_dict.get(module_id) if not ref_name: raise ValueError( f"NNReference in container '{container_name}' has no " - f"'referencedNN' field" + f"'referenceTarget' field" ) if ref_name not in nn_by_name: raise ValueError( @@ -854,9 +754,8 @@ def _visit_container(name: str, path: list) -> None: ) nn.add_sub_nn(nn_by_name[ref_name]) - # Step 6: Determine the main NN to return. - # The main NN is the one that is NOT referenced by any NNReference. - top_level = [cdata[0] for _, cdata in containers.items() if cdata[0] not in referenced_names] + # Step 6: pick the top-level NN. + top_level = [cname for _, cname in containers.items() if cname not in referenced_names] if len(top_level) > 1: raise ValueError( f"NN diagram contains {len(top_level)} top-level NNContainers " @@ -866,74 +765,70 @@ def _visit_container(name: str, path: list) -> None: if top_level: main_nn = nn_by_name.get(top_level[0]) elif nn_by_name: - # Every container is referenced (mutual reference) — still broken, but - # surface the issue clearly instead of silently picking one. raise ValueError( "NN diagram has no top-level NNContainer: every container is " "referenced by an NNReference. Remove one of the references." ) else: - # No containers at all — produce an empty NN so empty diagrams still export. main_nn = NN(name=title) - # Add configuration to the main NN if configuration: main_nn.add_configuration(configuration) - # Step 7: Parse datasets (TrainingDataset / TestDataset) and attach to main NN. - # The metamodel only holds one of each, so collect first and raise on duplicates - # rather than letting the last one silently overwrite the previous. - train_datasets = [] - test_datasets = [] - for element_id, element in elements.items(): - element_type = element.get('type', '') - if element_type == 'TrainingDataset': - train_datasets.append(element) - elif element_type == 'TestDataset': - test_datasets.append(element) - - if len(train_datasets) > 1: + train_nodes = [n for n in nodes if n.get('type') == 'TrainingDataset'] + test_nodes = [n for n in nodes if n.get('type') == 'TestDataset'] + + if len(train_nodes) > 1: raise ValueError( - f"NN diagram contains {len(train_datasets)} TrainingDataset elements; " + f"NN diagram contains {len(train_nodes)} TrainingDataset elements; " f"only one is supported per NN model" ) - if len(test_datasets) > 1: + if len(test_nodes) > 1: raise ValueError( - f"NN diagram contains {len(test_datasets)} TestDataset elements; " + f"NN diagram contains {len(test_nodes)} TestDataset elements; " f"only one is supported per NN model" ) - for datasets, add in ((train_datasets, main_nn.add_train_data), (test_datasets, main_nn.add_test_data)): - if datasets: - dataset = create_dataset(datasets[0], elements) - editor_ids.assign(dataset, datasets[0].get('id')) + for nodes_of_kind, add in ((train_nodes, main_nn.add_train_data), (test_nodes, main_nn.add_test_data)): + if nodes_of_kind: + dataset = create_dataset(nodes_of_kind[0]) + editor_ids.assign(dataset, nodes_of_kind[0].get('id')) add(dataset) - # Run model-level validation here so any caller (validation endpoint, - # code generation, BUML export) surfaces errors before producing output. main_nn.validate(raise_exception=True) - return main_nn -def topological_sort(module_ids, outgoing_connections, name_by_id=None): - """ - Topologically sort modules based on their NNNext connections. - First layer = the one with no incoming connections from other modules. - - Args: - module_ids: Set of module IDs - outgoing_connections: Dict mapping source_id to list of target_ids - name_by_id: Optional dict module_id -> display name. When supplied, - ties are broken by ``(name, id)`` instead of by raw UUID so the - resulting order is user-legible. Still deterministic either way. - - Returns: - List of module IDs in topological order +def _container_input_var(value): + """``NNContainer.data.input_var`` -> the ``NN.input_var`` string (or None).""" + if value is None: + return None + text = str(value).strip() + return text or None + + +def _container_return_vars(value): + """``NNContainer.data.return_vars`` -> the comma-separated ``NN.return_vars``. + + The BUML->JSON converter emits a list (``["rep", "recon"]``); the editor + may also hand over the comma-separated string the user typed. Both are + accepted; an empty value yields None. """ - # Kahn's algorithm - in_degree = {mid: 0 for mid in module_ids} + if value is None: + return None + if isinstance(value, (list, tuple)): + parts = [str(v).strip() for v in value] + else: + text = str(value).strip() + if text.startswith('[') and text.endswith(']'): + text = text[1:-1] + parts = [p.strip().strip("'\"") for p in text.split(',')] + parts = [p for p in parts if p] + return ", ".join(parts) if parts else None + - # Calculate in-degrees (only from connections within module_ids) +def topological_sort(module_ids, outgoing_connections, name_by_id=None): + """Topologically sort modules based on their NNNext connections.""" + in_degree = {mid: 0 for mid in module_ids} for source_id, targets in outgoing_connections.items(): if source_id in module_ids: for target_id in targets: @@ -941,30 +836,22 @@ def topological_sort(module_ids, outgoing_connections, name_by_id=None): in_degree[target_id] += 1 def _sort_key(mid): - # (display_name, id) — falls back to id if no name is known. if name_by_id is None: return mid return (name_by_id.get(mid, ''), mid) - # Find all nodes with in-degree 0 (first layers - no incoming from other modules) - # Sort for deterministic ordering when multiple nodes share in-degree 0 queue = sorted( (mid for mid, deg in in_degree.items() if deg == 0), key=_sort_key, ) result = [] - while queue: current = queue.pop(0) result.append(current) - - # Decrease in-degree for all neighbors for target_id in outgoing_connections.get(current, []): if target_id in in_degree: in_degree[target_id] -= 1 if in_degree[target_id] == 0: - # bisect.insort needs a comparable key; when we have - # names, do a linear insert over the (name, id) key. if name_by_id is None: bisect.insort(queue, target_id) else: @@ -978,37 +865,31 @@ def _sort_key(mid): hi = mid queue.insert(lo, target_id) - # Any nodes still missing from the result have a non-zero in-degree, - # which means they participate in a cycle (disconnected components - # always have at least one zero-in-degree node). That is a malformed - # network, so surface it instead of silently accepting it. remaining = [mid for mid in module_ids if mid not in result] if remaining: raise ValueError( "NNNext relationships form a cycle involving " f"{len(remaining)} module(s); cannot determine layer order" ) - return result +# --------------------------------------------------------------------------- # Layer creation functions +# --------------------------------------------------------------------------- -def _create_conv_layer(element, elements, conv_class, default_stride): - """Create a convolutional layer (Conv1D, Conv2D, or Conv3D) from element data.""" +def _create_conv_layer(node, conv_class, default_stride): + """Create a convolutional layer (Conv1D, Conv2D, or Conv3D) from v4 data.""" class_name = conv_class.__name__ - name = get_element_attribute(element, 'NameAttribute', elements) + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError(f"{class_name} layer missing mandatory 'name' attribute") - kernel_dim_raw = get_element_attribute(element, 'KernelDimAttribute', elements) + kernel_dim_raw = get_element_attribute(node, 'KernelDimAttribute') kernel_dim = parse_list_of_ints(kernel_dim_raw) if kernel_dim is None: raise ValueError(f"{class_name} layer '{name}' missing mandatory 'kernel_dim' attribute") - # Validate kernel_dim length before passing to the constructor — otherwise - # the metamodel setter raises ("kernel_dim list must have exactly N elements") - # without naming the layer, which surfaces as a cryptic 400 to the user. expected_dim = _CONV_EXPECTED_DIMS.get(class_name) if expected_dim is not None and len(kernel_dim) != expected_dim: raise ValueError( @@ -1016,7 +897,7 @@ def _create_conv_layer(element, elements, conv_class, default_stride): f"element(s), expected {expected_dim}." ) - out_channels_raw = get_element_attribute(element, 'OutChannelsAttribute', elements) + out_channels_raw = get_element_attribute(node, 'OutChannelsAttribute') out_channels = parse_tuple_or_int(out_channels_raw) if out_channels is None: raise ValueError(f"{class_name} layer '{name}' missing mandatory 'out_channels' attribute") @@ -1027,8 +908,7 @@ def _create_conv_layer(element, elements, conv_class, default_stride): out_channels=out_channels, ) - # Optional attributes - stride = get_element_attribute(element, 'StrideDimAttribute', elements) + stride = get_element_attribute(node, 'StrideDimAttribute') if stride is not None: stride_dim_parsed = parse_list_of_ints(stride, default_stride) if expected_dim is not None and stride_dim_parsed is not None \ @@ -1039,18 +919,16 @@ def _create_conv_layer(element, elements, conv_class, default_stride): ) layer.stride_dim = stride_dim_parsed - in_channels = get_element_attribute(element, 'InChannelsAttribute', elements) + in_channels = get_element_attribute(node, 'InChannelsAttribute') if in_channels is not None: layer.in_channels = parse_tuple_or_int(in_channels) - padding = get_element_attribute(element, 'PaddingAmountAttribute', elements) + padding = get_element_attribute(node, 'PaddingAmountAttribute') if padding is not None: layer.padding_amount = parse_tuple_or_int(padding, 0) - # Mark explicit so the converter/builder can distinguish a user-set - # 0 (valid, must round-trip) from the metamodel default of 0. mark_explicit(layer, 'padding_amount') - padding_type = get_element_attribute(element, 'PaddingTypeAttribute', elements) + padding_type = get_element_attribute(node, 'PaddingTypeAttribute') if padding_type: if padding_type not in _ALLOWED_PADDING_TYPES: raise ValueError( @@ -1059,37 +937,33 @@ def _create_conv_layer(element, elements, conv_class, default_stride): f"{', '.join(_ALLOWED_PADDING_TYPES)}." ) layer.padding_type = padding_type - # Track explicit so 'valid' (= metamodel default) still round-trips - # when the user actually picked it. mark_explicit(layer, 'padding_type') - actv_func = get_element_attribute(element, 'ActvFuncAttribute', elements) + actv_func = get_element_attribute(node, 'ActvFuncAttribute') if actv_func: layer.actv_func = actv_func - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - permute_in = get_element_attribute(element, 'PermuteInAttribute', elements) + permute_in = get_element_attribute(node, 'PermuteInAttribute') if permute_in is not None and str(permute_in).strip() != '': - # permute_in/out are booleans in the metamodel, not integer lists — - # they toggle dimension permutation in the PyTorch generator. layer.permute_in = parse_bool(permute_in) mark_explicit(layer, 'permute_in') - permute_out = get_element_attribute(element, 'PermuteOutAttribute', elements) + permute_out = get_element_attribute(node, 'PermuteOutAttribute') if permute_out is not None and str(permute_out).strip() != '': layer.permute_out = parse_bool(permute_out) mark_explicit(layer, 'permute_out') # New attributes added for Conv layers - dilation = get_element_attribute(element, 'DilationAttribute', elements) + dilation = get_element_attribute(node, 'DilationAttribute') if dilation is not None: dilation_parsed = parse_list_of_ints(dilation) if dilation_parsed is not None: @@ -1102,27 +976,27 @@ def _create_conv_layer(element, elements, conv_class, default_stride): layer.dilation = dilation_parsed mark_explicit(layer, 'dilation') - groups = get_element_attribute(element, 'GroupsAttribute', elements) + groups = get_element_attribute(node, 'GroupsAttribute') if groups is not None: layer.groups = parse_tuple_or_int(groups) mark_explicit(layer, 'groups') - bias = get_element_attribute(element, 'BiasAttribute', elements) + bias = get_element_attribute(node, 'BiasAttribute') if bias is not None: layer.bias = parse_bool(bias) mark_explicit(layer, 'bias') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') @@ -1130,28 +1004,13 @@ def _create_conv_layer(element, elements, conv_class, default_stride): return layer -def create_conv1d_layer(element, elements): - """Create a Conv1D layer from element data.""" - return _create_conv_layer(element, elements, Conv1D, [1]) - - -def create_conv2d_layer(element, elements): - """Create a Conv2D layer from element data.""" - return _create_conv_layer(element, elements, Conv2D, [1, 1]) - - -def create_conv3d_layer(element, elements): - """Create a Conv3D layer from element data.""" - return _create_conv_layer(element, elements, Conv3D, [1, 1, 1]) - - -def create_pooling_layer(element, elements): - """Create a PoolingLayer from element data.""" - name = get_element_attribute(element, 'NameAttribute', elements) +def create_pooling_layer(node): + """Create a PoolingLayer from a v4 node.""" + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError("PoolingLayer missing mandatory 'name' attribute") - pooling_type = get_element_attribute(element, 'PoolingTypeAttribute', elements) + pooling_type = get_element_attribute(node, 'PoolingTypeAttribute') if not pooling_type: raise ValueError(f"PoolingLayer '{name}' missing mandatory 'pooling_type' attribute") if pooling_type not in _ALLOWED_POOLING_TYPES: @@ -1160,17 +1019,14 @@ def create_pooling_layer(element, elements): f"Allowed values: {', '.join(_ALLOWED_POOLING_TYPES)}." ) - dimension_raw = get_element_attribute(element, 'DimensionAttribute', elements) + dimension_raw = get_element_attribute(node, 'DimensionAttribute') dimension = parse_dimension(dimension_raw) if dimension is None: raise ValueError(f"PoolingLayer '{name}' missing mandatory 'dimension' attribute") - # kernel_dim is required for non-adaptive/global pooling - provide default based on dimension - kernel_dim_raw = get_element_attribute(element, 'KernelDimAttribute', elements) + kernel_dim_raw = get_element_attribute(node, 'KernelDimAttribute') kernel_dim = parse_list_of_ints(kernel_dim_raw) - - # If kernel_dim not provided and it's not adaptive/global pooling, use default - if kernel_dim is None and not pooling_type.endswith(("adaptive", "global")): + if kernel_dim is None and not (pooling_type.startswith("adaptive") or pooling_type.startswith("global")): if dimension == "1D": kernel_dim = [2] elif dimension == "2D": @@ -1178,7 +1034,7 @@ def create_pooling_layer(element, elements): elif dimension == "3D": kernel_dim = [2, 2, 2] - stride_raw = get_element_attribute(element, 'StrideDimAttribute', elements) + stride_raw = get_element_attribute(node, 'StrideDimAttribute') stride_dim = parse_list_of_ints(stride_raw) layer = PoolingLayer( @@ -1189,12 +1045,12 @@ def create_pooling_layer(element, elements): stride_dim=stride_dim, ) - padding = get_element_attribute(element, 'PaddingAmountAttribute', elements) + padding = get_element_attribute(node, 'PaddingAmountAttribute') if padding is not None: layer.padding_amount = parse_tuple_or_int(padding, 0) mark_explicit(layer, 'padding_amount') - padding_type = get_element_attribute(element, 'PaddingTypeAttribute', elements) + padding_type = get_element_attribute(node, 'PaddingTypeAttribute') if padding_type: if padding_type not in _ALLOWED_PADDING_TYPES: raise ValueError( @@ -1205,46 +1061,45 @@ def create_pooling_layer(element, elements): layer.padding_type = padding_type mark_explicit(layer, 'padding_type') - output_dim = get_element_attribute(element, 'OutputDimAttribute', elements) + output_dim = get_element_attribute(node, 'OutputDimAttribute') if output_dim is not None: layer.output_dim = parse_list_of_ints(output_dim) mark_explicit(layer, 'output_dim') - actv_func = get_element_attribute(element, 'ActvFuncAttribute', elements) + actv_func = get_element_attribute(node, 'ActvFuncAttribute') if actv_func: layer.actv_func = actv_func - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - permute_in = get_element_attribute(element, 'PermuteInAttribute', elements) + permute_in = get_element_attribute(node, 'PermuteInAttribute') if permute_in is not None and str(permute_in).strip() != '': - # permute_in/out are booleans in the metamodel, not integer lists. layer.permute_in = parse_bool(permute_in) mark_explicit(layer, 'permute_in') - permute_out = get_element_attribute(element, 'PermuteOutAttribute', elements) + permute_out = get_element_attribute(node, 'PermuteOutAttribute') if permute_out is not None and str(permute_out).strip() != '': layer.permute_out = parse_bool(permute_out) mark_explicit(layer, 'permute_out') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') @@ -1252,14 +1107,14 @@ def create_pooling_layer(element, elements): return layer -def _create_rnn_like_layer(element, elements, rnn_class): - """Create an RNN-like layer (SimpleRNNLayer, LSTMLayer, or GRULayer) from element data.""" +def _create_rnn_like_layer(node, rnn_class): + """Create an RNN-like layer (SimpleRNNLayer, LSTMLayer, or GRULayer).""" class_name = rnn_class.__name__ - name = get_element_attribute(element, 'NameAttribute', elements) + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError(f"{class_name} missing mandatory 'name' attribute") - hidden_size_raw = get_element_attribute(element, 'HiddenSizeAttribute', elements) + hidden_size_raw = get_element_attribute(node, 'HiddenSizeAttribute') hidden_size = parse_tuple_or_int(hidden_size_raw) if hidden_size is None: raise ValueError(f"{class_name} '{name}' missing mandatory 'hidden_size' attribute") @@ -1269,8 +1124,7 @@ def _create_rnn_like_layer(element, elements, rnn_class): hidden_size=hidden_size, ) - # Optional attributes - return_type = get_element_attribute(element, 'ReturnTypeAttribute', elements) + return_type = get_element_attribute(node, 'ReturnTypeAttribute') if return_type: if return_type not in _ALLOWED_RETURN_TYPES: raise ValueError( @@ -1280,91 +1134,91 @@ def _create_rnn_like_layer(element, elements, rnn_class): ) layer.return_type = return_type - input_size = get_element_attribute(element, 'InputSizeAttribute', elements) + input_size = get_element_attribute(node, 'InputSizeAttribute') if input_size is not None: layer.input_size = parse_tuple_or_int(input_size) - bidirectional = get_element_attribute(element, 'BidirectionalAttribute', elements) + bidirectional = get_element_attribute(node, 'BidirectionalAttribute') if bidirectional is not None: layer.bidirectional = parse_bool(bidirectional) mark_explicit(layer, 'bidirectional') - dropout = get_element_attribute(element, 'DropoutAttribute', elements) + dropout = get_element_attribute(node, 'DropoutAttribute') if dropout is not None: layer.dropout = parse_float(dropout, 0.0) mark_explicit(layer, 'dropout') - batch_first = get_element_attribute(element, 'BatchFirstAttribute', elements) + batch_first = get_element_attribute(node, 'BatchFirstAttribute') if batch_first is not None: layer.batch_first = parse_bool(batch_first) mark_explicit(layer, 'batch_first') - actv_func = get_element_attribute(element, 'ActvFuncAttribute', elements) + actv_func = get_element_attribute(node, 'ActvFuncAttribute') if actv_func: layer.actv_func = actv_func - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - bias = get_element_attribute(element, 'BiasAttribute', elements) + bias = get_element_attribute(node, 'BiasAttribute') if bias is not None: layer.bias = parse_bool(bias) mark_explicit(layer, 'bias') - hx_source = get_element_attribute(element, 'HxSourceAttribute', elements) + hx_source = get_element_attribute(node, 'HxSourceAttribute') if hx_source is not None and str(hx_source).strip() != '': layer.hx_source = hx_source mark_explicit(layer, 'hx_source') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') - hidden_state_var = get_element_attribute(element, 'HiddenStateVarAttribute', elements) + hidden_state_var = get_element_attribute(node, 'HiddenStateVarAttribute') if hidden_state_var is not None and str(hidden_state_var).strip() != '': layer.hidden_state_var = hidden_state_var mark_explicit(layer, 'hidden_state_var') - hidden_unused = get_element_attribute(element, 'HiddenUnusedAttribute', elements) + hidden_unused = get_element_attribute(node, 'HiddenUnusedAttribute') if hidden_unused is not None: layer.hidden_unused = parse_bool(hidden_unused) mark_explicit(layer, 'hidden_unused') - hidden_subscript_source = get_element_attribute(element, 'HiddenSubscriptSourceAttribute', elements) + hidden_subscript_source = get_element_attribute(node, 'HiddenSubscriptSourceAttribute') if hidden_subscript_source is not None and str(hidden_subscript_source).strip() != '': layer.hidden_subscript_source = hidden_subscript_source mark_explicit(layer, 'hidden_subscript_source') - hidden_subscript_target = get_element_attribute(element, 'HiddenSubscriptTargetAttribute', elements) + hidden_subscript_target = get_element_attribute(node, 'HiddenSubscriptTargetAttribute') if hidden_subscript_target is not None and str(hidden_subscript_target).strip() != '': layer.hidden_subscript_target = hidden_subscript_target mark_explicit(layer, 'hidden_subscript_target') # LSTM-specific attributes if rnn_class.__name__ == 'LSTMLayer': - cell_state_var = get_element_attribute(element, 'CellStateVarAttribute', elements) + cell_state_var = get_element_attribute(node, 'CellStateVarAttribute') if cell_state_var is not None and str(cell_state_var).strip() != '': layer.cell_state_var = cell_state_var mark_explicit(layer, 'cell_state_var') - cell_unused = get_element_attribute(element, 'CellUnusedAttribute', elements) + cell_unused = get_element_attribute(node, 'CellUnusedAttribute') if cell_unused is not None: layer.cell_unused = parse_bool(cell_unused) mark_explicit(layer, 'cell_unused') @@ -1372,28 +1226,13 @@ def _create_rnn_like_layer(element, elements, rnn_class): return layer -def create_rnn_layer(element, elements): - """Create a SimpleRNNLayer from element data.""" - return _create_rnn_like_layer(element, elements, SimpleRNNLayer) - - -def create_lstm_layer(element, elements): - """Create an LSTMLayer from element data.""" - return _create_rnn_like_layer(element, elements, LSTMLayer) - - -def create_gru_layer(element, elements): - """Create a GRULayer from element data.""" - return _create_rnn_like_layer(element, elements, GRULayer) - - -def create_linear_layer(element, elements): - """Create a LinearLayer from element data.""" - name = get_element_attribute(element, 'NameAttribute', elements) +def create_linear_layer(node): + """Create a LinearLayer from a v4 node.""" + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError("LinearLayer missing mandatory 'name' attribute") - out_features_raw = get_element_attribute(element, 'OutFeaturesAttribute', elements) + out_features_raw = get_element_attribute(node, 'OutFeaturesAttribute') out_features = parse_tuple_or_int(out_features_raw) if out_features is None: raise ValueError(f"LinearLayer '{name}' missing mandatory 'out_features' attribute") @@ -1403,40 +1242,39 @@ def create_linear_layer(element, elements): out_features=out_features, ) - # Optional attributes - in_features = get_element_attribute(element, 'InFeaturesAttribute', elements) + in_features = get_element_attribute(node, 'InFeaturesAttribute') if in_features is not None: layer.in_features = parse_tuple_or_int(in_features) - actv_func = get_element_attribute(element, 'ActvFuncAttribute', elements) + actv_func = get_element_attribute(node, 'ActvFuncAttribute') if actv_func: layer.actv_func = actv_func - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - bias = get_element_attribute(element, 'BiasAttribute', elements) + bias = get_element_attribute(node, 'BiasAttribute') if bias is not None: layer.bias = parse_bool(bias) mark_explicit(layer, 'bias') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') @@ -1444,53 +1282,48 @@ def create_linear_layer(element, elements): return layer -def create_flatten_layer(element, elements): - """Create a FlattenLayer from element data.""" - name = get_element_attribute(element, 'NameAttribute', elements) +def create_flatten_layer(node): + """Create a FlattenLayer from a v4 node.""" + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError("FlattenLayer missing mandatory 'name' attribute") layer = FlattenLayer(name=sanitize_name(name)) - # Optional attributes - start_dim = get_element_attribute(element, 'StartDimAttribute', elements) + start_dim = get_element_attribute(node, 'StartDimAttribute') if start_dim is not None: layer.start_dim = parse_tuple_or_int(start_dim) - # Mark explicit so the converter emits start_dim even when the user - # set it to the metamodel default (1). Without this, a user who - # intentionally typed "1" into the editor sees the attribute vanish - # from the exported JSON. mark_explicit(layer, 'start_dim') - end_dim = get_element_attribute(element, 'EndDimAttribute', elements) + end_dim = get_element_attribute(node, 'EndDimAttribute') if end_dim is not None: layer.end_dim = parse_tuple_or_int(end_dim) mark_explicit(layer, 'end_dim') - actv_func = get_element_attribute(element, 'ActvFuncAttribute', elements) + actv_func = get_element_attribute(node, 'ActvFuncAttribute') if actv_func: layer.actv_func = actv_func - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') @@ -1498,18 +1331,18 @@ def create_flatten_layer(element, elements): return layer -def create_embedding_layer(element, elements): - """Create an EmbeddingLayer from element data.""" - name = get_element_attribute(element, 'NameAttribute', elements) +def create_embedding_layer(node): + """Create an EmbeddingLayer from a v4 node.""" + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError("EmbeddingLayer missing mandatory 'name' attribute") - num_embeddings_raw = get_element_attribute(element, 'NumEmbeddingsAttribute', elements) + num_embeddings_raw = get_element_attribute(node, 'NumEmbeddingsAttribute') num_embeddings = parse_tuple_or_int(num_embeddings_raw) if num_embeddings is None: raise ValueError(f"EmbeddingLayer '{name}' missing mandatory 'num_embeddings' attribute") - embedding_dim_raw = get_element_attribute(element, 'EmbeddingDimAttribute', elements) + embedding_dim_raw = get_element_attribute(node, 'EmbeddingDimAttribute') embedding_dim = parse_tuple_or_int(embedding_dim_raw) if embedding_dim is None: raise ValueError(f"EmbeddingLayer '{name}' missing mandatory 'embedding_dim' attribute") @@ -1520,46 +1353,45 @@ def create_embedding_layer(element, elements): embedding_dim=embedding_dim, ) - # Optional attributes - actv_func = get_element_attribute(element, 'ActvFuncAttribute', elements) + actv_func = get_element_attribute(node, 'ActvFuncAttribute') if actv_func: layer.actv_func = actv_func - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - padding_idx = get_element_attribute(element, 'PaddingIdxAttribute', elements) + padding_idx = get_element_attribute(node, 'PaddingIdxAttribute') if padding_idx is not None and str(padding_idx).strip() != '': layer.padding_idx = parse_tuple_or_int(padding_idx) mark_explicit(layer, 'padding_idx') - permute_in = get_element_attribute(element, 'PermuteInAttribute', elements) + permute_in = get_element_attribute(node, 'PermuteInAttribute') if permute_in is not None: layer.permute_in = parse_bool(permute_in) mark_explicit(layer, 'permute_in') - permute_out = get_element_attribute(element, 'PermuteOutAttribute', elements) + permute_out = get_element_attribute(node, 'PermuteOutAttribute') if permute_out is not None: layer.permute_out = parse_bool(permute_out) mark_explicit(layer, 'permute_out') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') @@ -1567,13 +1399,13 @@ def create_embedding_layer(element, elements): return layer -def create_dropout_layer(element, elements): - """Create a DropoutLayer from element data.""" - name = get_element_attribute(element, 'NameAttribute', elements) +def create_dropout_layer(node): + """Create a DropoutLayer from a v4 node.""" + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError("DropoutLayer missing mandatory 'name' attribute") - rate_raw = get_element_attribute(element, 'RateAttribute', elements) + rate_raw = get_element_attribute(node, 'RateAttribute') rate = parse_float(rate_raw) if rate is None: raise ValueError(f"DropoutLayer '{name}' missing mandatory 'rate' attribute") @@ -1583,42 +1415,41 @@ def create_dropout_layer(element, elements): rate=rate, ) - # Optional attributes - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - dimension = get_element_attribute(element, 'DimensionAttribute', elements) + dimension = get_element_attribute(node, 'DimensionAttribute') if dimension is not None and str(dimension).strip() != '': layer.dimension = dimension mark_explicit(layer, 'dimension') - permute_in = get_element_attribute(element, 'PermuteInAttribute', elements) + permute_in = get_element_attribute(node, 'PermuteInAttribute') if permute_in is not None: layer.permute_in = parse_bool(permute_in) mark_explicit(layer, 'permute_in') - permute_out = get_element_attribute(element, 'PermuteOutAttribute', elements) + permute_out = get_element_attribute(node, 'PermuteOutAttribute') if permute_out is not None: layer.permute_out = parse_bool(permute_out) mark_explicit(layer, 'permute_out') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') @@ -1626,13 +1457,13 @@ def create_dropout_layer(element, elements): return layer -def create_layer_norm_layer(element, elements): - """Create a LayerNormLayer from element data.""" - name = get_element_attribute(element, 'NameAttribute', elements) +def create_layer_norm_layer(node): + """Create a LayerNormLayer from a v4 node.""" + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError("LayerNormLayer missing mandatory 'name' attribute") - normalized_shape_raw = get_element_attribute(element, 'NormalizedShapeAttribute', elements) + normalized_shape_raw = get_element_attribute(node, 'NormalizedShapeAttribute') normalized_shape = parse_tuple_or_int(normalized_shape_raw) if normalized_shape is None: raise ValueError(f"LayerNormLayer '{name}' missing mandatory 'normalized_shape' attribute") @@ -1642,41 +1473,40 @@ def create_layer_norm_layer(element, elements): normalized_shape=normalized_shape, ) - # Optional attributes - actv_func = get_element_attribute(element, 'ActvFuncAttribute', elements) + actv_func = get_element_attribute(node, 'ActvFuncAttribute') if actv_func: layer.actv_func = actv_func - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - eps = get_element_attribute(element, 'EpsAttribute', elements) + eps = get_element_attribute(node, 'EpsAttribute') if eps is not None and str(eps).strip() != '': layer.eps = float(eps) mark_explicit(layer, 'eps') - affine = get_element_attribute(element, 'AffineAttribute', elements) + affine = get_element_attribute(node, 'AffineAttribute') if affine is not None: layer.affine = parse_bool(affine) mark_explicit(layer, 'affine') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') @@ -1684,18 +1514,18 @@ def create_layer_norm_layer(element, elements): return layer -def create_batch_norm_layer(element, elements): - """Create a BatchNormLayer from element data.""" - name = get_element_attribute(element, 'NameAttribute', elements) +def create_batch_norm_layer(node): + """Create a BatchNormLayer from a v4 node.""" + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError("BatchNormLayer missing mandatory 'name' attribute") - num_features_raw = get_element_attribute(element, 'NumFeaturesAttribute', elements) + num_features_raw = get_element_attribute(node, 'NumFeaturesAttribute') num_features = parse_tuple_or_int(num_features_raw) if num_features is None: raise ValueError(f"BatchNormLayer '{name}' missing mandatory 'num_features' attribute") - dimension_raw = get_element_attribute(element, 'DimensionAttribute', elements) + dimension_raw = get_element_attribute(node, 'DimensionAttribute') dimension = parse_dimension(dimension_raw) if dimension is None: raise ValueError(f"BatchNormLayer '{name}' missing mandatory 'dimension' attribute") @@ -1706,63 +1536,62 @@ def create_batch_norm_layer(element, elements): dimension=dimension, ) - # Optional attributes - actv_func = get_element_attribute(element, 'ActvFuncAttribute', elements) + actv_func = get_element_attribute(node, 'ActvFuncAttribute') if actv_func: layer.actv_func = actv_func - name_module_input = get_element_attribute(element, 'NameModuleInputAttribute', elements) + name_module_input = get_element_attribute(node, 'NameModuleInputAttribute') if name_module_input: layer.name_module_input = name_module_input - input_reused = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused = get_element_attribute(node, 'InputReusedAttribute') if input_reused is not None: layer.input_reused = parse_bool(input_reused) mark_explicit(layer, 'input_reused') - eps = get_element_attribute(element, 'EpsAttribute', elements) + eps = get_element_attribute(node, 'EpsAttribute') if eps is not None and str(eps).strip() != '': layer.eps = float(eps) mark_explicit(layer, 'eps') - momentum = get_element_attribute(element, 'MomentumAttribute', elements) + momentum = get_element_attribute(node, 'MomentumAttribute') if momentum is not None and str(momentum).strip() != '': layer.momentum = float(momentum) mark_explicit(layer, 'momentum') - affine = get_element_attribute(element, 'AffineAttribute', elements) + affine = get_element_attribute(node, 'AffineAttribute') if affine is not None: layer.affine = parse_bool(affine) mark_explicit(layer, 'affine') - track_running_stats = get_element_attribute(element, 'TrackRunningStatsAttribute', elements) + track_running_stats = get_element_attribute(node, 'TrackRunningStatsAttribute') if track_running_stats is not None: layer.track_running_stats = parse_bool(track_running_stats) mark_explicit(layer, 'track_running_stats') # BatchNorm takes permute_in / permute_out as real constructor parameters # (LayerNorm hard-codes them to False), so both directions must carry them. - permute_in = get_element_attribute(element, 'PermuteInAttribute', elements) + permute_in = get_element_attribute(node, 'PermuteInAttribute') if permute_in is not None and str(permute_in).strip() != '': layer.permute_in = parse_bool(permute_in) mark_explicit(layer, 'permute_in') - permute_out = get_element_attribute(element, 'PermuteOutAttribute', elements) + permute_out = get_element_attribute(node, 'PermuteOutAttribute') if permute_out is not None and str(permute_out).strip() != '': layer.permute_out = parse_bool(permute_out) mark_explicit(layer, 'permute_out') - is_layer_call = get_element_attribute(element, 'IsLayerCallAttribute', elements) + is_layer_call = get_element_attribute(node, 'IsLayerCallAttribute') if is_layer_call is not None: layer.is_layer_call = parse_bool(is_layer_call) mark_explicit(layer, 'is_layer_call') - input_var = get_element_attribute(element, 'InputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') if input_var is not None and str(input_var).strip() != '': layer.input_var = input_var mark_explicit(layer, 'input_var') - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + output_var = get_element_attribute(node, 'OutputVarAttribute') if output_var is not None and str(output_var).strip() != '': layer.output_var = output_var mark_explicit(layer, 'output_var') @@ -1770,13 +1599,13 @@ def create_batch_norm_layer(element, elements): return layer -def create_tensor_op(element, elements): - """Create a TensorOp from element data.""" - name = get_element_attribute(element, 'NameAttribute', elements) +def create_tensor_op(node): + """Create a TensorOp from a v4 node.""" + name = get_element_attribute(node, 'NameAttribute') if not name: raise ValueError("TensorOp missing mandatory 'name' attribute") - tns_type = get_element_attribute(element, 'TnsTypeAttribute', elements) + tns_type = get_element_attribute(node, 'TnsTypeAttribute') if not tns_type: raise ValueError(f"TensorOp '{name}' missing mandatory 'tns_type' attribute") if tns_type not in ALLOWED_TENSOR_OP_TYPES: @@ -1785,13 +1614,11 @@ def create_tensor_op(element, elements): f"Allowed values: {', '.join(ALLOWED_TENSOR_OP_TYPES)}." ) - # Parse all attributes first before creating TensorOp - # (because TensorOp validates required attributes in tns_type setter) - concatenate_dim = get_element_attribute(element, 'ConcatenateDimAttribute', elements) + concatenate_dim = get_element_attribute(node, 'ConcatenateDimAttribute') if concatenate_dim is not None: concatenate_dim = parse_tuple_or_int(concatenate_dim) - layers_of_tensors_raw = get_element_attribute(element, 'LayersOfTensorsAttribute', elements) + layers_of_tensors_raw = get_element_attribute(node, 'LayersOfTensorsAttribute') layers_of_tensors = None if layers_of_tensors_raw: # The metamodel declares this as list[str | float | int]. Preserve @@ -1799,31 +1626,31 @@ def create_tensor_op(element, elements): # e.g. [0.5, 'x'] to ['0.5', 'x']. layers_of_tensors = parse_mixed_list(layers_of_tensors_raw) - reshape_dim = get_element_attribute(element, 'ReshapeDimAttribute', elements) + reshape_dim = get_element_attribute(node, 'ReshapeDimAttribute') if reshape_dim is not None: reshape_dim = parse_list_of_ints(reshape_dim) - transpose_dim = get_element_attribute(element, 'TransposeDimAttribute', elements) + transpose_dim = get_element_attribute(node, 'TransposeDimAttribute') if transpose_dim is not None: transpose_dim = parse_list_of_ints(transpose_dim) - permute_dim = get_element_attribute(element, 'PermuteDimAttribute', elements) + permute_dim = get_element_attribute(node, 'PermuteDimAttribute') if permute_dim is not None: permute_dim = parse_list_of_ints(permute_dim) - reduce_dim = get_element_attribute(element, 'ReduceDimAttribute', elements) + reduce_dim = get_element_attribute(node, 'ReduceDimAttribute') if reduce_dim is not None: reduce_dim = parse_tuple_or_int(reduce_dim) - reduce_keepdims = get_element_attribute(element, 'ReduceKeepdimAttribute', elements) + reduce_keepdims = get_element_attribute(node, 'ReduceKeepdimAttribute') if reduce_keepdims is not None: reduce_keepdims = parse_bool(reduce_keepdims) - shape_dim = get_element_attribute(element, 'ShapeDimAttribute', elements) + shape_dim = get_element_attribute(node, 'ShapeDimAttribute') if shape_dim is not None: shape_dim = parse_tuple_or_int(shape_dim) - actual_vars_raw = get_element_attribute(element, 'ActualVarsAttribute', elements) + actual_vars_raw = get_element_attribute(node, 'ActualVarsAttribute') actual_vars = None if actual_vars_raw: if isinstance(actual_vars_raw, str): @@ -1834,7 +1661,7 @@ def create_tensor_op(element, elements): elif isinstance(actual_vars_raw, list): actual_vars = [str(v).strip("'\"") for v in actual_vars_raw] - subscript_indices_raw = get_element_attribute(element, 'SubscriptIndicesAttribute', elements) + subscript_indices_raw = get_element_attribute(node, 'SubscriptIndicesAttribute') subscript_indices = None if subscript_indices_raw: subscript_indices = parse_structured_literal( @@ -1843,7 +1670,7 @@ def create_tensor_op(element, elements): '[{"type": "index", "value": 0}]', ) - repeat_dim = get_element_attribute(element, 'RepeatDimAttribute', elements) + repeat_dim = get_element_attribute(node, 'RepeatDimAttribute') if repeat_dim is not None: # Declared list[int | str]: the frontend legitimately emits # [1, 'op_3', 1] to repeat along a dimension taken from another op. @@ -1851,20 +1678,20 @@ def create_tensor_op(element, elements): # dropped the user's whole value. repeat_dim = parse_mixed_list(repeat_dim, prefer_int=True) - interpolate_size_raw = get_element_attribute(element, 'InterpolateSizeAttribute', elements) + interpolate_size_raw = get_element_attribute(node, 'InterpolateSizeAttribute') interpolate_size = None if interpolate_size_raw: parsed = parse_list_of_ints(interpolate_size_raw) if parsed: interpolate_size = tuple(parsed) - interpolate_scale = get_element_attribute(element, 'InterpolateScaleAttribute', elements) + interpolate_scale = get_element_attribute(node, 'InterpolateScaleAttribute') if interpolate_scale is not None: interpolate_scale = parse_float(interpolate_scale) - interpolate_mode = get_element_attribute(element, 'InterpolateModeAttribute', elements) + interpolate_mode = get_element_attribute(node, 'InterpolateModeAttribute') - pad_amount_raw = get_element_attribute(element, 'PadAmountAttribute', elements) + pad_amount_raw = get_element_attribute(node, 'PadAmountAttribute') pad_amount = None if pad_amount_raw: pad_amount = parse_structured_literal( @@ -1872,25 +1699,25 @@ def create_tensor_op(element, elements): 'a list of [before, after] pairs like [[1, 1], [2, 2]]', ) - pad_mode = get_element_attribute(element, 'PadModeAttribute', elements) + pad_mode = get_element_attribute(node, 'PadModeAttribute') - pad_value = get_element_attribute(element, 'PadValueAttribute', elements) + pad_value = get_element_attribute(node, 'PadValueAttribute') if pad_value is not None: pad_value = parse_float(pad_value) - dropout_rate = get_element_attribute(element, 'DropoutRateAttribute', elements) + dropout_rate = get_element_attribute(node, 'DropoutRateAttribute') if dropout_rate is not None: dropout_rate = parse_float(dropout_rate) - dropout_training_aware = get_element_attribute(element, 'DropoutTrainingAwareAttribute', elements) + dropout_training_aware = get_element_attribute(node, 'DropoutTrainingAwareAttribute') if dropout_training_aware is not None: dropout_training_aware = parse_bool(dropout_training_aware) - split_dim = get_element_attribute(element, 'SplitDimAttribute', elements) + split_dim = get_element_attribute(node, 'SplitDimAttribute') if split_dim is not None: split_dim = parse_tuple_or_int(split_dim) - split_sizes_raw = get_element_attribute(element, 'SplitSizesAttribute', elements) + split_sizes_raw = get_element_attribute(node, 'SplitSizesAttribute') split_sizes = None if split_sizes_raw: try: @@ -1905,7 +1732,7 @@ def create_tensor_op(element, elements): except (ValueError, TypeError): split_sizes = None - output_vars_raw = get_element_attribute(element, 'OutputVarsAttribute', elements) + output_vars_raw = get_element_attribute(node, 'OutputVarsAttribute') output_vars = None if output_vars_raw: if isinstance(output_vars_raw, str): @@ -1916,16 +1743,16 @@ def create_tensor_op(element, elements): elif isinstance(output_vars_raw, list): output_vars = [str(v).strip("'\"") for v in output_vars_raw] - permute_in = get_element_attribute(element, 'PermuteInAttribute', elements) + permute_in = get_element_attribute(node, 'PermuteInAttribute') if permute_in is not None: permute_in = parse_bool(permute_in) - permute_out = get_element_attribute(element, 'PermuteOutAttribute', elements) + permute_out = get_element_attribute(node, 'PermuteOutAttribute') if permute_out is not None: permute_out = parse_bool(permute_out) - input_var = get_element_attribute(element, 'InputVarAttribute', elements) - output_var = get_element_attribute(element, 'OutputVarAttribute', elements) + input_var = get_element_attribute(node, 'InputVarAttribute') + output_var = get_element_attribute(node, 'OutputVarAttribute') # Validate required attributes based on tns_type types_requiring_layers = ['multiply', 'matmultiply', 'concatenate'] @@ -2076,7 +1903,7 @@ def create_tensor_op(element, elements): tensor_op.output_var = output_var mark_explicit(tensor_op, 'output_var') - input_reused_attr = get_element_attribute(element, 'InputReusedAttribute', elements) + input_reused_attr = get_element_attribute(node, 'InputReusedAttribute') if input_reused_attr is not None: tensor_op.input_reused = parse_bool(input_reused_attr) mark_explicit(tensor_op, 'input_reused') @@ -2084,24 +1911,24 @@ def create_tensor_op(element, elements): return tensor_op -def create_configuration(element, elements): - """Create a Configuration from element data.""" - batch_size_raw = get_element_attribute(element, 'BatchSizeAttribute', elements) +def create_configuration(node): + """Create a Configuration from a v4 node.""" + batch_size_raw = get_element_attribute(node, 'BatchSizeAttribute') batch_size = parse_tuple_or_int(batch_size_raw) if batch_size is None: raise ValueError("Configuration missing mandatory 'batch_size' attribute") - epochs_raw = get_element_attribute(element, 'EpochsAttribute', elements) + epochs_raw = get_element_attribute(node, 'EpochsAttribute') epochs = parse_tuple_or_int(epochs_raw) if epochs is None: raise ValueError("Configuration missing mandatory 'epochs' attribute") - learning_rate_raw = get_element_attribute(element, 'LearningRateAttribute', elements) + learning_rate_raw = get_element_attribute(node, 'LearningRateAttribute') learning_rate = parse_float(learning_rate_raw) if learning_rate is None: raise ValueError("Configuration missing mandatory 'learning_rate' attribute") - optimizer = get_element_attribute(element, 'OptimizerAttribute', elements) + optimizer = get_element_attribute(node, 'OptimizerAttribute') if not optimizer: raise ValueError("Configuration missing mandatory 'optimizer' attribute") if optimizer not in _ALLOWED_OPTIMIZERS: @@ -2110,7 +1937,7 @@ def create_configuration(element, elements): f"Allowed values: {', '.join(_ALLOWED_OPTIMIZERS)}." ) - loss_function = get_element_attribute(element, 'LossFunctionAttribute', elements) + loss_function = get_element_attribute(node, 'LossFunctionAttribute') if not loss_function: raise ValueError("Configuration missing mandatory 'loss_function' attribute") if loss_function not in _ALLOWED_LOSS_FUNCTIONS: @@ -2119,13 +1946,10 @@ def create_configuration(element, elements): f"Allowed values: {', '.join(_ALLOWED_LOSS_FUNCTIONS)}." ) - metrics_str = get_element_attribute(element, 'MetricsAttribute', elements) + metrics_str = get_element_attribute(node, 'MetricsAttribute') if not metrics_str: raise ValueError("Configuration missing mandatory 'metrics' attribute") - # Parse metrics (could be comma-separated, list notation, or quoted list - # like "['accuracy', 'precision']"). Strip quotes after splitting so the - # whitelist check sees the bare metric name. if isinstance(metrics_str, str): if metrics_str.startswith('[') and metrics_str.endswith(']'): inner = metrics_str[1:-1].strip() @@ -2152,13 +1976,12 @@ def create_configuration(element, elements): metrics=metrics, ) - # Optional attributes - weight_decay = get_element_attribute(element, 'WeightDecayAttribute', elements) + weight_decay = get_element_attribute(node, 'WeightDecayAttribute') if weight_decay is not None: config.weight_decay = parse_float(weight_decay, 0.0) mark_explicit(config, 'weight_decay') - momentum = get_element_attribute(element, 'MomentumAttribute', elements) + momentum = get_element_attribute(node, 'MomentumAttribute') if momentum is not None: config.momentum = parse_float(momentum, 0.0) mark_explicit(config, 'momentum') diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/object_diagram_processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/object_diagram_processor.py index 20c6b227a..4c8074938 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/object_diagram_processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/object_diagram_processor.py @@ -1,5 +1,11 @@ """ -Object diagram processing for converting JSON to BUML format. +Object diagram processing for converting v4 JSON to BUML format. + +Reads the v4 wire shape (``{nodes, edges}``) natively. The v4 spec +collapses ``ObjectAttribute`` rows onto the parent ``objectName`` node's +``data.attributes`` array; we walk that directly. ``referenceDiagramData`` +arrives in v4 too (and is consumed by walking its ``nodes``/``edges`` +likewise). """ import logging @@ -12,11 +18,26 @@ from besser.BUML.metamodel.object import Link, LinkEnd from besser.BUML.metamodel.structural import Metadata from besser.utilities.web_modeling_editor.backend.services.converters.parsers import parse_attribute +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + node_data, +) from besser.utilities.web_modeling_editor.backend.constants.user_buml_model import ( domain_model as user_reference_domain_model, ) from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.utils import sanitize_name from datetime import datetime, timedelta +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + reject_unreadable_model, +) + +# The React Flow frontend creates ``comment`` nodes tethered by +# ``CommentLink`` edges; ``Comments`` / ``Link`` are the legacy spellings. +COMMENT_NODE_TYPES = ("comment", "Comments") +COMMENT_LINK_TYPES = ("CommentLink", "Link") + +# UserDiagram links behave exactly like ObjectLink (the frontend registers +# ``UserModelLink`` as an ObjectLink alias). +OBJECT_LINK_TYPES = ("ObjectLink", "UserModelLink") def get_all_attributes(cls, domain_model): @@ -49,55 +70,51 @@ def _temporal_kind(type_name): def parse_datetime_value(value, type_name): """Parse datetime values from string format.""" + if not isinstance(value, str): + return value try: if type_name in ['datetime', 'DateTimeType']: - # Try different datetime formats if 'T' in value: - if len(value) == 16: # Format: YYYY-MM-DDTHH:MM + if len(value) == 16: return datetime.strptime(value, '%Y-%m-%dT%H:%M') - elif len(value) == 19: # Format: YYYY-MM-DDTHH:MM:SS + elif len(value) == 19: return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S') - else: # Try with milliseconds or other formats - # Remove milliseconds and timezone info for parsing + else: clean_value = value.split('.')[0].split('+')[0].split('Z')[0] - if len(clean_value) == 16: # After cleaning, check if it's YYYY-MM-DDTHH:MM + if len(clean_value) == 16: return datetime.strptime(clean_value, '%Y-%m-%dT%H:%M') else: return datetime.strptime(clean_value, '%Y-%m-%dT%H:%M:%S') else: - # Try other common formats try: return datetime.strptime(value, '%Y-%m-%d %H:%M:%S') except ValueError: - # Try without seconds return datetime.strptime(value, '%Y-%m-%d %H:%M') elif type_name in ['date', 'DateType']: return datetime.strptime(value, '%Y-%m-%d').date() elif type_name in ['time', 'TimeType']: - # Try different time formats - if len(value.split(':')) == 2: # Format: HH:MM + if len(value.split(':')) == 2: return datetime.strptime(value, '%H:%M').time() - else: # Format: HH:MM:SS + else: return datetime.strptime(value, '%H:%M:%S').time() elif type_name in ['timedelta', 'TimeDeltaType']: - # Parse timedelta from string (e.g., "1 day, 2:30:00", "2:30:00", or "1:30") if 'day' in value: parts = value.split(',') days = int(parts[0].split()[0]) time_part = parts[1].strip() if len(parts) > 1 else "0:00:00" time_components = time_part.split(':') - if len(time_components) == 2: # HH:MM format + if len(time_components) == 2: hours, minutes = map(int, time_components) return timedelta(days=days, hours=hours, minutes=minutes) - else: # HH:MM:SS format + else: hours, minutes, seconds = map(int, time_components) return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds) else: time_components = value.split(':') - if len(time_components) == 2: # HH:MM format + if len(time_components) == 2: hours, minutes = map(int, time_components) return timedelta(hours=hours, minutes=minutes) - else: # HH:MM:SS format + else: hours, minutes, seconds = map(int, time_components) return timedelta(hours=hours, minutes=minutes, seconds=seconds) except (ValueError, IndexError): @@ -107,6 +124,29 @@ def parse_datetime_value(value, type_name): return value +def _reference_class_name(class_node_id: str, reference_data: dict) -> str: + """Look up a class node's name in v4 reference diagram data.""" + if not isinstance(reference_data, dict): + return "" + for node in reference_data.get("nodes") or []: + if node.get("id") != class_node_id: + continue + if node.get("type") == "class": + return (node.get("data") or {}).get("name", "") + return "" + + +def _reference_association_name(assoc_id: str, reference_data: dict) -> str: + """Look up an association edge's name in v4 reference diagram data.""" + if not isinstance(reference_data, dict): + return "" + for edge in reference_data.get("edges") or []: + if edge.get("id") != assoc_id: + continue + return (edge.get("data") or {}).get("name", "") + return "" + + def _is_shared_domain_model(domain_model) -> bool: """Return True if *domain_model* is a process-wide model shared across requests. @@ -134,19 +174,8 @@ def _append_description(element, text): def process_object_diagram(json_data, domain_model): - """Process Object Diagram specific elements and return an ObjectModel. - - Args: - json_data: The JSON payload describing the object diagram. - domain_model: A ``DomainModel`` instance that provides the class - definitions referenced by objects in the diagram. This parameter - is required; passing ``None`` will raise a ``ConversionError`` - with a clear message. - - Raises: - ConversionError: If *domain_model* is ``None`` or does not expose the - expected interface. - """ + """Process an Object Diagram in the v4 wire shape and return an ObjectModel.""" + reject_unreadable_model(json_data, "ObjectDiagram") if domain_model is None: raise ConversionError( "Object diagram processing requires a reference class diagram (domain model). " @@ -156,290 +185,260 @@ def process_object_diagram(json_data, domain_model): title = sanitize_name(json_data.get('title', 'Generated_Object_Model')) object_model = ObjectModel(title) - # Get elements, relationships, and reference data from the JSON payload - model_data = json_data.get('model', {}) - elements = model_data.get('elements', {}) - relationships = model_data.get('relationships', {}) - reference_data = model_data.get('referenceDiagramData', {}) - - # If elements is empty, try the nested structure some exporters use - if not elements and isinstance(model_data.get('model'), dict): + model_data = json_data.get('model', {}) or {} + nodes = model_data.get('nodes') or [] + edges = model_data.get('edges') or [] + if not isinstance(nodes, list): + nodes = [] + if not isinstance(edges, list): + edges = [] + + reference_data = model_data.get('referenceDiagramData', {}) or {} + + # If nodes is empty, try the nested structure some exporters use + if not nodes and isinstance(model_data.get('model'), dict): nested_model = model_data.get('model') - elements = nested_model.get('elements', {}) - relationships = nested_model.get('relationships', {}) + nodes = nested_model.get('nodes') or [] + edges = nested_model.get('edges') or [] reference_data = nested_model.get('referenceDiagramData', reference_data) - # Track objects by their ID for link creation + # Track objects by node id for link creation. objects_by_id = {} - # Build a class name lookup for O(1) attribute property resolution - # (get_all_attributes already traverses generalizations, so we just need fast class lookups) + comment_nodes = {} + comment_links = {} - # Store comments for later processing - comment_elements = {} # {comment_id: comment_text} - comment_links = {} # {comment_id: [linked_element_ids]} + for node in nodes: + node_type = node.get("type") + node_id = node.get("id") + data = node_data(node) - # First pass: Create objects using fluent API - for element_id, element in elements.items(): - # Collect comments - if element.get("type") == "Comments": - comment_text = element.get("name", "").strip() - comment_elements[element_id] = comment_text + if node_type in COMMENT_NODE_TYPES: + comment_nodes[node_id] = (data.get("name") or "").strip() continue - if element.get("type") == "ObjectName" or element.get("type") == "UserModelName": - # Extract object name and class ID - object_name = element.get("name", "") - class_id = element.get("classId") - - # Find the corresponding class in the domain model using classId: - # by element id first (survives a rename), then by the class name - # in the reference data or on the object. - class_obj = _find_by_id(domain_model.get_classes(), class_id) - class_name = None - if not class_obj and class_id and reference_data: - reference_elements = reference_data.get('elements', {}) - class_element = reference_elements.get(class_id) - if class_element: - class_name = class_element.get("name", "") - if not class_obj and not class_name: - class_name = element.get("className") - - if not class_obj and class_name: - class_obj = domain_model.get_class_by_name(class_name) - - if not class_obj: - # Fall back to searching by object name if class lookup fails - class_obj = domain_model.get_class_by_name(object_name) - - if not class_obj: - raise ConversionError( - f"Could not find class for object '{object_name}' with class ID '{class_id}'. " - "Ensure either reference diagram data or explicit class names are provided." - ) - - # Create object using fluent API - builder = ObjectBuilder(class_obj).name(object_name) - - # Process object attributes (slots) and add them to builder - attributes_dict = {} - for attr_id in element.get("attributes", []): - attr_element = elements.get(attr_id) - if not attr_element: - continue + if node_type not in ("objectName", "UserModelName"): + continue - attr_type = attr_element.get("type") - attr_string = attr_element.get("name", "") - attr_name = None - value = None - - if attr_type == "ObjectAttribute": - # Format: "+ name: type = value" - if " = " in attr_string: - attr_part, value_part = attr_string.split(" = ", 1) - value = value_part.strip() - attr_string = attr_part.strip() - try: - _, attr_name, _ = parse_attribute(attr_string, domain_model) - except Exception as e: - logger.warning("Could not process attribute '%s' for object '%s': %s", attr_string, object_name, e) - continue - elif attr_type == "UserModelAttribute": - operator = attr_element.get("attributeOperator", "==") - # The name string can embed the operator in two forms: the - # stored symbol (e.g. "age == 22", produced by manual edits) - # or the editor's displayed equality symbol (a single '=', - # e.g. "age = 22", produced by the modeling agent). Try the - # stored operator first so "age == 22" is not split on its - # first '=' (which captured "= 22" as the value and broke - # type conversion). Fall back to the displayed '=' for - # equality, so agent-generated criteria are still parsed - # instead of dropped. - candidate_operators = [operator] - if operator == "==": - candidate_operators.append("=") - for candidate in candidate_operators: - if candidate and candidate in attr_string: - attr_part, value_part = attr_string.split(candidate, 1) - attr_name = attr_part.strip() - value = value_part.strip() - break - else: - attr_name = attr_string.strip() - value = attr_element.get("attributeValue") - else: + object_name = data.get("name", "") or "" + class_id = data.get("classId") + + # By element id first (survives a rename), then by the class name in + # the reference data or on the object. + class_obj = _find_by_id(domain_model.get_classes(), class_id) + class_name = None + if not class_obj and class_id and reference_data: + class_name = _reference_class_name(class_id, reference_data) + if not class_obj and not class_name: + class_name = data.get("className") + if not class_obj and class_name: + class_obj = domain_model.get_class_by_name(class_name) + if not class_obj: + class_obj = domain_model.get_class_by_name(object_name) + if not class_obj: + raise ConversionError( + f"Could not find class for object '{object_name}' with class ID '{class_id}'. " + "Ensure either reference diagram data or explicit class names are provided." + ) + + builder = ObjectBuilder(class_obj).name(object_name) + + attributes_dict = {} + for attr in data.get("attributes") or []: + attr_string = attr.get("name", "") or "" + attr_name = None + value = None + if node_type == "objectName": + # v4 inspector rows carry the value in a separate + # ``value`` field (``ObjectNodeAttribute`` in + # packages/library/lib/types/nodes/NodeProps.ts); legacy + # rows bake a combined "name = value" string into ``name``. + split_value = attr.get("value") + # Legacy combined format: "name = value". + if " = " in attr_string: + attr_part, value_part = attr_string.split(" = ", 1) + if split_value is None: + split_value = value_part.strip() + attr_string = attr_part.strip() + value = split_value + try: + _, attr_name, _ = parse_attribute(attr_string, domain_model) + except Exception as e: + logger.warning( + "Could not process attribute '%s' for object '%s': %s", + attr_string, object_name, e, + ) continue - - # Skip criteria left blank in the editor (e.g. "age = "): an - # empty value is "no constraint", not a value to type-convert, - # so it must not raise on int/float parsing. - if attr_name and value not in (None, ""): - # Find the corresponding property in the class or its - # ancestors: by attributeId first, then by name. - all_attrs = get_all_attributes(class_obj, domain_model) - property_obj = _find_by_id(all_attrs, attr_element.get("attributeId")) - if property_obj is None: - for prop in all_attrs: - if prop.name == attr_name: - property_obj = prop - break - - if property_obj: - # Convert value to appropriate type - converted_value = value - - # Check if the property type is an enumeration - if hasattr(property_obj.type, 'literals'): # This is an enumeration + else: # UserModelName + # v4 inspector rows carry ``value`` (preferred) / + # ``defaultValue`` plus an ``attributeOperator`` comparator + # (``UserModelAttributeRow``). Legacy rows bake + # "name value" into ``name``. + operator_str = attr.get("attributeOperator", "==") + attr_name = attr_string.strip() + embedded_value = None + # The name string can embed the operator in two forms: the + # stored symbol (e.g. "age == 22", from manual edits) or the + # editor's displayed equality symbol (a single '=', e.g. + # "age = 22", from the modeling agent). Try the stored + # operator first so "age == 22" is not split on its first '='; + # fall back to '=' for equality so agent-generated criteria + # are still parsed instead of dropped. + candidate_operators = [operator_str] + if operator_str == "==": + candidate_operators.append("=") + for candidate in candidate_operators: + if candidate and candidate in attr_name: + attr_part, value_part = attr_name.split(candidate, 1) + attr_name = attr_part.strip() + embedded_value = value_part.strip() + break + value = attr.get("value") + if value is None: + value = attr.get("defaultValue") + if value is None: + value = embedded_value if embedded_value else attr.get("attributeValue") + + # Skip values left blank in the editor (e.g. "age = "): an empty + # value is "no constraint", not a value to type-convert, so it + # must not raise on int/float parsing. + if attr_name and value not in (None, ""): + # The class's (or an ancestor's) attribute: by attributeId + # first, then by name. + all_attrs = get_all_attributes(class_obj, domain_model) + property_obj = _find_by_id(all_attrs, attr.get("attributeId")) + if property_obj is None: + property_obj = next((prop for prop in all_attrs if prop.name == attr_name), None) + + if property_obj: + converted_value = value + if hasattr(property_obj.type, 'literals'): + try: + for literal in property_obj.type.literals: + if literal.name == value: + converted_value = literal + break + else: + converted_value = getattr(property_obj.type, value) + except (AttributeError, StopIteration): + logger.warning( + "Enumeration literal '%s' not found in %s", + value, property_obj.type.name, + ) + converted_value = value + elif hasattr(property_obj.type, 'name'): + type_name = ( + property_obj.type.name + if hasattr(property_obj.type, 'name') + else str(property_obj.type) + ) + if type_name in ['int', 'IntegerType']: + try: + converted_value = int(value) + except (TypeError, ValueError) as exc: + raise ConversionError( + f"Object '{object_name}' (class '{class_obj.name}'): " + f"attribute '{attr_name}' expects an integer, " + f"but received {value!r}." + ) from exc + elif type_name in ['float', 'FloatType']: try: - for literal in property_obj.type.literals: - if literal.name == value: - converted_value = literal - break - else: - converted_value = getattr(property_obj.type, value) - except (AttributeError, StopIteration): - logger.warning("Enumeration literal '%s' not found in %s", value, property_obj.type.name) - converted_value = value - elif hasattr(property_obj.type, 'name'): - type_name = property_obj.type.name if hasattr(property_obj.type, 'name') else str(property_obj.type) - if type_name in ['int', 'IntegerType']: - try: - converted_value = int(value) - except (TypeError, ValueError) as exc: - raise ConversionError( - f"Object '{object_name}' (class '{class_obj.name}'): " - f"attribute '{attr_name}' expects an integer, " - f"but received {value!r}." - ) from exc - elif type_name in ['float', 'FloatType']: - try: - converted_value = float(value) - except (TypeError, ValueError) as exc: - raise ConversionError( - f"Object '{object_name}' (class '{class_obj.name}'): " - f"attribute '{attr_name}' expects a number, " - f"but received {value!r}." - ) from exc - elif type_name in ['bool', 'BooleanType']: + converted_value = float(value) + except (TypeError, ValueError) as exc: + raise ConversionError( + f"Object '{object_name}' (class '{class_obj.name}'): " + f"attribute '{attr_name}' expects a number, " + f"but received {value!r}." + ) from exc + elif type_name in ['bool', 'BooleanType']: + if isinstance(value, str): converted_value = value.lower() in ['true', '1', 'yes'] - elif type_name in ['datetime', 'DateTimeType', 'date', 'DateType', 'time', 'TimeType', 'timedelta', 'TimeDeltaType']: - converted_value = parse_datetime_value(value, type_name) - - attributes_dict[property_obj.name] = converted_value - - # Add attributes to builder if any were found - if attributes_dict: - builder = builder.attributes(**attributes_dict) - - # Build the object. Translate metamodel TypeError/ValueError (e.g. a - # datetime/enum value the upstream conversion let through and the - # metamodel rejected) into a ConversionError carrying the object - # context, so the user sees a 400 with a clear message instead of a - # 500 internal error. - try: - obj = builder.build() - except (TypeError, ValueError) as exc: - raise ConversionError( - f"Object '{object_name}' (class '{class_obj.name}'): {exc}" - ) from exc - logger.debug("Created object '%s' of class '%s'", object_name, class_obj.name) - - # Add the object to the model and track it - object_model.add_object(obj) - objects_by_id[element_id] = obj - # Second pass: Create links between objects - for rel_id, relationship in relationships.items(): - # Handle Link (comment links) - if relationship.get("type") == "Link": - source_element_id = relationship.get("source", {}).get("element") - target_element_id = relationship.get("target", {}).get("element") - - # Determine which is the comment and which is the target + else: + converted_value = bool(value) + elif type_name in ['datetime', 'DateTimeType', 'date', 'DateType', 'time', 'TimeType', 'timedelta', 'TimeDeltaType']: + converted_value = parse_datetime_value(value, type_name) + attributes_dict[property_obj.name] = converted_value + + if attributes_dict: + builder = builder.attributes(**attributes_dict) + + try: + obj = builder.build() + except (TypeError, ValueError) as exc: + raise ConversionError( + f"Object '{object_name}' (class '{class_obj.name}'): {exc}" + ) from exc + logger.debug("Created object '%s' of class '%s'", object_name, class_obj.name) + + object_model.add_object(obj) + objects_by_id[node_id] = obj + + # Process links (edges). + for edge in edges: + edge_type = edge.get("type") + if edge_type in COMMENT_LINK_TYPES: + source_id = edge.get("source") + target_id = edge.get("target") comment_id = None - target_id = None - - if source_element_id in comment_elements: - comment_id = source_element_id - target_id = target_element_id - elif target_element_id in comment_elements: - comment_id = target_element_id - target_id = source_element_id - - if comment_id and target_id: - if comment_id not in comment_links: - comment_links[comment_id] = [] - comment_links[comment_id].append(target_id) - + target = None + if source_id in comment_nodes: + comment_id = source_id + target = target_id + elif target_id in comment_nodes: + comment_id = target_id + target = source_id + if comment_id and target: + comment_links.setdefault(comment_id, []).append(target) continue - if relationship.get("type") == "ObjectLink": - source_id = relationship.get("source", {}).get("element") - target_id = relationship.get("target", {}).get("element") - link_name = relationship.get("name", "") - association_id = relationship.get("associationId") + if edge_type in OBJECT_LINK_TYPES: + source_id = edge.get("source") + target_id = edge.get("target") + edge_data = edge.get("data") or {} + link_name = edge_data.get("name", "") or "" + association_id = edge_data.get("associationId") source_obj = objects_by_id.get(source_id) target_obj = objects_by_id.get(target_id) - if not source_obj or not target_obj: raise ConversionError( f"Could not find objects for link '{link_name}'. Please ensure all objects in the link exist in the diagram." ) - # Find the corresponding association in the domain model + association_obj = None if association_id: - # First try to find the association directly by ID from the domain model if hasattr(domain_model, 'association_by_id') and domain_model.association_by_id: association_obj = domain_model.association_by_id.get(association_id) + if not association_obj and reference_data: + assoc_name = _reference_association_name(association_id, reference_data) + if assoc_name: + for assoc in domain_model.associations: + if assoc.name == assoc_name: + association_obj = assoc + break - # If not found by direct ID lookup, try the reference diagram approach - if not association_obj: - # Look for the association by ID in the reference diagram data - reference_data = json_data.get('model', {}).get('referenceDiagramData', {}) - if reference_data: - reference_relationships = reference_data.get('relationships', {}) - assoc_element = reference_relationships.get(association_id) - if assoc_element: - # Found association in reference data - assoc_name = assoc_element.get("name", "") - # Only try to find by name if the association name is not empty - if assoc_name: - # Try to find the association by name - for assoc in domain_model.associations: - if assoc.name == assoc_name: - association_obj = assoc - break - - # If still not found, try to find association by matching the connected classes if not association_obj: for assoc in domain_model.associations: - # Check if this association connects the right classes end_types = {end.type for end in assoc.ends} if (source_obj.classifier in end_types and target_obj.classifier in end_types): association_obj = assoc break if association_obj: - # Create link using association ends link_ends = [] for end in association_obj.ends: - # Check if end type matches source object (considering inheritance) source_matches = False if end.type == source_obj.classifier: source_matches = True else: - # Check if source object's class inherits from end type for gen in domain_model.generalizations: if gen.specific == source_obj.classifier and gen.general == end.type: source_matches = True break - - # Check if end type matches target object (considering inheritance) target_matches = False if end.type == target_obj.classifier: target_matches = True else: - # Check if target object's class inherits from end type for gen in domain_model.generalizations: if gen.specific == target_obj.classifier and gen.general == end.type: target_matches = True @@ -448,19 +447,16 @@ def process_object_diagram(json_data, domain_model): if source_matches: link_end = LinkEnd(name=f"{end.name}_end", association_end=end, object=source_obj) link_ends.append(link_end) - logger.debug("Created link end for source: %s_end", end.name) elif target_matches: link_end = LinkEnd(name=f"{end.name}_end", association_end=end, object=target_obj) link_ends.append(link_end) if len(link_ends) == 2: - # Use link_name if provided, otherwise generate a default name # Object names may be display names with spaces ("Alice Smith"); a link name may not. link_display_name = link_name if link_name else sanitize_name( f"{source_obj.name}_{target_obj.name}_link" ) Link(name=link_display_name, association=association_obj, connections=link_ends) - # Links are automatically added to objects via the Link constructor else: raise ConversionError( f"Expected 2 link ends but got {len(link_ends)} for link '{link_name}'. There may be an issue with the association structure." @@ -477,7 +473,7 @@ def process_object_diagram(json_data, domain_model): # kept on this request's object model instead. (Objects cannot carry # metadata themselves: their attribute access is mapped onto slots/links.) annotate_classifiers = not _is_shared_domain_model(domain_model) - for comment_id, comment_text in comment_elements.items(): + for comment_id, comment_text in comment_nodes.items(): linked_objects = [ objects_by_id[element_id] for element_id in comment_links.get(comment_id, ()) diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/project_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/project_converter.py index e966526ce..a3b808929 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/project_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/project_converter.py @@ -6,17 +6,19 @@ """ import logging +import re from typing import Optional from . import ( process_class_diagram, + process_bpmn_diagram, process_object_diagram, process_agent_diagram, process_state_machine, - process_bpmn_diagram, process_component_diagram, process_deployment_diagram, ) +from .a2a_tags import annotate_agent_with_a2a from .kg_diagram_processor import process_kg_diagram from .method_nn_linker import link_method_neural_networks from besser.BUML.metamodel.project import Project @@ -161,9 +163,23 @@ def _is_valid_diagram(diag, diagram_type): nodes = data.get("nodes") if isinstance(data, dict) else getattr(model, "nodes", None) return bool(nodes) - # Standard element-based diagrams - elements = data.get("elements") if isinstance(data, dict) else getattr(model, "elements", None) - return bool(elements) + # Standard element-based diagrams accept the v4 ``nodes`` shape. The + # editor migrator at ``packages/library/lib/utils/versionConverter.ts`` + # is the only place v3 is converted to v4 in the system; the backend + # never sees v3. + if isinstance(data, dict): + nodes = data.get("nodes") + else: + nodes = getattr(model, "nodes", None) + if nodes: + return True + + # An agent diagram may hold only off-canvas ``components`` (intents, + # LLMs, RAG databases, ...) and no canvas nodes yet; it is still a model. + if diagram_type == "AgentDiagram": + components = data.get("components") if isinstance(data, dict) else getattr(model, "components", None) + return bool(components) + return False def _collect_valid_diagrams(project): @@ -202,9 +218,8 @@ def json_to_buml_project(project): Processes ALL diagrams of each type (not just the active one), so that every model is included in the resulting Project. """ - name = project.name - if name and "-" in name: - name = name.replace("-", "_") + # The editor allows any project name; the B-UML name must be an identifier. + name = re.sub(r"\W", "_", project.name) if project.name else project.name description = project.description or "" # Collect all valid diagrams, grouped by type @@ -215,6 +230,15 @@ def json_to_buml_project(project): # built model. Populated for BPMN + Agent diagrams as they are processed; # consumed by the cross-diagram resolver for process_model_refs / agent_diagram_ref. diagram_index: dict = {} + # id(model) -> (diagram model type, WME diagram id, title); project_to_code + # writes them so a .py import keeps the ids cross-diagram refs point at. + diagram_ids: dict = {} + # id(object model) -> the editor ``references`` it was resolved with. + diagram_references: dict = {} + + def _remember(model, diagram_type: str, diag) -> None: + if getattr(diag, "id", None): + diagram_ids[id(model)] = (diagram_type, diag.id, getattr(diag, "title", None)) # ── ClassDiagram caching ────────────────────────────────────────── # Cache processed ClassDiagrams by ID so we never process the same one twice # (e.g. when an ObjectDiagram and a GUINoCodeDiagram both reference it). @@ -225,6 +249,7 @@ def _get_or_process_class_diagram(class_diag): diag_id = class_diag.id if class_diag.id else id(class_diag) if diag_id not in processed_class_diagrams: processed_class_diagrams[diag_id] = process_class_diagram(class_diag.model_dump()) + _remember(processed_class_diagrams[diag_id], "ClassDiagram", class_diag) return processed_class_diagrams[diag_id] # ── Process ALL ClassDiagrams first ─────────────────────────────── @@ -243,8 +268,17 @@ def _get_or_process_class_diagram(class_diag): obj_class_diag = diagrams["ClassDiagram"][0] if obj_class_diag: obj_domain_model = _get_or_process_class_diagram(obj_class_diag) - object_model = process_object_diagram(obj_diag.model_dump(), obj_domain_model) + obj_json = obj_diag.model_dump() + # Stored object diagrams carry no reference data (the migration + # drops develop's embedded copy): resolve ``classId`` against the + # referenced class diagram so it wins over a missing/stale className. + if not obj_json["model"].get("referenceDiagramData"): + obj_json["model"]["referenceDiagramData"] = obj_class_diag.model_dump()["model"] + object_model = process_object_diagram(obj_json, obj_domain_model) model_list.append(object_model) + _remember(object_model, "ObjectDiagram", obj_diag) + if obj_class_diag.id: + diagram_references[id(object_model)] = {"ClassDiagram": obj_class_diag.id} else: logger.warning( "ObjectDiagram '%s' skipped: no ClassDiagram reference found.", @@ -260,12 +294,16 @@ def _get_or_process_class_diagram(class_diag): user_diag.model_dump(), user_reference_domain_model ) model_list.append(user_model) + _remember(user_model, "UserDiagram", user_diag) # ── Process ALL AgentDiagrams ───────────────────────────────────── for agent_diag in diagrams.get("AgentDiagram", []): + agent_json = agent_diag.model_dump() # An export keeps a transition the agent could not run, with a logged warning. - agent_model = process_agent_diagram(agent_diag.model_dump(), warnings=[]) + agent_model = process_agent_diagram(agent_json, warnings=[]) + annotate_agent_with_a2a(agent_model, agent_json) model_list.append(agent_model) + _remember(agent_model, "AgentDiagram", agent_diag) # Index by diagram UUID so an agentic task's agent_diagram_ref resolves. if getattr(agent_diag, "id", None): diagram_index[agent_diag.id] = agent_model @@ -301,6 +339,7 @@ def _get_or_process_class_diagram(class_diag): gui_model = process_gui_diagram(gui_json, class_json, gui_domain_model) model_list.append(gui_model) + _remember(gui_model, "GUINoCodeDiagram", gui_diag) else: logger.warning( "GUINoCodeDiagram '%s' skipped: no ClassDiagram reference found.", @@ -313,6 +352,7 @@ def _get_or_process_class_diagram(class_diag): for quantum_diag in diagrams.get("QuantumCircuitDiagram", []): quantum_model = process_quantum_diagram(quantum_diag.model_dump()) model_list.append(quantum_model) + _remember(quantum_model, "QuantumCircuitDiagram", quantum_diag) # The user-facing title of each NN and KG diagram, by id(model): those # metamodels store only a sanitized name, so project_to_code writes this @@ -327,6 +367,7 @@ def _get_or_process_class_diagram(class_diag): # was a line in the server log the user never sees. kg_model = process_kg_diagram(kg_diag.model_dump()) model_list.append(kg_model) + _remember(kg_model, "KnowledgeGraphDiagram", kg_diag) if kg_diag.title: diagram_titles[id(kg_model)] = kg_diag.title @@ -334,6 +375,7 @@ def _get_or_process_class_diagram(class_diag): for sm_diag in diagrams.get("StateMachineDiagram", []): sm_model = process_state_machine(sm_diag.model_dump()) model_list.append(sm_model) + _remember(sm_model, "StateMachineDiagram", sm_diag) # ── Process ALL NNDiagrams ──────────────────────────────────────── @@ -343,6 +385,7 @@ def _get_or_process_class_diagram(class_diag): for nn_diag in diagrams.get("NNDiagram", []): nn_model = process_nn_diagram(nn_diag.model_dump()) model_list.append(nn_model) + _remember(nn_model, "NNDiagram", nn_diag) processed_nn_models[nn_diag.id or id(nn_diag)] = nn_model if nn_diag.title: diagram_titles[id(nn_model)] = nn_diag.title @@ -355,6 +398,7 @@ def _get_or_process_class_diagram(class_diag): for bpmn_diag in diagrams.get("BPMN", []): bpmn_model = process_bpmn_diagram(bpmn_diag.model_dump()) model_list.append(bpmn_model) + _remember(bpmn_model, "BPMNDiagram", bpmn_diag) if bpmn_diag.id: diagram_index[bpmn_diag.id] = bpmn_model @@ -362,11 +406,13 @@ def _get_or_process_class_diagram(class_diag): for comp_diag in diagrams.get("ComponentDiagram", []): comp_model = process_component_diagram(comp_diag.model_dump()) model_list.append(comp_model) + _remember(comp_model, "ComponentDiagram", comp_diag) # ── Process ALL DeploymentDiagrams ─────────────────────────────── for dep_diag in diagrams.get("DeploymentDiagram", []): dep_model = process_deployment_diagram(dep_diag.model_dump()) model_list.append(dep_model) + _remember(dep_model, "DeploymentDiagram", dep_diag) # Ensure ALL processed ClassDiagrams are in model_list. # Object/GUI diagrams may reference ClassDiagrams that were not in the @@ -388,6 +434,10 @@ def _get_or_process_class_diagram(class_diag): # can read them without changing this function's return type (the # public API stays a single Project instance). project_instance._diagram_titles = diagram_titles + if name != project.name: + project_instance._display_name = project.name + project_instance._diagram_ids = diagram_ids + project_instance._diagram_references = diagram_references # Project-level cross-diagram-reference promotion. # Classify the already-built models and promote dangling cross-refs diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/state_machine_processor.py b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/state_machine_processor.py index 464a6cd05..21610826f 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/state_machine_processor.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/json_to_buml/state_machine_processor.py @@ -1,7 +1,8 @@ """ -State machine processing for converting JSON to BUML format. +State machine processing for converting v4 JSON to a BUML StateMachine. -Returns a StateMachine metamodel instance (not a code string). +Reads the v4 wire shape (``{nodes, edges}``) natively. See +``docs/source/migrations/uml-v4-shape.md`` for the spec. """ import logging @@ -14,22 +15,29 @@ from besser.utilities.buml_code_builder.common import _sanitize_identifier from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import EditorIds from besser.utilities.web_modeling_editor.backend.services.exceptions import ConversionError +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + node_data, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml._node_helpers import ( + reject_unreadable_model, +) logger = logging.getLogger(__name__) +# The React Flow frontend creates ``comment`` nodes tethered by +# ``CommentLink`` edges; ``Comments`` / ``Link`` are the legacy spellings. +COMMENT_NODE_TYPES = ("comment", "Comments") +COMMENT_LINK_TYPES = ("CommentLink", "Link") + def process_state_machine(json_data): - """Process State Machine Diagram specific elements and return a StateMachine instance. + """Process a v4 State Machine Diagram and return a ``StateMachine``. Args: - json_data: Dictionary containing the state machine diagram JSON data. - - Returns: - StateMachine: A BUML StateMachine metamodel instance. - - Raises: - ConversionError: If the JSON data is invalid or missing required fields. + json_data: Dictionary containing the state machine diagram JSON + in the v4 wire shape (``model.nodes`` / ``model.edges``). """ + reject_unreadable_model(json_data, "StateMachineDiagram") sm_name = json_data.get("title", "Generated_State_Machine") if ' ' in sm_name: sm_name = sm_name.replace(' ', '_') @@ -42,252 +50,210 @@ def process_state_machine(json_data): model_data = json_data.get('model') if not model_data: raise ConversionError("State machine JSON is missing the 'model' key.") - elements = model_data.get('elements') or {} - relationships = model_data.get('relationships') or {} + nodes = model_data.get('nodes') or [] + edges = model_data.get('edges') or [] + if not isinstance(nodes, list): + nodes = [] + if not isinstance(edges, list): + edges = [] + + nodes_by_id = {n.get("id"): n for n in nodes if n.get("id")} - # Track states by element ID for later reference - states_by_id = {} # element_id -> State object + states_by_id = {} # node_id -> State body_names = set() event_names = set() - # Store comments for later processing - comment_elements = {} # {comment_id: comment_text} - comment_links = {} # {comment_id: [linked_element_ids]} - - # Collect all body and event names first - for element_id, element in elements.items(): - if element.get("type") == "Comments": - comment_text = element.get("name", "") - comment_elements[element_id] = comment_text + comment_nodes = {} # comment_id -> text + comment_links = {} # comment_id -> [linked_node_ids] + + # First pass: collect body / fallback body names from State data, and + # comments. + for node in nodes: + node_type = node.get("type") + node_id = node.get("id") + data = node_data(node) + if node_type in COMMENT_NODE_TYPES: + comment_nodes[node_id] = data.get("name", "") continue - elif element.get("type") == "StateBody": - body_names.add(element.get("name")) - elif element.get("type") == "StateFallbackBody": - body_names.add(element.get("name")) + if node_type == "State": + for body in data.get("bodies") or []: + if body.get("name"): + body_names.add(body["name"]) + for body in data.get("fallbackBodies") or []: + if body.get("name"): + body_names.add(body["name"]) - # Collect guard condition names from transitions (for code-block backed guards) guard_names = set() - # Collect event names from transitions - for rel in relationships.values(): - if rel.get("type") == "StateTransition" and rel.get("name"): - event_names.add(rel.get("name")) - if rel.get("type") == "StateTransition" and rel.get("guard"): - guard_value = rel["guard"] - # If the guard matches a code-block function name, record it - guard_names.add(guard_value) - elif rel.get("type") == "Link": - # Handle comment links - source_element_id = rel.get("source", {}).get("element") - target_element_id = rel.get("target", {}).get("element") - + # Collect event names + guards from edges, and comment links. + for edge in edges: + edge_type = edge.get("type") + edge_data = edge.get("data") or {} + if edge_type == "StateTransition": + if edge_data.get("name"): + event_names.add(edge_data["name"]) + if edge_data.get("guard"): + guard_names.add(edge_data["guard"]) + elif edge_type in COMMENT_LINK_TYPES: + source_id = edge.get("source") + target_id = edge.get("target") comment_id = None - target_id = None - - if source_element_id in comment_elements: - comment_id = source_element_id - target_id = target_element_id - elif target_element_id in comment_elements: - comment_id = target_element_id - target_id = source_element_id - - if comment_id and target_id: - if comment_id not in comment_links: - comment_links[comment_id] = [] - comment_links[comment_id].append(target_id) - - # Build Body, Event, and Condition objects from code blocks - body_objects = {} # function name -> Body instance - event_objects = {} # function name -> Event instance - condition_objects = {} # function/guard name -> Condition instance - - - for code_block_id, element in elements.items(): - if element.get("type") == "StateCodeBlock": - name = element.get("name", "") - code_content = element.get("code", "") - - # If name is empty, try to extract function name from code content - if not name: - function_match = re.search(r'def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(', code_content) - if function_match: - name = function_match.group(1) - - if not name: - continue - - # Clean up the code content by removing extra newlines - cleaned_code = "\n".join(line for line in code_content.splitlines() if line.strip()) - - if name in body_names: - # Create a Body with a CustomCodeAction containing the source code. - # We cannot pass a live callable here since we only have source text, - # so we use the actions-based constructor with CustomCodeAction. - body = Body(name=name, actions=[CustomCodeAction(source=cleaned_code)]) - editor_ids.assign(body, code_block_id) - body_objects[name] = body - - - if name in event_names: - # The Event metamodel class only takes a name (no callable). - # The code content is stored separately on the code block element - # and will be preserved through round-trip via code blocks. - event = Event(name=name) - # Attach the source code for round-trip fidelity (not part of - # Event's formal metamodel, but needed for BUML export). - event._source_code = cleaned_code - event_objects[name] = event - - if name in guard_names: - # Guard references a code block: create a Condition with source code - condition = Condition(name=name, source=cleaned_code) - condition_objects[name] = condition - - # Determine which element IDs are initial states (targets of transitions from StateInitialNode) - # and which are final states (sources of transitions to StateFinalNode) + target = None + if source_id in comment_nodes: + comment_id = source_id + target = target_id + elif target_id in comment_nodes: + comment_id = target_id + target = source_id + if comment_id and target: + comment_links.setdefault(comment_id, []).append(target) + + # Build Body / Event / Condition objects from StateCodeBlock nodes. + body_objects = {} + event_objects = {} + condition_objects = {} + for node in nodes: + if node.get("type") != "StateCodeBlock": + continue + data = node_data(node) + name = data.get("name") or "" + code_content = data.get("code", "") or "" + if not name: + function_match = re.search(r'def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(', code_content) + if function_match: + name = function_match.group(1) + if not name: + continue + cleaned_code = "\n".join(line for line in code_content.splitlines() if line.strip()) + if name in body_names: + body = Body(name=name, actions=[CustomCodeAction(source=cleaned_code)]) + editor_ids.assign(body, node.get("id")) + body_objects[name] = body + if name in event_names: + event = Event(name=name) + event._source_code = cleaned_code + event_objects[name] = event + if name in guard_names: + condition = Condition(name=name, source=cleaned_code) + condition_objects[name] = condition + + # Determine initial / final state ids from edges. initial_state_ids = set() final_state_ids = set() - for rel in relationships.values(): - if rel.get("type") == "StateTransition": - source_id = rel.get("source", {}).get("element") - target_id = rel.get("target", {}).get("element") - if elements.get(source_id, {}).get("type") == "StateInitialNode": - initial_state_ids.add(target_id) - if elements.get(target_id, {}).get("type") == "StateFinalNode": - final_state_ids.add(source_id) - - # Create states - initial state(s) first to satisfy StateMachine ordering constraint - state_elements = [ - (eid, elem) for eid, elem in elements.items() - if elem.get("type") == "State" - ] - - # Sort so initial states come first - state_elements.sort(key=lambda pair: pair[0] not in initial_state_ids) - - for element_id, element in state_elements: - raw_name = element.get("name", "") + for edge in edges: + if edge.get("type") != "StateTransition": + continue + source_id = edge.get("source") + target_id = edge.get("target") + if (nodes_by_id.get(source_id) or {}).get("type") == "StateInitialNode": + initial_state_ids.add(target_id) + if (nodes_by_id.get(target_id) or {}).get("type") == "StateFinalNode": + final_state_ids.add(source_id) + + # Create states; initial state(s) first to satisfy ordering constraint. + state_nodes = [n for n in nodes if n.get("type") == "State"] + state_nodes.sort(key=lambda n: n.get("id") not in initial_state_ids) + + for node in state_nodes: + node_id = node.get("id") + data = node_data(node) + raw_name = data.get("name", "") or "" if not raw_name.strip(): - logger.warning("State element '%s' has an empty name, using 'unnamed'.", element_id) + logger.warning("State node '%s' has an empty name, using 'unnamed'.", node_id) raw_name = "unnamed" - - is_initial = element_id in initial_state_ids - is_final = element_id in final_state_ids - + is_initial = node_id in initial_state_ids + is_final = node_id in final_state_ids try: state = sm.new_state(name=raw_name, initial=is_initial, final=is_final) except ValueError as e: - # Handle duplicate state names or other validation errors gracefully raise ConversionError(str(e)) from e + editor_ids.assign(state, node_id) + states_by_id[node_id] = state + + # Assign bodies / fallback bodies. + for node in state_nodes: + node_id = node.get("id") + state = states_by_id.get(node_id) + if not state: + continue + data = node_data(node) + for body in data.get("bodies") or []: + body_name = body.get("name") + if body_name in body_objects: + state.set_body(body=body_objects[body_name]) + for body in data.get("fallbackBodies") or []: + body_name = body.get("name") + if body_name in body_objects: + state.set_fallback_body(body=body_objects[body_name]) + + # Create transitions. + for edge in edges: + if edge.get("type") != "StateTransition": + continue + source_id = edge.get("source") + target_id = edge.get("target") - editor_ids.assign(state, element_id) - states_by_id[element_id] = state - - # Assign bodies and fallback bodies to states - for element_id, element in elements.items(): - if element.get("type") == "State": - state = states_by_id.get(element_id) - if not state: - continue - - - for body_id in element.get("bodies", []): - body_element = elements.get(body_id) - if body_element: - body_name = body_element.get("name") - if body_name in body_objects: - state.set_body(body=body_objects[body_name]) - - for fallback_id in element.get("fallbackBodies", []): - fallback_element = elements.get(fallback_id) - if fallback_element: - fallback_name = fallback_element.get("name") - if fallback_name in body_objects: - state.set_fallback_body(body=body_objects[fallback_name]) - - # Create transitions - for relationship_id, relationship in relationships.items(): - if relationship.get("type") == "StateTransition": - source_id = relationship.get("source", {}).get("element") - target_id = relationship.get("target", {}).get("element") - - # Skip transitions from StateInitialNode or to StateFinalNode - if elements.get(source_id, {}).get("type") == "StateInitialNode": - continue - if elements.get(target_id, {}).get("type") == "StateFinalNode": - continue + if (nodes_by_id.get(source_id) or {}).get("type") == "StateInitialNode": + continue + if (nodes_by_id.get(target_id) or {}).get("type") == "StateFinalNode": + continue - source_state = states_by_id.get(source_id) - target_state = states_by_id.get(target_id) + source_state = states_by_id.get(source_id) + target_state = states_by_id.get(target_id) + if not source_state or not target_state: + logger.warning( + "Skipping transition: source '%s' or target '%s' state not found.", + source_id, target_id, + ) + continue - if not source_state or not target_state: - logger.warning( - "Skipping transition: source state '%s' or target state '%s' not found.", - source_id, target_id + transitions_before = len(source_state.transitions) + edge_data = edge.get("data") or {} + event_name = edge_data.get("name", "") + params = edge_data.get("params") + guard_expr = edge_data.get("guard", "") + + guard_condition = None + if guard_expr: + guard_condition = condition_objects.get(guard_expr) + if not guard_condition: + guard_condition = Condition( + name=_sanitize_identifier(guard_expr), + source=guard_expr, ) - continue - - transitions_before = len(source_state.transitions) - event_name = relationship.get("name", "") - params = relationship.get("params") - guard_expr = relationship.get("guard", "") - - # Resolve guard into a Condition object if present - guard_condition = None - if guard_expr: - guard_condition = condition_objects.get(guard_expr) - if not guard_condition: - # Guard is a plain expression string (not a code-block reference). - # Create a Condition from the expression source directly. - guard_condition = Condition( - name=_sanitize_identifier(guard_expr), - source=guard_expr, - ) - condition_objects[guard_expr] = guard_condition - - if event_name: - event = event_objects.get(event_name) - if not event: - # Create a simple event if no code block was associated - event = Event(name=event_name) - event_objects[event_name] = event - - # Build the transition, optionally attaching a guard condition - try: - builder = source_state.when_event(event) - if guard_condition: - builder = builder.with_condition(guard_condition) - builder.go_to(target_state) - except ValueError as e: - raise ConversionError(str(e)) from e - - # Store event_params on the transition for round-trip fidelity. - # The metamodel Transition class does not have a formal event_params - # attribute, so we attach it as an informal attribute. - if params and source_state.transitions: - last_transition = source_state.transitions[-1] - last_transition._event_params = params - - elif guard_condition: - # Transition with guard only (no event) -- use when_condition API - try: - source_state.when_condition(guard_condition).go_to(target_state) - except ValueError as e: - raise ConversionError(str(e)) from e - - if len(source_state.transitions) == transitions_before + 1: - editor_ids.assign(source_state.transitions[-1], relationship.get("id") or relationship_id) - - # Process comments - apply as metadata - for comment_id, comment_text in comment_elements.items(): + condition_objects[guard_expr] = guard_condition + + if event_name: + event = event_objects.get(event_name) + if not event: + event = Event(name=event_name) + event_objects[event_name] = event + try: + builder = source_state.when_event(event) + if guard_condition: + builder = builder.with_condition(guard_condition) + builder.go_to(target_state) + except ValueError as e: + raise ConversionError(str(e)) from e + if params and source_state.transitions: + last_transition = source_state.transitions[-1] + last_transition._event_params = params + elif guard_condition: + try: + source_state.when_condition(guard_condition).go_to(target_state) + except ValueError as e: + raise ConversionError(str(e)) from e + + if len(source_state.transitions) == transitions_before + 1: + editor_ids.assign(source_state.transitions[-1], edge.get("id")) + + # Apply comments. + for comment_id, comment_text in comment_nodes.items(): if comment_id in comment_links: - # Comment is linked to one or more elements - for linked_element_id in comment_links[comment_id]: - if linked_element_id in states_by_id: - state = states_by_id[linked_element_id] - state.metadata = Metadata(description=comment_text) + for linked_id in comment_links[comment_id]: + if linked_id in states_by_id: + states_by_id[linked_id].metadata = Metadata(description=comment_text) else: - # Unlinked comment - add to StateMachine metadata sm.metadata = Metadata(description=comment_text) return sm diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/layout_adoption.py b/besser/utilities/web_modeling_editor/backend/services/converters/layout_adoption.py new file mode 100644 index 000000000..649da8df8 --- /dev/null +++ b/besser/utilities/web_modeling_editor/backend/services/converters/layout_adoption.py @@ -0,0 +1,513 @@ +"""Lay a diagram imported from B-UML out like the diagram it replaces (issue #774). + +A B-UML ``.py`` file carries no layout for Class, Agent and State Machine +diagrams, so importing one rebuilds the diagram on a grid with fresh ids. +``adopt_layout`` takes the diagram the editor already has and the freshly +imported one (both v4 wire shape, ``{nodes, edges}``) and returns the imported +content laid out like the existing diagram: + +- a node is matched to an existing node by id when the import kept it, else by + type and name (case-insensitive) inside the matched parent, duplicates in + order. A matched node takes the existing id and position, and the existing + size unless its new content needs more room; +- a node renamed in the file is matched to its old self only when, among the + unmatched nodes of its type and parent, it is the one on each side connected + to the same matched neighbours by the same edges (type, direction, content); + any other rename reads as a removal plus an addition; +- member rows (class attributes and methods, agent state bodies) and agent + components keep their existing ids, matched by name inside their match; +- an edge is matched by id, else by type and (matched) ends, preferring one + with the same content. A matched edge takes the existing id and handles, and + its bend points while neither end changed size; +- a new top-level node is placed on the first free slot next to a matched + neighbour it is connected to, else right of the diagram. + +Content always comes from the import. Nothing here reads B-UML. +""" + +import copy +import json +from collections import defaultdict +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple + +# Diagram types whose B-UML import rebuilds the layout and that adopt_layout handles. +# BPMN, Component and Deployment diagrams keep their layout through B-UML already. +LAYOUT_ADOPTION_DIAGRAM_TYPES = frozenset({"ClassDiagram", "AgentDiagram", "StateMachineDiagram"}) + +# Space left between a placed node and its neighbours, in canvas pixels (the grid gap of the converters). +PLACEMENT_GAP = 60 +# How many rings of slots around a neighbour are tried before a new node goes right of the diagram. +MAX_PLACEMENT_RINGS = 8 +# Slot directions around a neighbour, nearest first: right, below, left, above, then the corners. +_SLOT_DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)) + +# Node data lists whose rows carry their own ids, and the row fields that identify a row. +_ROW_FIELDS = { + "attributes": ("name",), + "methods": ("name",), + "bodies": ("replyType", "name"), + "fallbackBodies": ("replyType", "name"), +} +# Edge data fields that are layout, not content. +_EDGE_LAYOUT_FIELDS = ("points", "isManuallyLayouted") + + +def adopt_layout(existing: Dict[str, Any], imported: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: + """Return ``imported`` laid out like ``existing``, and a report of what was matched. + + Both arguments are v4 diagram models (``nodes`` and ``edges`` lists); neither + is modified. The report holds ``matched`` (nodes that kept their id and + place), ``renamed``, ``added`` (new top-level nodes and the neighbour they + were placed next to), ``notInImport`` (existing nodes the import no longer + has), and the edge counts ``edgesKept``, ``edgesRerouted`` (kept, bend + points dropped because an end changed size) and ``edgesAdded``. + """ + result = copy.deepcopy(imported) + old_nodes = {n["id"]: n for n in _nodes(existing)} + new_nodes = _nodes(result) + taken_ids = _all_ids(result) + + node_map = _match_nodes(list(old_nodes.values()), new_nodes, taken_ids) + renamed = _match_renames(existing, result, old_nodes, new_nodes, node_map, taken_ids) + + id_map = dict(node_map) + resized = set() + for node in new_nodes: + old = old_nodes.get(node_map.get(node["id"])) + if old is None: + continue + _keep_place(node, old, node_map, resized) + for field, key_fields in _ROW_FIELDS.items(): + id_map.update(_match_items( + _rows(old, field), _rows(node, field), taken_ids, + key=lambda row, fields=key_fields: tuple(_norm(row.get(f)) for f in fields), + )) + id_map.update(_match_components(existing.get("components"), result.get("components"), taken_ids)) + result = _replace_ids(result, id_map) + + edge_map, edge_report = _match_edges(existing, result, resized, taken_ids) + result = _replace_ids(result, edge_map) + + added = _place_new_nodes(result, set(node_map.values())) + + matched_old = set(node_map.values()) + report = { + "matched": len(node_map), + "renamed": [ + {"id": old_id, "type": old_nodes[old_id]["type"], + "from": _name(old_nodes[old_id]), "to": name} + for old_id, name in renamed + ], + "added": added, + "notInImport": [ + _describe(n) for n in old_nodes.values() + if n["id"] not in matched_old and (n.get("parentId") is None or n.get("parentId") in matched_old) + ], + **edge_report, + } + return result, report + + +# --------------------------------------------------------------------------- +# Matching +# --------------------------------------------------------------------------- + +def _match_nodes(old_nodes: List[dict], new_nodes: List[dict], taken_ids: set) -> Dict[str, str]: + """New node id -> existing node id: by id first, then by type and name inside matched parents.""" + old_by_id = {n["id"]: n for n in old_nodes} + mapping = {n["id"]: n["id"] for n in new_nodes + if n["id"] in old_by_id and old_by_id[n["id"]]["type"] == n["type"]} + + old_children = _children_index(old_nodes, lambda n: n.get("parentId")) + new_children = _children_index(new_nodes, lambda n: n.get("parentId")) + + def pair(old_parent: Optional[str], new_parent: Optional[str]) -> None: + mapping.update(_match_items( + old_children.get(old_parent, []), new_children.get(new_parent, []), taken_ids, + key=_node_key, already=mapping, + )) + for node in new_children.get(new_parent, []): + if node["id"] in mapping and mapping[node["id"]] in old_children: + pair(mapping[node["id"]], node["id"]) + + pair(None, None) + return mapping + + +def _match_renames(existing: dict, result: dict, old_nodes: Dict[str, dict], new_nodes: List[dict], + node_map: Dict[str, str], taken_ids: set) -> List[Tuple[str, str]]: + """Pair a renamed node with its old self when nothing else could be meant (see module doc).""" + matched_old = set(node_map.values()) + old_left = defaultdict(list) + for n in old_nodes.values(): + if n["id"] not in matched_old and n["id"] not in taken_ids: + old_left[(n.get("parentId"), n["type"])].append(n) + new_left = defaultdict(list) + for n in new_nodes: + if n["id"] not in node_map: + parent = n.get("parentId") + new_left[(node_map.get(parent, parent), n["type"])].append(n) + + old_signatures = _neighbour_signatures(_edges(existing), lambda node_id: node_id if node_id in matched_old else None) + new_signatures = _neighbour_signatures(_edges(result), node_map.get) + renamed = [] + for slot, olds in old_left.items(): + old_by_signature = defaultdict(list) + for old in olds: + if old_signatures.get(old["id"]): + old_by_signature[old_signatures[old["id"]]].append(old) + new_by_signature = defaultdict(list) + for new in new_left.get(slot, []): + if new_signatures.get(new["id"]): + new_by_signature[new_signatures[new["id"]]].append(new) + for signature, news in new_by_signature.items(): + olds_alike = old_by_signature.get(signature, []) + if len(news) == 1 and len(olds_alike) == 1: + node_map[news[0]["id"]] = olds_alike[0]["id"] + renamed.append((olds_alike[0]["id"], _name(news[0]))) + return renamed + + +def _neighbour_signatures(edges: Iterable[dict], resolve: Callable[[str], Optional[str]]) -> Dict[str, frozenset]: + """Node id -> the (edge type, direction, neighbour, content) of its edges to resolvable neighbours.""" + signatures = defaultdict(set) + for edge in edges: + source, target = edge.get("source"), edge.get("target") + if resolve(target) is not None: + signatures[source].add((edge.get("type"), "out", resolve(target), _edge_content(edge))) + if resolve(source) is not None: + signatures[target].add((edge.get("type"), "in", resolve(source), _edge_content(edge))) + return {node_id: frozenset(sig) for node_id, sig in signatures.items()} + + +def _match_components(old: Any, new: Any, taken_ids: set) -> Dict[str, str]: + """Agent components (intents, LLMs, ...) keep their ids, matched by type and name; intent bodies by owner.""" + if not isinstance(old, dict) or not isinstance(new, dict): + return {} + old_items = [c for c in old.values() if isinstance(c, dict) and c.get("id")] + new_items = [c for c in new.values() if isinstance(c, dict) and c.get("id")] + old_by_id = {c["id"]: c for c in old_items} + mapping = {c["id"]: c["id"] for c in new_items + if c["id"] in old_by_id and old_by_id[c["id"]].get("type") == c.get("type")} + mapping.update(_match_items( + [c for c in old_items if not c.get("owner")], [c for c in new_items if not c.get("owner")], + taken_ids, key=_node_key, already=mapping, + )) + old_owned = _children_index([c for c in old_items if c.get("owner")], lambda c: c["owner"]) + new_owned = _children_index([c for c in new_items if c.get("owner")], lambda c: c["owner"]) + for new_owner, items in new_owned.items(): + if new_owner in mapping: + mapping.update(_match_items(old_owned.get(mapping[new_owner], []), items, taken_ids, + key=_node_key, already=mapping)) + return mapping + + +def _match_items(old_items: List[dict], new_items: List[dict], taken_ids: set, key: Callable[[dict], Any], + already: Optional[Dict[str, str]] = None) -> Dict[str, str]: + """New id -> old id for items with equal keys, in order. + + An old id is given once, and never when the import already uses it for something else. + """ + already = already or {} + used = set(already.values()) + buckets = defaultdict(list) + for item in old_items: + if item.get("id") and item["id"] not in used and item["id"] not in taken_ids: + buckets[key(item)].append(item) + mapping = {} + for item in new_items: + if not item.get("id") or item["id"] in already: + continue + candidates = [c for c in buckets.get(key(item), []) if c["id"] not in used] + if candidates: + mapping[item["id"]] = candidates[0]["id"] + used.add(candidates[0]["id"]) + return mapping + + +def _match_edges(existing: dict, result: dict, resized: set, taken_ids: set) -> Tuple[Dict[str, str], Dict[str, int]]: + """Give matched edges their existing id and layout; returns (new id -> old id, edge counts).""" + old_edges = list(_edges(existing)) + new_edges = list(_edges(result)) + old_by_id = {e["id"]: e for e in old_edges if e.get("id")} + mapping = {e["id"]: e["id"] for e in new_edges + if e.get("id") in old_by_id and _edge_ends(old_by_id[e["id"]]) == _edge_ends(e)} + # Same ends and content first (two transitions between the same states differ by intent), then same ends. + for key in (lambda e: (_edge_ends(e), _edge_content(e)), _edge_ends): + mapping.update(_match_items(old_edges, new_edges, taken_ids, key=key, already=mapping)) + + kept = rerouted = 0 + for edge in new_edges: + old = old_by_id.get(mapping.get(edge.get("id"))) + if old is None: + continue + kept += 1 + for handle in ("sourceHandle", "targetHandle"): + if old.get(handle): + edge[handle] = old[handle] + data = edge.setdefault("data", {}) + if {edge.get("source"), edge.get("target")} & resized: + rerouted += 1 + data["points"] = [] + data.pop("isManuallyLayouted", None) + continue + old_data = old.get("data") or {} + for field in _EDGE_LAYOUT_FIELDS: + if field in old_data: + data[field] = copy.deepcopy(old_data[field]) + else: + data.pop(field, None) + data.setdefault("points", []) + return mapping, {"edgesKept": kept, "edgesRerouted": rerouted, "edgesAdded": len(new_edges) - kept} + + +# --------------------------------------------------------------------------- +# Layout +# --------------------------------------------------------------------------- + +def _keep_place(node: dict, old: dict, node_map: Dict[str, str], resized: set) -> None: + """Give a matched node the existing position, and the existing size unless its content needs more.""" + parent = node.get("parentId") + if node_map.get(parent, parent) == old.get("parentId"): + node["position"] = dict(old.get("position") or node.get("position") or {"x": 0, "y": 0}) + old_w, old_h = _size(old) + new_w, new_h = _size(node) + width, height = max(old_w, new_w), max(old_h, new_h) + if (width, height) != (old_w, old_h): + resized.add(old["id"]) + node["width"], node["height"] = width, height + node["measured"] = {"width": width, "height": height} + + +def _place_new_nodes(result: dict, kept_ids: set) -> List[Dict[str, Any]]: + """Move every new top-level node next to a neighbour; returns what was placed where.""" + nodes = {n["id"]: n for n in _nodes(result)} + top_level = [n for n in nodes.values() if n.get("parentId") is None] + new_top = [n for n in top_level if n["id"] not in kept_ids] + taken = [_bounds(n) for n in top_level if n["id"] in kept_ids] + if not taken: + # Nothing matched: the existing diagram tells nothing about where things go. + return [{**_describe(n), "placedNextTo": None} for n in new_top] + + def top_ancestor(node_id: Optional[str]) -> Optional[str]: + seen = set() + while node_id in nodes and nodes[node_id].get("parentId") and node_id not in seen: + seen.add(node_id) + node_id = nodes[node_id]["parentId"] + return node_id if node_id in nodes else None + + neighbours = defaultdict(list) + for edge in _edges(result): + a, b = top_ancestor(edge.get("source")), top_ancestor(edge.get("target")) + if a and b and a != b: + neighbours[a].append(b) + neighbours[b].append(a) + + placed: List[Dict[str, Any]] = [] + placed_ids = set() + for node in new_top: + candidates = neighbours.get(node["id"], []) + anchor_id = next((n for n in candidates if n in kept_ids), None) \ + or next((n for n in candidates if n in placed_ids), None) + width, height = _size(node) + slot = _free_slot(width, height, _bounds(nodes[anchor_id]), taken) if anchor_id else None + if slot is None: + anchor_id = None + slot = _slot_right_of(width, height, taken) + node["position"] = {"x": slot["x"], "y": slot["y"]} + taken.append(slot) + placed_ids.add(node["id"]) + placed.append({**_describe(node), "placedNextTo": _name(nodes[anchor_id]) if anchor_id else None}) + return placed + + +def _free_slot(width: float, height: float, anchor: dict, taken: List[dict]) -> Optional[dict]: + """The first slot around ``anchor``, nearest ring first, that overlaps nothing in ``taken``.""" + step_x = max(anchor["width"], width) + PLACEMENT_GAP + step_y = max(anchor["height"], height) + PLACEMENT_GAP + for ring in range(1, MAX_PLACEMENT_RINGS + 1): + for dx, dy in _SLOT_DIRECTIONS: + slot = {"x": anchor["x"] + dx * ring * step_x, "y": anchor["y"] + dy * ring * step_y, + "width": width, "height": height} + if not any(_overlaps(slot, other) for other in taken): + return slot + return None + + +def _slot_right_of(width: float, height: float, taken: List[dict]) -> dict: + """A slot right of everything in ``taken``, moved down until it overlaps nothing.""" + slot = {"x": max(t["x"] + t["width"] for t in taken) + PLACEMENT_GAP, + "y": min(t["y"] for t in taken), "width": width, "height": height} + while any(_overlaps(slot, other) for other in taken): + slot["y"] += height + PLACEMENT_GAP + return slot + + +def _overlaps(a: dict, b: dict) -> bool: + """True when the boxes are closer than half the placement gap.""" + gap = PLACEMENT_GAP / 2 + return not (a["x"] + a["width"] + gap <= b["x"] or b["x"] + b["width"] + gap <= a["x"] + or a["y"] + a["height"] + gap <= b["y"] or b["y"] + b["height"] + gap <= a["y"]) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _nodes(model: dict) -> List[dict]: + return [n for n in model.get("nodes") or [] if isinstance(n, dict) and n.get("id")] + + +def _edges(model: dict) -> List[dict]: + return [e for e in model.get("edges") or [] if isinstance(e, dict) and e.get("id")] + + +def _rows(node: dict, field: str) -> List[dict]: + rows = (node.get("data") or {}).get(field) + return [r for r in rows if isinstance(r, dict)] if isinstance(rows, list) else [] + + +def _children_index(items: Iterable[dict], parent_of: Callable[[dict], Optional[str]]) -> Dict[Optional[str], list]: + index = defaultdict(list) + for item in items: + index[parent_of(item)].append(item) + return index + + +def _name(item: dict) -> str: + data = item.get("data") + name = data.get("name") if isinstance(data, dict) else item.get("name") + return name if isinstance(name, str) else "" + + +def _norm(value: Any) -> Any: + return value.strip().casefold() if isinstance(value, str) else value + + +def _node_key(item: dict) -> tuple: + return item.get("type"), _norm(_name(item)) + + +def _edge_ends(edge: dict) -> tuple: + return edge.get("type"), edge.get("source"), edge.get("target") + + +def _edge_content(edge: dict) -> str: + data = {k: v for k, v in (edge.get("data") or {}).items() if k not in _EDGE_LAYOUT_FIELDS} + return json.dumps(data, sort_keys=True, default=str) + + +def _size(node: dict) -> Tuple[float, float]: + measured = node.get("measured") or {} + width = node.get("width") or measured.get("width") or 0 + height = node.get("height") or measured.get("height") or 0 + return width, height + + +def _bounds(node: dict) -> dict: + position = node.get("position") or {} + width, height = _size(node) + return {"x": position.get("x", 0), "y": position.get("y", 0), "width": width, "height": height} + + +def _describe(node: dict) -> Dict[str, Any]: + return {"id": node["id"], "type": node.get("type"), "name": _name(node)} + + +def _all_ids(value: Any) -> set: + """Every ``id`` value and ``components`` key in a model.""" + ids = set() + stack = [value] + while stack: + item = stack.pop() + if isinstance(item, dict): + if isinstance(item.get("id"), str): + ids.add(item["id"]) + stack.extend(item.values()) + elif isinstance(item, list): + stack.extend(item) + return ids + + +def _replace_ids(value: Any, mapping: Dict[str, str]) -> Any: + """``value`` with every string (and dict key) found in ``mapping`` replaced: ids and references to them.""" + if not mapping: + return value + if isinstance(value, str): + return mapping.get(value, value) + if isinstance(value, list): + return [_replace_ids(v, mapping) for v in value] + if isinstance(value, dict): + return {mapping.get(k, k): _replace_ids(v, mapping) for k, v in value.items()} + return value + + +# --------------------------------------------------------------------------- +# Import endpoint glue +# --------------------------------------------------------------------------- + +def adopt_existing_layout(existing_model: str, imported: Dict[str, Any], + diagram_type: str) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: + """Lay ``imported`` out like the editor's ``existing_model`` (JSON text); returns (model, warnings). + + ``existing_model`` is the diagram being updated: a v4 model, or a project + diagram entry holding one under ``model``. When it cannot be used (not JSON, + not a v4 model, another diagram type, a type without layout adoption) the + import is returned unchanged with a ``layout-not-adopted`` warning saying why. + Otherwise the warnings report the outcome: ``layout-adopted`` (a summary), + ``element-renamed``, ``element-added`` and ``element-not-in-import``. + """ + existing, reason = _read_existing_model(existing_model, diagram_type) + if existing is None: + return imported, [{"code": "layout-not-adopted", + "message": f"The diagram is imported with a new layout: {reason}"}] + + model, report = adopt_layout(existing, imported) + warnings: List[Dict[str, Any]] = [{ + "code": "layout-adopted", + "message": (f"Kept the place and id of {report['matched']} element(s) of the existing diagram; " + f"{len(report['added'])} new, {len(report['notInImport'])} not in the imported file."), + "matched": report["matched"], + "edgesKept": report["edgesKept"], + "edgesRerouted": report["edgesRerouted"], + "edgesAdded": report["edgesAdded"], + }] + for item in report["renamed"]: + warnings.append({ + "code": "element-renamed", + "message": f"{item['type']} '{item['from']}' is read as renamed to '{item['to']}' and keeps its place.", + "elementId": item["id"], "type": item["type"], "from": item["from"], "name": item["to"], + }) + for item in report["added"]: + where = f"next to '{item['placedNextTo']}'" if item["placedNextTo"] else "right of the diagram" + warnings.append({ + "code": "element-added", + "message": f"New {item['type']} '{item['name']}' placed {where}.", + "elementId": item["id"], "type": item["type"], "name": item["name"], + "placedNextTo": item["placedNextTo"], + }) + for item in report["notInImport"]: + warnings.append({ + "code": "element-not-in-import", + "message": f"{item['type']} '{item['name']}' of the existing diagram is not in the imported file.", + "elementId": item["id"], "type": item["type"], "name": item["name"], + }) + return model, warnings + + +def _read_existing_model(text: str, diagram_type: str) -> Tuple[Optional[Dict[str, Any]], str]: + """The v4 model in ``text``, or None and the reason it cannot be used.""" + if diagram_type not in LAYOUT_ADOPTION_DIAGRAM_TYPES: + return None, f"keeping the layout of an existing {diagram_type} is not supported." + try: + value = json.loads(text) + except (TypeError, ValueError): + return None, "the existing diagram sent with the file is not valid JSON." + if isinstance(value, dict) and isinstance(value.get("model"), dict): + value = value["model"] + if not isinstance(value, dict) or not isinstance(value.get("nodes"), list): + return None, "the existing diagram sent with the file is not a diagram model with nodes." + existing_type = value.get("type") + if existing_type and existing_type != diagram_type: + return None, f"the existing diagram is a {existing_type}, the file holds a {diagram_type}." + return value, "" diff --git a/besser/utilities/web_modeling_editor/backend/services/exceptions.py b/besser/utilities/web_modeling_editor/backend/services/exceptions.py index c123ca6df..d851dc5a6 100644 --- a/besser/utilities/web_modeling_editor/backend/services/exceptions.py +++ b/besser/utilities/web_modeling_editor/backend/services/exceptions.py @@ -53,3 +53,13 @@ class CodeValidationError(ValidationError): other user-input validation failure. """ pass + + +class LegacyDiagramFormatError(ConversionError): + """Raised when a UML diagram arrives in the legacy v3 editor format. + + The converters read only the v4 ``{nodes, edges}`` shape; a v3 + ``{elements, relationships}`` payload would otherwise convert to an empty + model. Subclasses :class:`ConversionError`, so it maps to HTTP 400. + """ + pass diff --git a/besser/utilities/web_modeling_editor/backend/services/generation/agents.py b/besser/utilities/web_modeling_editor/backend/services/generation/agents.py index 06977ecc0..bc7539ff3 100644 --- a/besser/utilities/web_modeling_editor/backend/services/generation/agents.py +++ b/besser/utilities/web_modeling_editor/backend/services/generation/agents.py @@ -33,6 +33,8 @@ delivery_traces, ) from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import ( + agent_diagram_without_states, + agent_without_states_message, extract_openai_api_key, handle_configuration_variants, handle_multi_language_generation, @@ -182,6 +184,8 @@ def _with_traces(output: GeneratedOutput, generators: List[BAFGenerator]) -> Gen async def generate_agent_output(json_data: dict) -> GeneratedOutput: """Generate an agent diagram's ZIP, dispatching on its config (languages, variations, ...).""" + if agent_diagram_without_states(json_data.get('model')): + raise ValidationError(agent_without_states_message(json_data.get('title'))) config = json_data.get('config', {}) config_yaml: Optional[str] = json_data.get('configYaml') if isinstance(json_data.get('configYaml'), str) else None sanitized_config_log = ( diff --git a/besser/utilities/web_modeling_editor/backend/services/generation/dispatch.py b/besser/utilities/web_modeling_editor/backend/services/generation/dispatch.py index bf2adf477..da863a327 100644 --- a/besser/utilities/web_modeling_editor/backend/services/generation/dispatch.py +++ b/besser/utilities/web_modeling_editor/backend/services/generation/dispatch.py @@ -90,6 +90,7 @@ attach_governance_to_agents, ) from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import ( + agent_diagram_without_states, collect_agents_from_diagrams, normalize_personalization_mapping, ) @@ -415,7 +416,11 @@ async def _handle_deployment_project_generation( for entry in input_data.diagrams.get("AgentDiagram", []): entry_dict = entry.model_dump() model = entry_dict.get("model") - if not entry_dict.get("id") or not (isinstance(model, dict) and model.get("elements")): + if agent_diagram_without_states(model): + # One agent still being drawn must not block Docker Compose for the project. + logger.warning("Skipping agent diagram '%s': it has no states.", entry_dict.get("title") or "Agent") + continue + if not entry_dict.get("id") or not (isinstance(model, dict) and model.get("nodes")): continue agent_config = entry_dict.get("config") if isinstance(agent_config, dict) and isinstance(agent_config.get("personalizationMapping"), list): @@ -552,7 +557,10 @@ def _extract_reference_class_diagram(json_data: dict): model_payload = reference_data title = reference_data.get("title") - if not isinstance(model_payload, dict) or "elements" not in model_payload: + # The reference diagram arrives in the v4 wire shape (``{nodes, edges}``) + # — the same gate validation_router applies before calling + # ``process_class_diagram``. + if not isinstance(model_payload, dict) or "nodes" not in model_payload: return None return { diff --git a/besser/utilities/web_modeling_editor/backend/services/reverse_engineering/ai_reverse.py b/besser/utilities/web_modeling_editor/backend/services/reverse_engineering/ai_reverse.py index de6bab8ca..2f86fc901 100644 --- a/besser/utilities/web_modeling_editor/backend/services/reverse_engineering/ai_reverse.py +++ b/besser/utilities/web_modeling_editor/backend/services/reverse_engineering/ai_reverse.py @@ -534,13 +534,11 @@ def _spec_to_model(spec: dict) -> tuple[Optional[DomainModel], list[str]]: def _with_enumerations(spec: dict) -> dict: """``convert_spec_json_to_buml``'s diagram plus the spec's enumerations, which that format lacks.""" diagram = convert_spec_json_to_buml(spec, title=spec["systemName"]) - elements = diagram["model"]["elements"] for n, enum in enumerate(spec["enumerations"], start=1): - literal_ids = [] - for m, literal in enumerate(enum["literals"], start=1): - literal_id = f"enum-{n}-literal-{m}" - elements[literal_id] = {"id": literal_id, "type": "ClassAttribute", "owner": f"enum-{n}", "name": literal} - literal_ids.append(literal_id) - elements[f"enum-{n}"] = {"id": f"enum-{n}", "type": "Enumeration", "name": enum["name"], - "attributes": literal_ids, "methods": []} + literals = [{"id": f"enum-{n}-literal-{m}", "name": literal} + for m, literal in enumerate(enum["literals"], start=1)] + diagram["model"]["nodes"].append({ + "id": f"enum-{n}", "type": "class", "position": {"x": 0, "y": 0}, + "data": {"name": enum["name"], "stereotype": "Enumeration", "attributes": literals, "methods": []}, + }) return diagram diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/model_assembly.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/model_assembly.py index 29eab0c70..d91fa2c84 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/model_assembly.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/model_assembly.py @@ -573,8 +573,16 @@ def _collect_diagrams_of_type( def _element_ids(diagram: DiagramInput) -> set: - elements = (diagram.model or {}).get("elements") if isinstance(diagram.model, dict) else None - return set(elements) if isinstance(elements, dict) else set() + """The ids of a class diagram's classes and their attribute and method rows.""" + nodes = (diagram.model or {}).get("nodes") if isinstance(diagram.model, dict) else None + ids = set() + for node in nodes if isinstance(nodes, list) else (): + if not isinstance(node, dict): + continue + data = node.get("data") if isinstance(node.get("data"), dict) else {} + rows = [*(data.get("attributes") or []), *(data.get("methods") or [])] + ids.update(item.get("id") for item in (node, *rows) if isinstance(item, dict) and item.get("id")) + return ids def _strings(value) -> set: diff --git a/besser/utilities/web_modeling_editor/backend/services/svg_postprocess.py b/besser/utilities/web_modeling_editor/backend/services/svg_postprocess.py index 43c765b66..62d1b806f 100644 --- a/besser/utilities/web_modeling_editor/backend/services/svg_postprocess.py +++ b/besser/utilities/web_modeling_editor/backend/services/svg_postprocess.py @@ -1,6 +1,6 @@ """Post-processing for SVG diagrams returned by the headless render service. -The WME Node renderer (Apollon + ELK) sizes the root ```` to the diagram's +The WME Node renderer (headless editor + ELK) sizes the root ```` to the diagram's node/edge geometry, but it does **not** account for association-end *labels* (role names and multiplicities) that are drawn outside that box. For a self-referential association the loop is routed on the node's left edge and its diff --git a/besser/utilities/web_modeling_editor/backend/services/utils/agent_config_recommendation_utils.py b/besser/utilities/web_modeling_editor/backend/services/utils/agent_config_recommendation_utils.py index 970521f57..d157f59af 100644 --- a/besser/utilities/web_modeling_editor/backend/services/utils/agent_config_recommendation_utils.py +++ b/besser/utilities/web_modeling_editor/backend/services/utils/agent_config_recommendation_utils.py @@ -22,7 +22,7 @@ "font": ["sans", "serif", "monospace", "neutral", "grotesque", "condensed", "hyperlegible", "lexend", "dyslexia", "verdana", "fredoka"], "alignment": ["left", "center", "justify"], "color": [ - "var(--apollon-primary-contrast)", + "var(--besser-primary-contrast)", "#000000", "#ffffff", "#1a73e8", @@ -88,7 +88,7 @@ def load_default_agent_recommendation_config() -> Dict[str, Any]: "font": "sans", "lineSpacing": 1.5, "alignment": "left", - "color": "var(--apollon-primary-contrast)", + "color": "var(--besser-primary-contrast)", "contrast": "medium", }, "voiceStyle": { diff --git a/besser/utilities/web_modeling_editor/backend/services/utils/agent_generation_utils.py b/besser/utilities/web_modeling_editor/backend/services/utils/agent_generation_utils.py index 57b025d8f..1e613d0b0 100644 --- a/besser/utilities/web_modeling_editor/backend/services/utils/agent_generation_utils.py +++ b/besser/utilities/web_modeling_editor/backend/services/utils/agent_generation_utils.py @@ -24,6 +24,9 @@ OUTPUT_DIR_NAME, ) from besser.utilities.web_modeling_editor.backend.services.converters import process_agent_diagram +from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_not_legacy_payload, +) AgentZipGenerator = Callable[[Any, Optional[Dict[str, Any]]], Tuple[io.BytesIO, str]] @@ -142,9 +145,16 @@ def normalize_personalization_mapping( ), ) + ensure_not_legacy_payload( + user_profile_payload, "UserDiagram", f"personalizationMapping[{index}].user_profile", + ) + agent_model_json = entry.get('agent_model') + ensure_not_legacy_payload( + agent_model_json, "AgentDiagram", f"personalizationMapping[{index}].agent_model", + ) + simplified_profile = profile_generator_fn(user_profile_payload) - agent_model_json = entry.get('agent_model') agent_model_buml = None if isinstance(agent_model_json, dict): mapping_payload = dict(json_data) @@ -422,6 +432,16 @@ def handle_personalized_agent( return zip_buffer, file_name +def agent_diagram_without_states(model: Any) -> bool: + """True for an agent diagram that defines components (intents, LLMs, ...) + but no states: unlike an empty placeholder, it cannot become an agent.""" + return isinstance(model, dict) and not model.get("nodes") and bool(model.get("components")) + + +def agent_without_states_message(title: Any) -> str: + return f"Agent diagram '{title or 'Agent'}' has no states: add at least one state to generate the agent." + + def collect_agents_from_diagrams( agent_diagrams: List[Any], default_config: Any = None, @@ -463,9 +483,13 @@ def collect_agents_from_diagrams( model = entry_dict.get("model") if not model: continue - # The deploy endpoint additionally required a non-empty ``elements`` map; - # treat that as the unified contract so both paths reject blank diagrams. - if isinstance(model, dict) and not model.get("elements"): + # The deploy endpoint additionally required a non-empty ``nodes`` list; + # treat that as the unified contract so both paths skip blank diagrams. + if agent_diagram_without_states(model): + # One agent still being drawn must not block the other diagrams of the project. + logger.warning("Skipping agent diagram '%s': it has no states.", entry_dict.get("title") or "Agent") + continue + if isinstance(model, dict) and not model.get("nodes"): continue # Every agent diagram of the project is read, used by the GUI or not: a transition # BAF would refuse is logged, not raised, so one stale diagram does not block the app. diff --git a/besser/utilities/web_modeling_editor/backend/services/utils/user_profile_utils.py b/besser/utilities/web_modeling_editor/backend/services/utils/user_profile_utils.py index 5b55cd0ef..4ecf038e0 100644 --- a/besser/utilities/web_modeling_editor/backend/services/utils/user_profile_utils.py +++ b/besser/utilities/web_modeling_editor/backend/services/utils/user_profile_utils.py @@ -74,7 +74,7 @@ def _container_parent_by_child() -> dict[str, str]: def reinject_hidden_containers(payload: dict) -> dict: """Insert hidden grouping containers (Accessibility, Competence) into a - raw UserDiagram JSON payload before it reaches process_object_diagram. + raw v4 UserDiagram payload before it reaches process_object_diagram. The canvas omits these containers: it connects User→Disability directly. This rewrites every such direct link to User→Container→Child, mirroring @@ -85,7 +85,7 @@ def reinject_hidden_containers(payload: dict) -> dict: Args: payload: The full ``input_data.model_dump()`` dict with a ``"model"`` - key holding the raw ``UserDiagram`` model. + key holding the raw ``UserDiagram`` model (``nodes`` / ``edges``). Returns: The same dict with the ``"model"`` key replaced by the re-injected @@ -95,36 +95,32 @@ def reinject_hidden_containers(payload: dict) -> dict: if not isinstance(model, dict) or model.get("type") != "UserDiagram": return payload - elements: dict = model.get("elements", {}) - relationships: dict = model.get("relationships", {}) - if not elements or not relationships: + nodes = [node for node in model.get("nodes") or [] if isinstance(node, dict)] + edges = [edge for edge in model.get("edges") or [] if isinstance(edge, dict)] + if not nodes or not edges: return payload box_class: dict[str, str] = { - eid: el["className"] - for eid, el in elements.items() - if el and el.get("type") == "UserModelName" and el.get("className") + node["id"]: _node_data(node)["className"] + for node in nodes + if node.get("type") == "UserModelName" and node.get("id") and _node_data(node).get("className") } - needs_reinject = any( - (box_class.get(rel.get("source", {}).get("element", "")) == "User" - and box_class.get(rel.get("target", {}).get("element", "")) in _HIDDEN_CONTAINER_PARENT) - or - (box_class.get(rel.get("target", {}).get("element", "")) == "User" - and box_class.get(rel.get("source", {}).get("element", "")) in _HIDDEN_CONTAINER_PARENT) - for rel in relationships.values() - if rel - ) - if not needs_reinject: + def direct_link(edge: dict) -> bool: + ends = box_class.get(edge.get("source")), box_class.get(edge.get("target")) + return (ends[0] == "User" and ends[1] in _HIDDEN_CONTAINER_PARENT) or ( + ends[1] == "User" and ends[0] in _HIDDEN_CONTAINER_PARENT) + + if not any(direct_link(edge) for edge in edges): return payload - new_elements = dict(elements) - new_relationships: dict = {} + new_nodes = list(nodes) + new_edges: list = [] container_box_for: dict[tuple, str] = {} _seq = [0] # Object names must be unique across the diagram. Every profile gets its own container, # so take the first free ``_``: accessibility_1, accessibility_2, ... - used_names = {el.get("name") for el in elements.values() if isinstance(el, dict) and el.get("name")} + used_names = {_node_data(node).get("name") for node in nodes if _node_data(node).get("name")} def _unique_container_name(container_class: str) -> str: base = f"{container_class[0].lower()}{container_class[1:]}" @@ -141,60 +137,71 @@ def _ensure_container(user_box_id: str, container_class: str) -> str: return container_box_for[key] box_id = f"reinject_{container_class.lower()}_{_seq[0]}" _seq[0] += 1 - new_elements[box_id] = { - "type": "UserModelName", + new_nodes.append({ "id": box_id, - "name": _unique_container_name(container_class), - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 50}, - "attributes": [], - "methods": [], - "className": container_class, - } + "type": "UserModelName", + "position": {"x": 0, "y": 0}, + "width": 200, + "height": 50, + "data": { + "name": _unique_container_name(container_class), + "className": container_class, + "attributes": [], + "methods": [], + }, + }) container_box_for[key] = box_id return box_id def _make_link(link_id: str, src_id: str, tgt_id: str) -> dict: return { "id": link_id, - "type": "ObjectLink", - "source": {"element": src_id, "direction": "Right", - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}}, - "target": {"element": tgt_id, "direction": "Left", - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}}, - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}, - "name": "", - "path": [{"x": 100, "y": 10}, {"x": 0, "y": 10}], - "isManuallyLayouted": False, + "type": "UserModelLink", + "source": src_id, + "target": tgt_id, + "sourceHandle": "right", + "targetHandle": "left", + "data": {"name": "", "points": []}, } - for rel_id, rel in relationships.items(): - src_id = rel.get("source", {}).get("element", "") - tgt_id = rel.get("target", {}).get("element", "") - src_cls = box_class.get(src_id, "") - tgt_cls = box_class.get(tgt_id, "") + for edge in edges: + src_id, tgt_id = edge.get("source"), edge.get("target") + src_cls, tgt_cls = box_class.get(src_id, ""), box_class.get(tgt_id, "") if src_cls == "User" and tgt_cls in _HIDDEN_CONTAINER_PARENT: - container_cls = _HIDDEN_CONTAINER_PARENT[tgt_cls] - container_id = _ensure_container(src_id, container_cls) - new_relationships[rel_id] = _make_link(rel_id, src_id, container_id) + container_id = _ensure_container(src_id, _HIDDEN_CONTAINER_PARENT[tgt_cls]) + new_edges.append(_make_link(edge.get("id"), src_id, container_id)) child_link_id = f"reinject_link_{_seq[0]}" _seq[0] += 1 - new_relationships[child_link_id] = _make_link(child_link_id, container_id, tgt_id) + new_edges.append(_make_link(child_link_id, container_id, tgt_id)) elif tgt_cls == "User" and src_cls in _HIDDEN_CONTAINER_PARENT: - container_cls = _HIDDEN_CONTAINER_PARENT[src_cls] - container_id = _ensure_container(tgt_id, container_cls) - new_relationships[rel_id] = _make_link(rel_id, container_id, tgt_id) + container_id = _ensure_container(tgt_id, _HIDDEN_CONTAINER_PARENT[src_cls]) + new_edges.append(_make_link(edge.get("id"), container_id, tgt_id)) child_link_id = f"reinject_link_{_seq[0]}" _seq[0] += 1 - new_relationships[child_link_id] = _make_link(child_link_id, src_id, container_id) + new_edges.append(_make_link(child_link_id, src_id, container_id)) else: - new_relationships[rel_id] = rel + new_edges.append(edge) - new_model = {**model, "elements": new_elements, "relationships": new_relationships} + new_model = {**model, "nodes": new_nodes, "edges": new_edges} return {**payload, "model": new_model} +def _node_data(node: dict) -> dict: + data = node.get("data") + return data if isinstance(data, dict) else {} + + +def _user_diagram_nodes(json_data: Dict[str, Any]) -> List[Dict[str, Any]]: + """The nodes of the v4 UserDiagram in ``json_data`` (a diagram payload, or one with a nested ``model``).""" + model_data = json_data.get("model") if isinstance(json_data, dict) else None + if not isinstance(model_data, dict): + return [] + if not model_data.get("nodes") and isinstance(model_data.get("model"), dict): + model_data = model_data["model"] + return [node for node in model_data.get("nodes") or [] if isinstance(node, dict)] + + def safe_path(base_dir: str, user_filename: str) -> str: """Resolve a user-provided filename safely within base_dir.""" return safe_join(base_dir, os.path.basename(user_filename)) @@ -228,50 +235,45 @@ def _criterion_value(raw: str, attribute_name: str) -> Optional[str]: return (match.group(2) if match else "").strip() +def _row_criterion_value(row: Dict[str, Any], attribute_name: str) -> Optional[str]: + """The value of a v4 ``UserModelAttribute`` row for ``attribute_name``, or ``None`` for another attribute. + + A row carries a bare ``name`` with its value in ``value`` / ``defaultValue``, or a + legacy ``"name = Frenchguy"`` name with the value embedded. + """ + name = str(row.get("name") or "") + if _CRITERION_RE.match(name): + return _criterion_value(name, attribute_name) + if name.strip() != attribute_name: + return None + value = row.get("value", row.get("defaultValue")) + return str(value).strip() if value is not None else "" + + def extract_user_profile_names(json_data: Dict[str, Any]) -> Dict[str, str]: """Map each ``User`` box's object name to its human profile name. - The profile name is carried by a ``name`` ``UserModelAttribute`` on the - ``User`` box (e.g. "Frenchguy"). It is not a domain property, so - object-model conversion drops it — we read it straight from the raw diagram - so output files can be named after the profile ("Frenchguy.json") instead - of the auto-generated box id ("user_1.json"). + The profile name is carried by a ``name`` row on the ``User`` box (e.g. + "Frenchguy"). It is not a domain property, so object-model conversion drops + it — we read it straight from the raw diagram so output files can be named + after the profile ("Frenchguy.json") instead of the auto-generated box id + ("user_1.json"). Keyed by the box ``name``, which becomes the generated object's ``id`` and thus the ``model.id`` that ``normalize_user_model_output`` matches on. Boxes - without a filled-in ``name`` attribute are omitted (callers fall back). + without a filled-in ``name`` row are omitted (callers fall back). """ names: Dict[str, str] = {} - if not isinstance(json_data, dict): - return names - model_data = json_data.get("model", {}) - if not isinstance(model_data, dict): - return names - elements = model_data.get("elements", {}) - if not elements and isinstance(model_data.get("model"), dict): - elements = model_data["model"].get("elements", {}) - if not isinstance(elements, dict): - return names - - for element in elements.values(): - if not isinstance(element, dict): + for node in _user_diagram_nodes(json_data): + data = _node_data(node) + if node.get("type") != "UserModelName" or data.get("className") != _ROOT_CLASS_NAME: continue - if ( - element.get("type") != "UserModelName" - or element.get("className") != _ROOT_CLASS_NAME - ): + object_name = data.get("name") + rows = data.get("attributes") + if not object_name or not isinstance(rows, list): continue - object_name = element.get("name") - if not object_name: - continue - attribute_ids = element.get("attributes") - if not isinstance(attribute_ids, list): - continue - for attr_id in attribute_ids: - attr = elements.get(attr_id) - if not isinstance(attr, dict) or attr.get("type") != "UserModelAttribute": - continue - value = _criterion_value(attr.get("name", ""), _USER_NAME_ATTRIBUTE) + for row in rows: + value = _row_criterion_value(row, _USER_NAME_ATTRIBUTE) if isinstance(row, dict) else None if value: names[object_name] = value break @@ -396,16 +398,23 @@ def user_criteria_comparators(diagram_payload: Dict[str, Any]) -> Dict[str, Dict model_data = diagram_payload.get("model") if isinstance(diagram_payload, dict) else None if not isinstance(model_data, dict): return {} - elements = model_data.get("elements") or (model_data.get("model") or {}).get("elements") or {} + nodes = model_data.get("nodes") or (model_data.get("model") or {}).get("nodes") or [] comparators: Dict[str, Dict[str, str]] = defaultdict(dict) - for element in elements.values(): - if not isinstance(element, dict) or element.get("type") != "UserModelAttribute": + for node in nodes: + if not isinstance(node, dict) or node.get("type") != "UserModelName": continue - operator = element.get("attributeOperator") - name = element.get("name") or "" - owner = elements.get(element.get("owner")) or {} - if operator in _CRITERIA_COMPARATORS and operator in name and owner.get("name"): - comparators[owner["name"]][name.split(operator, 1)[0].strip()] = operator + data = node.get("data") or {} + owner_name = data.get("name") + for row in data.get("attributes") or []: + if not isinstance(row, dict): + continue + operator = row.get("attributeOperator") + name = row.get("name") or "" + # Rows carry either a bare name (value in ``value``) or a legacy + # "age > 65" name with the comparator embedded. + attribute = name.split(operator, 1)[0].strip() if operator and operator in name else name.strip() + if operator in _CRITERIA_COMPARATORS and attribute and owner_name: + comparators[owner_name][attribute] = operator return dict(comparators) @@ -417,28 +426,24 @@ def build_user_model_hierarchy(document: Dict[str, Any]) -> Optional[Dict[str, A def extract_profile_personalization_rules(diagram_payload: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]: - """Collect each User's rules without crossing into another User's profile.""" - model = diagram_payload.get('model', {}) if isinstance(diagram_payload, dict) else {} - if not isinstance(model, dict): - return {} - if not model.get('elements') and isinstance(model.get('model'), dict): - model = model['model'] - elements = model.get('elements') or {} - relationships = model.get('relationships') or {} - if not isinstance(elements, dict) or not isinstance(relationships, dict): - return {} - boxes = {key: value for key, value in elements.items() - if isinstance(value, dict) and value.get('type') == 'UserModelName'} + """Collect each User's rules without crossing into another User's profile. + + Rules ride on a box node's ``data.personalization`` and on an attribute row's + ``personalization``; a ``User`` box may carry the editor's captured + ``data.profilePersonalizationRules`` instead. + """ + nodes = _user_diagram_nodes(diagram_payload) + model = diagram_payload.get("model") if isinstance(diagram_payload, dict) else None + if isinstance(model, dict) and not model.get("nodes") and isinstance(model.get("model"), dict): + model = model["model"] + edges = (model.get("edges") or []) if isinstance(model, dict) else [] + boxes = {node["id"]: _node_data(node) for node in nodes + if node.get("type") == "UserModelName" and node.get("id")} adjacency: Dict[str, Set[str]] = defaultdict(set) - for relation in relationships.values(): - if not isinstance(relation, dict): - continue - source_end = relation.get('source') - target_end = relation.get('target') - if not isinstance(source_end, dict) or not isinstance(target_end, dict): + for edge in edges: + if not isinstance(edge, dict): continue - source = source_end.get('element') - target = target_end.get('element') + source, target = edge.get("source"), edge.get("target") if source in boxes and target in boxes: adjacency[source].add(target) adjacency[target].add(source) @@ -462,15 +467,13 @@ def extract_profile_personalization_rules(diagram_payload: Dict[str, Any]) -> Di class_name = box.get('className') or '' if isinstance(box.get('personalization'), dict) and box['personalization']: rules.append({'source': 'profile' if box_id == root_id else 'box', - 'elementId': box.get('id', box_id), 'className': class_name, + 'elementId': box_id, 'className': class_name, 'rules': deepcopy(box['personalization'])}) - for attr_id in box.get('attributes') or []: - attribute = elements.get(attr_id) - if (isinstance(attribute, dict) and attribute.get('type') == 'UserModelAttribute' - and isinstance(attribute.get('personalization'), dict) and attribute['personalization']): - rules.append({'source': 'attribute', 'elementId': attribute.get('id', attr_id), - 'className': class_name, 'attribute': attribute.get('name') or '', - 'rules': deepcopy(attribute['personalization'])}) + for row in box.get('attributes') or []: + if isinstance(row, dict) and isinstance(row.get('personalization'), dict) and row['personalization']: + rules.append({'source': 'attribute', 'elementId': row.get('id'), + 'className': class_name, 'attribute': row.get('name') or '', + 'rules': deepcopy(row['personalization'])}) for neighbor in sorted(adjacency[box_id]): if neighbor not in visited and boxes[neighbor].get('className') != 'User': visited.add(neighbor) @@ -605,6 +608,9 @@ def generate_user_profile_document(user_profile_model: Dict[str, Any]) -> Dict[s or user_profile_model.get("id") or "UserProfile" ) + if isinstance(user_profile_model.get("nodes"), list): + # A bare v4 model carries its own id/title (a v3 model had neither). + diagram_title = "UserProfile" prepared_payload = { "title": diagram_title, "diagramType": "UserDiagram", diff --git a/besser/utilities/web_modeling_editor/backend/services/validators/__init__.py b/besser/utilities/web_modeling_editor/backend/services/validators/__init__.py index 3d39ce86d..7032db8b8 100644 --- a/besser/utilities/web_modeling_editor/backend/services/validators/__init__.py +++ b/besser/utilities/web_modeling_editor/backend/services/validators/__init__.py @@ -3,7 +3,19 @@ """ from .ocl_checker import check_ocl_constraint +from .legacy_format import ( + ensure_diagram_not_legacy, + ensure_not_legacy_model, + ensure_not_legacy_payload, + ensure_project_not_legacy, + is_legacy_v3_model, +) __all__ = [ "check_ocl_constraint", + "ensure_diagram_not_legacy", + "ensure_not_legacy_model", + "ensure_not_legacy_payload", + "ensure_project_not_legacy", + "is_legacy_v3_model", ] diff --git a/besser/utilities/web_modeling_editor/backend/services/validators/legacy_format.py b/besser/utilities/web_modeling_editor/backend/services/validators/legacy_format.py new file mode 100644 index 000000000..4dac3025d --- /dev/null +++ b/besser/utilities/web_modeling_editor/backend/services/validators/legacy_format.py @@ -0,0 +1,206 @@ +"""Reject diagrams saved in the legacy v3 editor format. + +The JSON -> B-UML converters read only the v4 (React Flow) wire shape, +``{version: '4.x', nodes: [...], edges: [...]}`` (see +``docs/source/migrations/uml-v4-shape.md``). A v3 payload +(``{version: '3.x', elements: {...}, relationships: {...}}``) walks no node +array, so without this guard it converts to an *empty* model and every +endpoint answers 200 with empty code or ``isValid: true``. + +The current editor upgrades v3 diagrams on load, so a v3 payload reaching the +backend means a stale client or a hand-made request. It is rejected with a +:class:`LegacyDiagramFormatError` (a ``ConversionError``, so HTTP 400). + +GUI (GrapesJS), quantum-circuit and Knowledge Graph diagrams keep their own +formats and are never treated as legacy UML. +""" + +from typing import Any, Iterable, Mapping, Optional + +from besser.utilities.web_modeling_editor.backend.services.exceptions import ( + ConversionError, + LegacyDiagramFormatError, +) + +# Diagram types whose model is not the UML nodes/edges shape. +NON_UML_DIAGRAM_TYPES = frozenset( + {"GUINoCodeDiagram", "QuantumCircuitDiagram", "KnowledgeGraphDiagram"} +) + +LEGACY_V3_HINT = ( + "open it in the current BESSER web editor (which upgrades it to the v4 " + "format automatically) and retry, or re-export it from there." +) + + +def _is_non_uml(model: Mapping[str, Any], diagram_type: Optional[str]) -> bool: + """The project bucket / ``diagram_type`` decides when one is given, so a + model cannot exempt itself by its own ``type``; ``model['type']`` is used + only without one.""" + if diagram_type: + return diagram_type in NON_UML_DIAGRAM_TYPES + return model.get("type") in NON_UML_DIAGRAM_TYPES + + +def is_legacy_v3_model(model: Any, diagram_type: Optional[str] = None) -> bool: + """Return True when ``model`` is a UML diagram in the legacy v3 shape. + + ``nodes`` content decides first: a model with a non-empty ``nodes`` list is + v4 whatever its ``version`` says (the editor reads it the same way). + Otherwise a model is legacy when its ``elements`` / ``relationships`` maps + are populated, when it declares a UML ``type`` and a ``version`` starting + with ``"3."``, or when it has those maps and no ``nodes`` key. GUI, + quantum and Knowledge Graph diagrams are never legacy; the version rule + also needs a ``type`` because GrapesJS GUI models carry their own, + unrelated ``version`` and no ``type``. + """ + if not isinstance(model, Mapping): + return False + if _is_non_uml(model, diagram_type): + return False + nodes = model.get("nodes") + if isinstance(nodes, list) and nodes: + return False + if model.get("elements") or model.get("relationships"): + return True + model_type = model.get("type") + version = model.get("version") + if ( + isinstance(model_type, str) and model_type + and isinstance(version, str) and version.strip().startswith("3.") + ): + return True + if "nodes" in model: + return False + return "elements" in model or "relationships" in model + + +def ensure_v4_shape( + model: Any, + diagram_type: Optional[str] = None, + title: Optional[str] = None, +) -> None: + """Raise :class:`ConversionError` (HTTP 400) when a UML model's ``nodes`` / + ``edges`` are not lists of objects with a string ``id`` and an object + ``data``, or an edge's ``source`` / ``target`` is not a string. The + converters assume this shape and would otherwise fail with a 500.""" + if not isinstance(model, Mapping): + return + if _is_non_uml(model, diagram_type): + return + what = f"Diagram '{title}'" if title else "The diagram" + for key in ("nodes", "edges"): + if key not in model: + continue + items = model[key] + if not isinstance(items, list): + raise ConversionError(f"{what} is malformed: '{key}' must be a list.") + for item in items: + if not isinstance(item, Mapping) or not isinstance(item.get("id"), str): + raise ConversionError( + f"{what} is malformed: every entry of '{key}' must be an object with a string 'id'." + ) + if item.get("data") is not None and not isinstance(item["data"], Mapping): + raise ConversionError(f"{what} is malformed: {key[:-1]} '{item['id']}' has a non-object 'data'.") + if key == "edges" and not all( + isinstance(item.get(end), str) for end in ("source", "target") if item.get(end) is not None + ): + raise ConversionError(f"{what} is malformed: edge '{item['id']}' has a non-string source or target.") + + +def legacy_v3_message( + model: Mapping[str, Any], + diagram_type: Optional[str] = None, + title: Optional[str] = None, +) -> str: + """Build the user-facing rejection message for a legacy v3 model.""" + dtype = model.get("type") or diagram_type + what = "This diagram" + if title and dtype: + what = f"Diagram '{title}' ({dtype})" + elif title: + what = f"Diagram '{title}'" + elif dtype: + what = f"This {dtype}" + version = model.get("version") + version_note = f" (version {version})" if isinstance(version, str) and version else "" + return f"{what} uses the legacy v3 editor format{version_note}, which this backend no longer reads; {LEGACY_V3_HINT}" + + +def ensure_not_legacy_model( + model: Any, + diagram_type: Optional[str] = None, + title: Optional[str] = None, +) -> None: + """Raise :class:`LegacyDiagramFormatError` if ``model`` is a legacy v3 UML model.""" + if is_legacy_v3_model(model, diagram_type): + raise LegacyDiagramFormatError(legacy_v3_message(model, diagram_type, title)) + + +def ensure_not_legacy_payload( + payload: Any, + diagram_type: Optional[str] = None, + title: Optional[str] = None, +) -> None: + """Check a model nested in a request config, given bare or wrapped as + ``{title, model: }`` (the converters unwrap the same way).""" + while isinstance(payload, Mapping): + ensure_not_legacy_model(payload, diagram_type, title) + payload = payload.get("model") + + +def _as_diagram_list(value: Any) -> Iterable[Any]: + if isinstance(value, list): + return value + if isinstance(value, Mapping): + return [value] + return [] + + +def ensure_project_not_legacy(diagrams: Any) -> None: + """Check every diagram of a raw project ``diagrams`` map. + + Accepts both the multi-diagram (``{type: [diagram, ...]}``) and the old + single-diagram (``{type: diagram}``) layouts. Each entry is a + ``{title, model, ...}`` dict; entries that are not dicts are ignored. + """ + if not isinstance(diagrams, Mapping): + return + for diagram_type, value in diagrams.items(): + for diagram in _as_diagram_list(value): + if not isinstance(diagram, Mapping): + continue + title = diagram.get("title") if isinstance(diagram.get("title"), str) else None + ensure_diagram_not_legacy( + diagram.get("model"), + diagram_type=diagram_type, + title=title, + reference=diagram.get("referenceDiagramData"), + ) + + +def ensure_diagram_not_legacy( + model: Any, + diagram_type: Optional[str] = None, + title: Optional[str] = None, + reference: Any = None, +) -> None: + """Check one diagram: its model (legacy format and v4 shape), the model's + embedded ``referenceDiagramData`` (object diagrams) and a sibling ``reference``.""" + ensure_not_legacy_model(model, diagram_type, title) + ensure_v4_shape(model, diagram_type, title) + if isinstance(model, Mapping): + ensure_not_legacy_reference(model.get("referenceDiagramData"), title) + ensure_not_legacy_reference(reference, title) + + +def ensure_not_legacy_reference(reference: Any, title: Optional[str] = None) -> None: + """Check a ``referenceDiagramData`` payload (a bare model or a ``{model}`` wrapper).""" + if not isinstance(reference, Mapping): + return + inner = reference.get("model") + model = inner if isinstance(inner, Mapping) else reference + ref_title = reference.get("title") if isinstance(reference.get("title"), str) else None + if ref_title is None and title: + ref_title = f"reference of {title}" + ensure_not_legacy_model(model, None, ref_title) diff --git a/besser/utilities/web_modeling_editor/frontend b/besser/utilities/web_modeling_editor/frontend index f32bb7ff4..143fdf3b1 160000 --- a/besser/utilities/web_modeling_editor/frontend +++ b/besser/utilities/web_modeling_editor/frontend @@ -1 +1 @@ -Subproject commit f32bb7ff46db62b6e4a5e47ff618dd292eb686f7 +Subproject commit 143fdf3b11dea0432ce7df395bef1c3e7fce929c diff --git a/docs/source/contributing/diagram_dsl_workflow.rst b/docs/source/contributing/diagram_dsl_workflow.rst index e10b8da5d..ad8106242 100644 --- a/docs/source/contributing/diagram_dsl_workflow.rst +++ b/docs/source/contributing/diagram_dsl_workflow.rst @@ -4,7 +4,7 @@ End-to-End: New Diagram Type + DSL This guide explains the full workflow for adding a **new diagram type with a new DSL** that must work across both repositories: -* **WME repo** (frontend + editor package): `BESSER-Web-Modeling-Editor` +* **WME repo** (frontend diagramming library + webapp): `BESSER-Web-Modeling-Editor` * **BESSER repo** (backend + BUML): this repository Use this when you need **new elements, new rendering, and new backend processing**. @@ -14,10 +14,10 @@ checklist in ``packages/webapp/src/main/features/project/ADDING_NEW_DIAGRAM_TYPE Decision Tree ------------- -1. **Diagram type already exists in the editor package** (``packages/editor``)? +1. **Diagram type already exists in the library package** (``packages/library``)? * Yes: only do the **webapp wiring** (sidebar, project model, import/export labels). - * No: you must add **editor package support** + **webapp wiring** + **backend processing**. + * No: you must add **library package support** + **webapp wiring** + **backend processing**. 2. **New DSL / new semantics**? @@ -28,8 +28,9 @@ Repository Boundaries (who owns what) * **WME repo (frontend, diagram engine)** - - Editor package (diagram types, elements, rendering, palette, property panels) - - Webapp (project model, sidebar, import/export, UI) + - Library package ``packages/library`` — React Flow + Zustand diagram engine + (node components, edge renderers, palette previews, inspector panels) + - Webapp ``packages/webapp`` — project model, sidebar, import/export, UI * **BESSER repo (backend, BUML)** @@ -45,36 +46,43 @@ Step 1: Extend the BUML Metamodel (BESSER repo) 3. Add or update tests under ``tests/BUML`` and ``tests/BUML_invalid``. 4. Update docs under ``docs/source/buml_language``. -Step 2: Add the Diagram Type in the Editor Package (WME repo) -------------------------------------------------------------- +Step 2: Add the Diagram Type in the Library Package (WME repo) +-------------------------------------------------------------- -These files live in the WME repo under ``packages/editor``: +These files live in the WME repo under ``packages/library``: 1. **Register diagram and element types** - * ``packages/editor/src/main/packages/diagram-type.ts`` - * ``packages/editor/src/main/uml-element-type.ts`` - * ``packages/editor/src/main/uml-relationship-type.ts`` (if you add new relationships) + * ``packages/library/lib/types/DiagramType.ts`` (diagram-type enum) + * ``packages/library/lib/types/nodes/NodeProps.ts`` (per-node data shapes) + * ``packages/library/lib/edges/EdgeProps.ts`` (per-edge data shapes if you add new relationships) -2. **Create a new diagram package folder** +2. **Create a new diagram folder for nodes and edges** - * Create ``packages/editor/src/main/packages//`` - * Add element classes (model), React components (rendering), and palette previews. + * Create ``packages/library/lib/nodes//`` and add the React Flow + node components (``.tsx``) plus the ``index.ts`` that registers + them under their v4 type strings. + * Create ``packages/library/lib/edges/edgeTypes/.tsx`` for any new + edge types and add palette previews in + ``packages/library/lib/components/svgs/nodes//``. 3. **Wire registries** - * ``packages/editor/src/main/packages/components.ts`` (component map) - * ``packages/editor/src/main/packages/uml-elements.ts`` (element map) - * ``packages/editor/src/main/packages/uml-relationships.ts`` (relationship map) - * ``packages/editor/src/main/packages/compose-preview.ts`` (palette previews) - * ``packages/editor/src/main/packages/popups.ts`` (property panels) - * ``packages/editor/src/main/components/create-pane/create-pane.tsx`` (diagram type selection) + * ``packages/library/lib/nodes//index.ts`` (per-diagram node map) + * ``packages/library/lib/edges/edgeTypes/index.ts`` (edge type map) + * ``packages/library/lib/components/inspectors//index.ts`` (inspector panels) + * ``packages/library/lib/components/popovers/PopoverManager.tsx`` (popover routing) + * ``packages/library/lib/utils/versionConverter.ts`` (v3 → v4 migration cases + if you need to lift legacy fixtures) 4. **Translations** - * ``packages/editor/src/main/i18n/en.json`` (and other locales if needed) + * Inspector / palette labels are inline in the component sources; + localization currently lives at the webapp layer + (``packages/webapp/src/main/i18n/``). -Tip: Follow patterns from existing diagram packages (e.g. ``uml-class-diagram``). +Tip: Follow patterns from existing diagram folders +(e.g. ``packages/library/lib/nodes/classDiagram``). Step 3: Wire the Diagram into the Webapp (WME repo) --------------------------------------------------- diff --git a/docs/source/generators/agent_personalization.rst b/docs/source/generators/agent_personalization.rst index f25c48da7..63fe5db55 100644 --- a/docs/source/generators/agent_personalization.rst +++ b/docs/source/generators/agent_personalization.rst @@ -48,7 +48,7 @@ optional — unspecified fields fall back to the defaults defined in "font": "sans", "lineSpacing": 1.8, "alignment": "left", - "color": "var(--apollon-primary-contrast)", + "color": "var(--besser-primary-contrast)", "contrast": "high", }, "voiceStyle": {"gender": "female", "speed": 1.0}, diff --git a/docs/source/generators/bpmn.rst b/docs/source/generators/bpmn.rst index f20612e4f..696775b9d 100644 --- a/docs/source/generators/bpmn.rst +++ b/docs/source/generators/bpmn.rst @@ -83,10 +83,11 @@ opaque ``BPMNElement.layout`` passthrough populated by ``process_bpmn_diagram`` when importing from the Web Modeling Editor). For freshly-built or programmatic models the DI section is omitted and the importing tool auto-lays out on open. -Edge waypoints are absolute canvas coordinates. The editor stores a flow's -``path`` relative to the flow's own ``bounds``, so the generator offsets it by -``bounds.x`` / ``bounds.y``. A path is kept only if it then starts on the source -shape and ends on the target shape; otherwise (placeholder geometry, such as the +Edge waypoints are absolute canvas coordinates. ``process_bpmn_diagram`` stores +the editor's absolute edge points as the flow's ``path`` with no ``bounds``; a +``path`` from an older B-UML file is relative to the flow's own ``bounds``, so +the generator offsets it by ``bounds.x`` / ``bounds.y``. A path is kept only if +it then starts on the source shape and ends on the target shape; otherwise (placeholder geometry, such as the flows the modeling assistant creates before the editor re-routes them, a stale path, or no path at all) the edge is re-routed orthogonally between the two shapes' bounds, so every arrow is drawn connected to its steps. diff --git a/docs/source/migrations/uml-v4-shape.md b/docs/source/migrations/uml-v4-shape.md new file mode 100644 index 000000000..d96a8a2e5 --- /dev/null +++ b/docs/source/migrations/uml-v4-shape.md @@ -0,0 +1,1441 @@ +# BESSER UML v4 Wire Shape + +**Status**: the wire contract between the web editor and the backend. +**Audience**: every contributor touching `packages/library` (frontend nodes/edges) +or `besser/utilities/web_modeling_editor/backend/services/converters/` (Python). + +This file describes, per BESSER diagram type, the **v4** shape that the +React Flow library at `packages/library` emits and accepts as the on-disk and +on-wire format. It also documents the legacy **v3** shape that the previous +editor emitted, because the frontend still upgrades it: the per-diagram +migrators in `packages/library/lib/utils/versionConverter.ts` lift a v3 model +to v4 when a project, file or template is loaded. The backend reads only v4 +and answers HTTP 400 on a v3 model (see +[Conversion direction guarantees](#conversion-direction-guarantees)). + +The mapping is exhaustive enough that: + +- frontend `nodes//*.tsx` and `edges/edgeTypes/*.tsx` know the exact + `data` field schema for each node/edge `type`, +- the Python `json_to_buml/_diagram_processor.py` and + `buml_to_json/_diagram_converter.py` parse and emit the correct + shape without consulting frontend code. + +When in doubt, prefer **explicit fields on `node.data`** over inferring from +labels. Inheritance from v3: + +- `id`, `name`, `type`, `bounds`, `owner`, `highlight`, `fillColor`, + `strokeColor`, `textColor`, `description`, `icon`, `uri`, `assessmentNote` + are common UMLModelElement fields. In v4, they all move into `node.data` + (except `id`, which stays on the `Node`, and `bounds`, which is replaced by + `position` + `width` + `height` + `measured`). +- v3 `owner: string | null` becomes v4 `parentId?: string` on the React-Flow + Node. **v4 has no separate "owner" string in `data`** — React Flow's + `parentId` is the only parent reference. Children whose `parentId` is set + are positioned relative to the parent. +- v3 `bounds: { x, y, width, height }` ⇒ v4 `position: { x, y }` and + `width` / `height` / `measured` on the React-Flow node. +- v3 `path: IPath` on relationships moves to v4 `edge.data.points: IPoint[]`. +- v3 `source: { element, direction }` and `target: { element, direction }` + on relationships become v4 `edge.source` / `edge.target` (element id) plus + `edge.sourceHandle` / `edge.targetHandle` (encoding direction). Roles and + multiplicities for class/agent/etc. associations move into `edge.data` — + see per-diagram sections. + +--- + +## Project envelope + +`BesserProject.diagrams[T][i].model` is one diagram model. The current +project schema is `PROJECT_SCHEMA_VERSION = 7` +(`packages/webapp/src/main/shared/types/project.ts`): schema 5 lifted the +diagram models to v4, schema 6 made Component and Deployment diagrams project +types, schema 7 made the Knowledge Graph diagram a project type (the KG build +stamped that step 6, so it runs on every project below 7). Knowledge Graph, +GUI and quantum-circuit models keep their own formats and are never lifted. + +### v3 model (legacy) + +```ts +type V3UMLModel = { + version: `3.${number}.${number}`; + type: UMLDiagramType; + size: { width: number; height: number }; + elements: { [id: string]: UMLElement }; + relationships: { [id: string]: UMLRelationship }; + interactive: { elements: Record; relationships: Record }; + assessments: { [id: string]: Assessment }; + referenceDiagramData?: any; +}; +``` + +### v4 model + +```ts +type V4UMLModel = { + version: `4.${number}.${number}`; + id: string; + title: string; + type: UMLDiagramType; + size?: { width: number; height: number }; // optional, recomputable from nodes + nodes: BesserNode[]; + edges: BesserEdge[]; + interactive?: { elements: Record; relationships: Record }; + assessments: { [id: string]: Assessment }; +}; + +type BesserNode = { + id: string; + type: DiagramNodeType; // string union, see per-diagram sections + position: { x: number; y: number }; + width: number; + height: number; + measured: { width: number; height: number }; + data: Record; + parentId?: string; // replaces v3 owner +}; + +type BesserEdge = { + id: string; + source: string; // node id + target: string; // node id + type: DiagramEdgeType; + sourceHandle: string; // direction encoded as handle id + targetHandle: string; + data: { points: IPoint[]; [key: string]: unknown }; +}; +``` + +Loading a project runs `ensureProjectMigrated` (`shared/types/project.ts`, +called by `ProjectStorageRepository.ts`), whose `migrateProjectToV5` step lifts +every v3 model through +`packages/webapp/src/main/shared/services/storage/migrate-uml-v3-to-v4.ts`. + +### Project mapping rules + +- For every diagram in `project.diagrams[T][i]`, check `model.version`: + - starts with `'3.'` → run the v3→v4 migrator on that single model in + place, leaving the surrounding `ProjectDiagram` envelope alone. + - starts with `'4.'` → leave alone. +- `currentDiagramType`, `currentDiagramIndices`, `references`, and + `settings` are unchanged. +- `GUINoCodeDiagram` and `QuantumCircuitDiagram` keep their pre-existing + formats (GrapesJS / custom canvas). They are **not** v3 UML models and the + migrator must skip them based on diagram type, not on the absence of + `elements`. +- A project exported as B-UML (`project_to_code`) records the editor ids in + its `PROJECT DEFINITION` section: one `# diagram-id : ""` + and one `# diagram-title : ""` line per diagram, in + section order per type, a `# diagram-references ObjectDiagram: {...}` line + per object diagram (the class diagram its objects resolve against), and one + `# class-ids {"": {"": ""}}` line. + `project_to_json` restores them, so cross-diagram references (object + `classId`, component `realizes` / `processModelRefs` / `agentModelRef`, + agent `a2a` refs) stay valid after a `.py` round trip. Files without the + lines (or whose sections no longer line up with them) get fresh ids. +- A project name that is not a B-UML identifier (spaces, hyphens, ...) is + exported with each such character replaced by `_`; the editor's name is + kept on a `# project-name ""` line in the same section and restored + on import. + +--- + +## ClassDiagram + +### v3 element subtypes (ClassDiagram) + +- `Package` — container for classes. +- `Class` / `AbstractClass` / `Interface` / `Enumeration` (`stereotype` field + on the type or the `type` value itself disambiguates). +- `ClassAttribute`, `ClassMethod` — children of a class via `owner`. The + parent class lists their ids in `attributes: string[]` / `methods: string[]`. +- `ClassOCLConstraint` — free-standing OCL constraint node. + +### v3 relationship subtypes + +- `ClassBidirectional`, `ClassUnidirectional`, `ClassAggregation`, + `ClassComposition`, `ClassInheritance`, `ClassRealization`, + `ClassDependency`, `ClassOCLLink`, `ClassLinkRel`. + +Associations carry `source.role`, `source.multiplicity`, `target.role`, +`target.multiplicity` (see `UMLAssociation` in `typings.ts`). Inheritance +points from child (source) to parent (target). + +### v4 node types + +```ts +// node.type values +'package' | 'class' + +// node.data for Package +{ + name: string; + fillColor?: string; strokeColor?: string; textColor?: string; + description?: string; assessmentNote?: string; +} + +// node.data for class | interface | abstract | enumeration +type ClassNodeData = { + name: string; + stereotype?: 'abstract' | 'interface' | 'enumeration' | string | null; + // member rows; v3 attributes/methods were separate UMLElements with owner=parent + attributes: ClassifierMember[]; + methods: ClassifierMember[]; + // OCL constraints attached directly to this class (was a separate element pointing via owner in v3) + oclConstraints?: { id: string; name: string; expression: string }[]; + fillColor?: string; strokeColor?: string; textColor?: string; + description?: string; icon?: string; uri?: string; assessmentNote?: string; +}; + +type ClassifierMember = { + id: string; + name: string; // bare identifier; method rows do NOT fuse the signature in here + attributeType: string; // canonical Python-style: 'str','int','float','bool','date','datetime','time','any', or custom + visibility: 'public' | 'private' | 'protected' | 'package'; + code?: string; + implementationType?: 'none' | 'code' | 'bal' | 'state_machine' | 'quantum_circuit' | 'neural_network'; + stateMachineId?: string; + quantumCircuitId?: string; + neuralNetworkId?: string; // method rows with implementationType 'neural_network': id of the + // project NNDiagram that implements the method (a network name is + // also accepted, for models imported from BUML) + isOptional?: boolean; + isDerived?: boolean; + isId?: boolean; + isExternalId?: boolean; + defaultValue?: unknown; + // Method rows only — structured signature (the inspector mirrors + // returnType onto attributeType; 'any' means "no explicit return type": + // the backend reads it as an untyped method (Method.type = None), and + // buml_to_json writes 'any' back for one, so JSON -> B-UML -> JSON is stable). + parameters?: { id: string; name: string; parameterType?: string; defaultValue?: unknown }[]; + returnType?: string; +}; +``` + +`stereotype` is encoded as a single string (capitalized canonical forms — +the frontend compares case-sensitively; readers stay case-insensitive for +legacy lowercase data). Map v3 element `type`: + +| v3 `type` | v4 `node.type` | v4 `data.stereotype` | +|----------------|----------------|----------------------| +| `Class` | `class` | `null` | +| `AbstractClass`| `class` | `'Abstract'` | +| `Interface` | `class` | `'Interface'` | +| `Enumeration` | `class` | `'Enumeration'` | +| `Package` | `package` | n/a | + +### v4 edge types + +`'ClassBidirectional' | 'ClassUnidirectional' | 'ClassAggregation' | +'ClassComposition' | 'ClassInheritance' | 'ClassRealization' | +'ClassDependency' | 'ClassOCLLink' | 'ClassLinkRel'`. + +```ts +// edge.data for class associations (Bidirectional, Unidirectional, Aggregation, Composition, Dependency) +{ + name?: string; // association name + sourceRole?: string; + sourceMultiplicity?: string; + targetRole?: string; + targetMultiplicity?: string; + sourceNavigable?: boolean; // per-end navigability (associations, aggregations, compositions) + targetNavigable?: boolean; + isManuallyLayouted?: boolean; + points: IPoint[]; +} + +// edge.data for ClassInheritance, ClassRealization, ClassOCLLink, ClassLinkRel +{ + name?: string; + isManuallyLayouted?: boolean; + points: IPoint[]; +} +``` + +### Mapping rules (ClassDiagram) + +- Each v3 `Class`/`AbstractClass`/`Interface`/`Enumeration` element → + one v4 node with `type: 'class'`, `data.attributes` rebuilt from the + v3 `attributes: string[]` lookups against `model.elements[attrId]`, and + similarly for `methods`. The child elements `ClassAttribute` / + `ClassMethod` are **not** emitted as v4 nodes — they collapse into rows + on the parent. +- Position: `node.position = { x: v3.bounds.x, y: v3.bounds.y }`, + `node.width = v3.bounds.width`, `node.height = v3.bounds.height`, + `node.measured = { width: v3.bounds.width, height: v3.bounds.height }`. +- `Package` v3 elements stay as nodes with `type: 'package'`; child + classes that had `owner: ` get `parentId: `. +- Layout through a backend round trip (JSON → B-UML → JSON): B-UML has no + package element here, so `package` nodes are not re-emitted and their + classes and enumerations come back as top-level nodes at their absolute + position (the ancestors' positions added). Class and enumeration colours + (`fillColor`, `strokeColor`, `textColor`, `highlight`) are kept, and a + `ClassInheritance` edge keeps its `sourceHandle` / `targetHandle` and + `points`, as associations do. +- `ClassOCLConstraint`: the canonical v4 shape is a free-standing node + with `type: 'ClassOCLConstraint'` (sticky-note rendering; + `data.expression` carries the full `context …` OCL text, + `data.description` the optional natural-language note), tethered to its + anchoring class by a visual `ClassOCLLink` edge. This is the shape the + editor authors (`ClassOCLConstraintEditPanel`) and the shape the + backend converter always emits — including for class invariants and + method pre/post conditions, mirroring the develop baseline where + constraints are always visible boxes. The v3→v4 migrator may still + collapse owner-linked constraints onto `data.oclConstraints` rows; the + backend processor accepts both shapes on ingest (plus the legacy + `type: 'class'` + `data.stereotype: 'oclConstraint'` fallback) and the + context class is re-derived from the OCL text itself, with the + `ClassOCLLink` edge resolving owners for legacy body-only rows. + Legacy body-only constraints (v3 `constraint` holding just the body plus + `kind: 'invariant' | 'precondition' | 'postcondition'`) keep their v3 + metadata as `data.constraintName` (the name used for the synthesised + `context …` header) and `data.targetMethodId` (pre/post only: the target + method row id) — on the node's `data` or on the `data.oclConstraints` row. + Without them a pre/post body-only row cannot be resolved (`unknown_method`). + The backend processor reads both fields from either place: an invariant + keeps `constraintName` as its constraint name, and a pre/post condition + attaches to the method whose row `id` equals `targetMethodId` (its header + is synthesised from that method's signature). BOCL names only + invariants, so pre/post conditions get generated names + (`_pre__`), as they did before v4. +- Associations: `edge.source = v3.source.element`, `edge.target = + v3.target.element`. Direction mapping uses + `sourceHandle = v3.source.direction` and `targetHandle = + v3.target.direction` (the strings `'Up'|'Down'|'Left'|'Right'` are + preserved verbatim — React Flow accepts arbitrary handle ids). +- Roles & multiplicities lift directly into `edge.data.sourceRole` etc. +- Navigability: v3 `source.navigable` / `target.navigable` lift into + `edge.data.sourceNavigable` / `edge.data.targetNavigable`. A plain + association is always `ClassBidirectional`; `ClassUnidirectional` is + **legacy** and is read as `ClassBidirectional` with + `sourceNavigable: false, targetNavigable: true` (by the TS migrators and + by the backend processor). When the flags are absent the legacy default + applies (`ClassUnidirectional` → source non-navigable, everything else → + both navigable); a present but non-boolean value falls back to that + default with a warning. Rules enforced on ingest (corrected with a + warning, never a hard failure): at least one end is navigable, and the + part (source) end of a composition is navigable — the composite (whole, + diamond) end is the target. BUML → JSON always emits `ClassBidirectional` + (or `ClassComposition`) with both flags, keeping the drawn orientation + (the processor records the source role in the layout side-channel). +- Association-end names are deduplicated per owning class (the class at the + opposite end): a colliding role gets a `_1`, `_2`, … suffix instead of + failing the conversion. +- `path` becomes `edge.data.points`. If `isManuallyLayouted` is set, copy + it through; otherwise omit. +- A class description (`data.description`, or the text of `comment` nodes + linked to the class by `CommentLink` edges, joined by newlines on ingest) + is emitted once by BUML → JSON, as `data.description` (the field the class + inspector edits). B-UML keeps one description per class, so a linked + comment comes back as that field, not as a `comment` node. +- Element timestamps (optional ISO 8601 strings, written only when the + B-UML element's timestamp is explicit; a missing or malformed value + falls back to the creation time on ingest): `model.timestamp` (the + domain model), `node.data.timestamp` (class, enumeration and + `ClassOCLConstraint` nodes), `timestamp` on attribute, method and + enumeration-literal rows, `edge.data.timestamp` (associations and + `ClassInheritance`), and `edge.data.sourceTimestamp` / + `edge.data.targetTimestamp` (the association ends). Parameter rows carry + none. A constraint node holding several constraints gives its timestamp + to none of them. +- Member name parsing: if a v3 `ClassAttribute.name` is `"+ counter: + int"` and `attributeType` is undefined, fall back to + `parseLegacyNameFormat` (see `utils/classifierMemberDisplay.ts`) — the + migrator must accept both shapes. After migration, write the + canonical separate fields. + +--- + +## ObjectDiagram + +### v3 element subtypes (ObjectDiagram) + +- `ObjectName` (top-level container; carries optional `classId` linking to + a class in a sibling ClassDiagram). +- `ObjectAttribute` (children, with optional `attributeId`). +- `ObjectMethod` (children). +- `ObjectIcon`. + +### v3 relationship subtypes + +- `ObjectLink` (with optional `associationId`). + +### v4 node types + +```ts +'objectName' + +type ObjectNodeData = { + name: string; // e.g. "myInstance: Customer" + classId?: string; // link to ClassDiagram class + attributes: ObjectAttribute[]; + methods: ObjectAttribute[]; + fillColor?: string; strokeColor?: string; textColor?: string; + description?: string; assessmentNote?: string; +}; + +type ObjectAttribute = { + id: string; + name: string; // "attribute = value" or just "attribute" + attributeId?: string; // link to ClassDiagram attribute + attributeType?: string; + defaultValue?: unknown; +}; +``` + +### v4 edge types + +`'ObjectLink'` + +```ts +{ + name?: string; + associationId?: string; + sourceRole?: string; + sourceMultiplicity?: string; + targetRole?: string; + targetMultiplicity?: string; + points: IPoint[]; +} +``` + +### Mapping rules (ObjectDiagram) + +- v3 `ObjectName` → v4 `objectName` node, with `attributes`/`methods` + collapsed in the same way as ClassDiagram members. +- v3 `ObjectIcon` is a standalone presentation element; collapse into the + owning object's node as `data.icon: string`. Do not emit a separate v4 + node. +- `ObjectLink.associationId` survives end-to-end on `edge.data.associationId`. + +--- + +## StateMachineDiagram + +### v3 element subtypes (StateMachineDiagram) + +- `State` (container; has `bodies: string[]`, `fallbackBodies: string[]`, + `stereotype: string | null`, `italic`, `underline`, `deviderPosition`, + `hasBody`, `hasFallbackBody`). +- `StateBody`, `StateFallbackBody` (children of State). +- `StateCodeBlock` (free-floating code panel attached to a state). +- `StateActionNode`, `StateObjectNode`, `StateInitialNode`, + `StateFinalNode`, `StateMergeNode`, `StateForkNode`, + `StateForkNodeHorizontal`. + +### v3 relationship subtypes + +- `StateTransition` with `params: { [id]: string }` and `guard?: string`. + +### v4 node types + +```ts +'State' // container +'StateActionNode' +'StateObjectNode' +'StateInitialNode' +'StateFinalNode' +'StateMergeNode' +'StateForkNode' +'StateForkNodeHorizontal' +'StateCodeBlock' +``` + +(v4 collapses `StateBody` and `StateFallbackBody` into the parent state's +`data.bodies` / `data.fallbackBodies` arrays — they are never separate +React-Flow nodes in v4.) + +```ts +type StateNodeData = { + name: string; + stereotype?: string | null; + italic?: boolean; + underline?: boolean; + bodies: { id: string; name: string }[]; + fallbackBodies: { id: string; name: string }[]; + // Display-only (recomputed at render time): deviderPosition, hasBody, hasFallbackBody. + description?: string; + fillColor?: string; strokeColor?: string; textColor?: string; + assessmentNote?: string; +}; + +type StateActionNodeData = { + name: string; + description?: string; + fillColor?: string; strokeColor?: string; textColor?: string; +}; + +type StateObjectNodeData = { + name: string; + classId?: string; // optional link to ClassDiagram if used + description?: string; +}; + +// StateInitialNode, StateFinalNode, StateMergeNode, StateForkNode, StateForkNodeHorizontal +type StateMarkerNodeData = { + name: string; // usually empty +}; + +type StateCodeBlockData = { + name: string; + code: string; // Python BAL code + language?: 'python' | 'bal'; +}; +``` + +### v4 edge types + +`'StateTransition'` + +```ts +{ + name?: string; // edge label + guard?: string; // optional guard expression in [brackets] + params: { [key: string]: string }; // ordered dictionary of parameters; v3 stored as { '0', '1', ... } + points: IPoint[]; +} +``` + +### Mapping rules (StateMachineDiagram) + +- A v3 `State` and its child `StateBody`/`StateFallbackBody` elements + collapse: every `StateBody` whose `owner === stateId` becomes an entry + in `data.bodies` (preserving id + name). Same for fallback bodies. The + child elements **do not** emit v4 nodes. +- All other state element types each map 1:1 to a v4 node with the same + type name (no rename). +- A `StateCodeBlock` is its own node in v4 (was not parented in v3). +- `StateTransition.params` is normalized to a dict in v4 just like v3 — + pass through. If a legacy diagram stored params as `string` or + `string[]`, the migrator coerces to dict (`{ '0': v }` or + `{ '0': v[0], '1': v[1], ... }`). +- Inheritance/initial relationships: `StateInitialNode → State` is + represented by a regular `StateTransition` whose source is the initial + node — there is no separate edge type. + +--- + +## AgentDiagram + +### v3 element subtypes (AgentDiagram) + +The agent diagram **inherits all StateMachine element types** plus its own: + +- Inherited: `State`, `StateBody`, `StateFallbackBody`, `StateActionNode`, + `StateFinalNode`, `StateForkNode`, `StateForkNodeHorizontal`, + `StateInitialNode`, `StateMergeNode`, `StateObjectNode`, + `StateCodeBlock`. +- Agent-specific: + - `AgentState` — extends `State` with `replyType: string`. + - `AgentStateBody`, `AgentStateFallbackBody`. + - `AgentIntent` — has `bodies: string[]` and `intent_description: string`. + - `AgentIntentBody`, `AgentIntentDescription`, + `AgentIntentObjectComponent`. + - `AgentRagElement` — extends UMLElement with optional + `ragDatabaseName`, `dbSelectionType`, `dbCustomName`, `dbQueryMode`, + `dbOperation`, `dbSqlQuery`. + +### v3 relationship subtypes + +- `AgentStateTransition` — see *Legacy AgentStateTransition shapes* below. +- `AgentStateTransitionInit` — initial-state marker edge. + +### v4 node types (agent diagram) + +```ts +// Canvas node types. State + StateMachine inherited types are reused as-is. +'AgentState' // standard and reasoning states (data.stateType) +'comment' // tethered to states by 'CommentLink' edges +``` + +`AgentIntent`, `AgentRagElement`, `AgentLLM`, `AgentTool`, `AgentSkill`, +`AgentWorkspace` (and `AgentGUI`) are **no longer v4 node types**: they are +off-canvas *components* stored in the model's top-level `components` map (see +*Components* below). Nodes of those types are accepted as **legacy input +only** (React Flow models saved before the Components page) and are migrated +into `components` on load by the library (`normalizeAgentComponents`), the +webapp and the backend processor. `AgentReasoningState` is likewise a legacy +input type, read as `AgentState` + `stateType: 'reasoning'`. + +(`AgentStateBody` / `AgentStateFallbackBody` collapse into the state's +`data.bodies` / `data.fallbackBodies` rows exactly like StateBody — v3-only +sub-elements that never emit v4 nodes.) + +```ts +type AgentStateNodeData = { + name: string; + initial?: boolean; // exactly one state carries true (replaces StateInitialNode + init edge) + stateType?: 'standard' | 'reasoning'; + bodies: AgentActionRow[]; // ordered: executed in this order + fallbackBodies: AgentActionRow[]; + fallbackBodyEnabled?: boolean; // absent = true + // reasoning states only + llm_name?: string; max_steps?: number; enable_task_planning?: boolean; + stream_steps?: boolean; system_prompt?: string; fallback_message?: string; + fillColor?: string; strokeColor?: string; textColor?: string; +}; + +// One action of a state body. Field names are the old editor's AgentStateMember +// serialization verbatim; only the fields of the row's action type are required. +type AgentActionRow = { + id: string; + name: string; // text of a text reply / source of a code row / display label otherwise + replyType: 'text' | 'llm' | 'llm_chat' | 'rag' | 'db_reply' | 'code' | 'web_crawl_llm' + | 'ws_markdown' | 'ws_html' | 'ws_speech' | 'ws_options' | 'ws_location' + | 'ws_file' | 'ws_image' | 'ws_dataframe' | 'ws_plotly' | 'gui_reply'; + actionType?: string; // metamodel class name, e.g. 'LLMReplyAction' (writer emits both; reader prefers actionType) + code?: string; // code rows: the source (reader falls back to name) + llm_name?: string; // registered LLM by name; '' = agent default + system_message?: string; // llm / llm_chat system prompt + ragDatabaseName?: string; prompt?: string; // rag + dbSelectionType?: string; dbCustomName?: string; dbQueryMode?: string; + dbOperation?: string; dbSqlQuery?: string; // db_reply + // prompt customisation & session data flow + inputPromptMode?: 'last_user_message' | 'custom'; // llm, rag, db_reply + customInputPrompt?: string; customInputPromptUseSessionVars?: boolean; + systemPromptUseSessionVars?: boolean; // llm, llm_chat + promptUseSessionVars?: boolean; // rag + useSessionVars?: boolean; // text, ws_markdown, ws_html, ws_speech + storeInSession?: string; // session variable receiving the generated answer + sendReply?: boolean; // default true; false = silent (store only) + // web_crawl_llm + initial_url?: string; max_depth?: number; max_pages?: number; crawl_format?: string; + base_url_prefix?: string; run_crawl?: boolean; no_crawl_error_message?: string; + system_message_prefix?: string; systemMessagePrefixUseSessionVars?: boolean; + // websocket replies + ws_message?: string; ws_audio_speed?: number | null; ws_options?: string; // options: one per line + ws_latitude?: number; ws_longitude?: number; + guiId?: string; // gui_reply: gui_id of an AgentGUI component +}; +``` + +`replyType` ↔ `actionType`: text↔TextReplyAction, llm↔LLMReplyAction, +llm_chat↔LLMChatAction, rag↔RAGReplyAction, db_reply↔DBAction, +code↔CustomCodeAction, web_crawl_llm↔WebCrawlLLMAction, +ws_markdown/ws_html/ws_speech/ws_options/ws_location/ws_file/ws_image/ws_dataframe/ws_plotly +↔ WebSocketReply{Markdown,HTML,Speech,Options,Location,File,Image,Dataframe,Plotly}Action, +gui_reply↔GUIReplyAction. Legacy rows: an `llm` / `llm_chat` row without +`system_message` had its prompt on `name` (ignored when it is the +placeholder `"AI response 🪄"`). + +### Components (agent diagram) + +```ts +type AgentDiagramModel = UMLModel & { + components?: { [id: string]: AgentComponent }; // sibling of nodes / edges +}; +``` + +The agent's settings, `default_llm_name` among them, live on the project +diagram envelope (`project.diagrams.AgentDiagram[i].config`), which the editor +reads and writes. `agent_buml_to_json` returns the default LLM on +`model.config`; the project importer moves it onto the envelope (the +single-file importer copies it there), and +`process_agent_diagram` reads `model.config` underneath the envelope's +`config`, so a model saved with it still works. + +```ts + +// Flat entry, no geometry (bounds / position). Identical to the v3 +// smart-generator `model.components` entry, so v3 and v4 share it verbatim. +type AgentComponent = { id: string; type: AgentComponentType; name: string; owner?: string | null } & TypeFields; +``` + +| `type` | fields (defaults) | +|---|---| +| `AgentLLM` | `provider` (`'openai'`), `parameters` (`{}`), `num_previous_messages` (1), `global_context` (`''`) | +| `AgentIntent` | `intent_description` (`''`), `bodies: string[]` — ordered ids of its `AgentIntentBody` entries | +| `AgentIntentBody` | `name` = one training sentence, `owner` = intent id | +| `AgentRagElement` | `llm_name` (`''` = default LLM), `llm_prompt`, `k` (4), `num_previous_messages` (0), `embedding_provider` (`'openai'` \| `'ollama'`), `embedding_base_url`, `embedding_model` (Ollama defaults `http://localhost:11434` / `nomic-embed-text`), `use_hybrid_rag` (false), `bm25_weight` (0.6, 0 < w < 1) | +| `AgentTool` | `description`, `code` | +| `AgentSkill` | `description`, `content` | +| `AgentWorkspace` | `path`, `description`, `writable` (true), `max_read_bytes` (200000) | +| `AgentGUI` | `gui_id`, `persist` (true), `width` (`''`), `is_form` (false), `guiModel` (GrapesJS GUI JSON, or `null` = not designed yet) | + +Canvas → component references are **by name** (`intentName`, `llm_name`, +`ragDatabaseName`) or by **`gui_id`** (`guiId`, `formGuiId`, `guiEventGuiId`). + +Legacy locations, merged into `components` on read (later wins; the +canonical `model.components` always wins): +1. v4 `nodes` of a component type — `node.data` is flattened onto the entry; + an intent's `data.training_phrases` (or `data.bodies`) rows `{id, name}` + become `AgentIntentBody` entries owned by the intent. Edges touching a + migrated node are dropped. +2. v3 `model.elements` of a component type (backend processor only). +3. Diagram-level (`ProjectDiagram.agentComponents`) and model-level + `model.agentComponents` maps (an early components-panel build). + +`buml_to_json` emits components **only** in `model.components`, never as nodes. + +### v4 edge types (agent diagram) + +`'AgentStateTransition' | 'CommentLink'` + +(`AgentStateTransitionInit` is legacy input only: the initial state is the +`data.initial` flag.) + +`AgentStateTransition` is the most complex edge in the migration. The v4 +`edge.data` shape is the **canonical** form: + +```ts +type AgentStateTransitionData = { + name?: string; + params?: { [key: string]: string }; + transitionType: 'predefined' | 'custom'; + predefined?: { + predefinedType: string; // 'when_intent_matched' | 'when_no_intent_matched' | 'auto' | 'when_variable_operation_matched' | 'when_file_received' | 'when_form_submitted' + intentName?: string; // for when_intent_matched + fileType?: string; // for when_file_received: one or more comma-separated MIME types or extensions ('pdf, csv, image/png') + formGuiId?: string; // for when_form_submitted: gui_id of a form AgentGUI ('' = any form) + conditionValue?: + | string + | { variable: string; operator: string; targetValue: string }; + }; + custom?: { + event: + | 'None' + | 'DummyEvent' + | 'WildcardEvent' + | 'ReceiveMessageEvent' + | 'ReceiveTextEvent' + | 'ReceiveJSONEvent' + | 'ReceiveFileEvent' + | 'GUIEvent'; + condition: string[]; + guiEventGuiId?: string; // for GUIEvent: GUIEvent.message_id (gui_id of the AgentGUI) + }; + points: IPoint[]; +}; +``` + +**`predefined` is filled when `transitionType === 'predefined'` and `custom` +is filled when `transitionType === 'custom'`.** The migrator always emits +the canonical shape and strips the legacy flat fields (legacy flat +`formGuiId` / `guiEventGuiId` are lifted into the blocks). + +### Legacy AgentStateTransition shapes (must round-trip) + +The legacy v3 deserializer accepted at least 5 historical shapes. The +migrator must collapse them all to the canonical v4 shape above. Reference +fixtures: + +#### 1. Canonical predefined (current writer output) + +```json +{ + "transitionType": "predefined", + "predefined": { "predefinedType": "when_intent_matched", "intentName": "greet" }, + "custom": { "condition": [] } +} +``` + +→ v4: keep `predefined` as-is; drop `custom`. + +#### 2. Canonical custom (current writer output) + +```json +{ + "transitionType": "custom", + "predefined": { "predefinedType": "" }, + "custom": { "event": "ReceiveTextEvent", "condition": ["len(msg) > 0"] } +} +``` + +→ v4: keep `custom` as-is; drop `predefined`. + +#### 3. Legacy flat predefined (pre-2024) + +```json +{ + "predefinedType": "when_variable_operation_matched", + "variable": "score", + "operator": ">=", + "targetValue": "10" +} +``` + +→ v4: + +```json +{ + "transitionType": "predefined", + "predefined": { + "predefinedType": "when_variable_operation_matched", + "conditionValue": { "variable": "score", "operator": ">=", "targetValue": "10" } + } +} +``` + +#### 4. Legacy flat custom (`condition` was a string) + +```json +{ + "condition": "custom_transition", + "customEvent": "WildcardEvent", + "customConditions": ["x == 1"] +} +``` + +→ v4: + +```json +{ + "transitionType": "custom", + "custom": { "event": "WildcardEvent", "condition": ["x == 1"] } +} +``` + +#### 5. Legacy nested `conditionValue.events`/`conditions` + +```json +{ + "transitionType": "custom", + "conditionValue": { + "events": ["ReceiveMessageEvent"], + "conditions": ["msg == 'hi'"] + } +} +``` + +→ v4: + +```json +{ + "transitionType": "custom", + "custom": { "event": "ReceiveMessageEvent", "condition": ["msg == 'hi'"] } +} +``` + +#### 6. Legacy `predefinedType: 'when_file_received'` (file selector) + +```json +{ + "predefinedType": "when_file_received", + "fileType": "image/png" +} +``` + +→ v4: + +```json +{ + "transitionType": "predefined", + "predefined": { + "predefinedType": "when_file_received", + "fileType": "image/png" + } +} +``` + +The Python transition normalizer (`_normalise_agent_transitions` in +`json_to_buml/agent_diagram_processor.py`) and the TS migrator implement the +same fallthrough order: + +1. If `transitionType === 'custom'` **or** legacy `condition === 'custom_transition'` + **or** `custom.event` non-empty and not `"None"`/`custom.condition` non-empty: emit + `transitionType: 'custom'` with `custom` filled. The conditions come from + `custom.condition`, else a top-level `conditions` or list-valued `condition`, + else `customConditions`, else the nested `conditionValue.conditions`. +2. Else: emit `transitionType: 'predefined'` with `predefined` filled. +3. Inside `predefined`, the type comes from + `predefined.predefinedType ?? predefinedType ?? (legacy condition string) ?? 'when_intent_matched'`. +4. `intentName` / `variable`/`operator`/`targetValue` / `fileType` extracted + per the per-type rules above. A missing `intentName` (`when_intent_matched`) + or `fileType` (`when_file_received`) falls back to a string + `predefined.conditionValue`, then a string top-level `conditionValue`. + +### Mapping rules (AgentDiagram) + +- `AgentState` collapses its body children into `data.bodies` / + `data.fallbackBodies` rows just like `State` collapses `StateBody`. +- v3 component elements (`AgentIntent` + `AgentIntentBody`, `AgentLLM`, + `AgentRagElement`, `AgentTool`, `AgentSkill`, `AgentWorkspace`, + `AgentGUI`) and v3 `model.components` / `agentComponents` go to the v4 + `components` map verbatim (bounds stripped) — never to `nodes`. +- `StateInitialNode` + `AgentStateTransitionInit` fold into `data.initial` + on the target state. +- `replyType` defaults to `'text'` when missing (or is derived from + `actionType`). +- `AgentIntent.intent_description` defaults to `''`. +- Agent-to-agent (A2A) wiring tags, read by Docker Compose generation + (`json_to_buml/a2a_tags.py`): an `AgentState`'s `data.description` may hold + `a2a:out;peer=;ref=;flow=;order=;kind=` + lines (one per outbound edge, mixed with free text), and an + `AgentStateTransition`'s `data.name` an + `a2a:in;peer=...;ref=...;flow=...;kind=...` tag, with the intent in + `data.predefined.intentName`. v3 -> v4 keeps `AgentState.description` as + `data.description` and the transition `name` as `data.name`. A B-UML + export writes the parsed tags as `._a2a = {...}` (the form the + generator reads); the `.py` import writes them back to those two fields. + +--- + +## UserDiagram + +### v3 element subtypes (UserDiagram) + +- `UserModelName` (top-level user node; like ObjectName). +- `UserModelAttribute`. +- `UserModelIcon`. + +### v3 relationship subtypes + +- `UserModelLink`. + +### v4 node types + +```ts +'UserModelName' + +type UserModelNameData = { + name: string; // user identifier (e.g. "Alice: Customer") + className?: string; // the user-metamodel class, e.g. "User", "Disability" + attributes: UserModelAttribute[]; + description?: string; + fillColor?: string; strokeColor?: string; textColor?: string; + icon?: string; + personalization?: object; // box-level personalization rules + profilePersonalizationRules?: object[]; // User box: rules the editor captured for the whole profile +}; + +type UserModelAttribute = { + id: string; + name: string; // bare name, or legacy "name = value" + attributeType?: string; + attributeOperator?: string; // "==", "<", "<=", ">", ">=" + value?: unknown; + defaultValue?: unknown; + personalization?: object; // attribute-level personalization rules +}; +``` + +### v4 edge types + +`'UserModelLink'` + +```ts +{ + name?: string; + points: IPoint[]; +} +``` + +### Mapping rules (UserDiagram) + +- `UserModelAttribute` and `UserModelIcon` v3 children collapse into the + parent `UserModelName` data — same shape as ObjectDiagram. +- B-UML → JSON (project import of a `user_object_model` section) emits + `UserModelName` nodes with `data.classId: null` and `data.className` (the + editor resolves classes from its own copy of the user metamodel), rows + with `value` and `attributeOperator: '=='` (B-UML stores a slot value, not + a comparison), `UserModelLink` edges, and no `referenceDiagramData`. +- The canvas links `User` straight to classes that sit under a hidden + grouping class (`Accessibility`, `Competence`); the backend inserts the + grouping `UserModelName` node and `UserModelLink` edges before conversion + (`reinject_hidden_containers`). A `User` box's profile name is its `name` + row; its personalization rules are read from `profilePersonalizationRules`, + else from the boxes and rows reachable from it without crossing another `User`. +- Comments linked to user objects are kept on the request's object model, + never on the module-level user reference model, which is shared by every + request. +- The reference metamodel JSON (`usermetamodel_buml_short.json`) is bundled + in the new lib at `services/userMetaModel/usermetamodel.json` — backend + remains the OCL validation authority. + +--- + +## NNDiagram + +This is the largest single transformation: **v3 represents each layer +attribute as its own UMLElement** (e.g. `NameAttributeConv2D`, +`KernelDimAttributeConv2D`, …), all owned by the layer; **v4 collapses +every layer's attributes into `node.data.attributes: Record`**. + +### v3 element subtypes (NNDiagram) + +Layer types: + +- `Conv1DLayer`, `Conv2DLayer`, `Conv3DLayer` +- `PoolingLayer` +- `RNNLayer`, `LSTMLayer`, `GRULayer` +- `LinearLayer` +- `FlattenLayer` +- `EmbeddingLayer` +- `DropoutLayer` +- `LayerNormalizationLayer` +- `BatchNormalizationLayer` +- `TensorOp` +- `Configuration` +- `TrainingDataset`, `TestDataset` + +Attribute element types: per layer kind there are 3–13 attribute element +types in the legacy v3 shape, whose +names start with the attribute slug and end in the layer slug, e.g. +`NameAttributeConv2D`, `KernelDimAttributeConv2D`, +`InputReusedAttributeConv2D`. + +Section helper element types (`NNSectionTitle`, `NNSectionSeparator`) and +container types (`NNContainer`, `NNReference`). + +### v3 relationship subtypes + +- `NNNext` — sequential layer flow (unidirectional with "next" label). +- `NNComposition` — diamond on container side. +- `NNAssociation` — dataset ↔ container. + +### v4 node types + +```ts +'Conv1DLayer' | 'Conv2DLayer' | 'Conv3DLayer' +'PoolingLayer' +'RNNLayer' | 'LSTMLayer' | 'GRULayer' +'LinearLayer' +'FlattenLayer' | 'EmbeddingLayer' | 'DropoutLayer' +'LayerNormalizationLayer' | 'BatchNormalizationLayer' +'TensorOp' +'Configuration' +'TrainingDataset' | 'TestDataset' +'NNContainer' | 'NNReference' +``` + +```ts +type NNLayerNodeData = { + name: string; // layer instance name + attributes: Record; // per-layer attribute schema (see widget config) + description?: string; + fillColor?: string; strokeColor?: string; textColor?: string; + assessmentNote?: string; +}; + +type NNContainerNodeData = { + name: string; // model name + input_var?: string; // NN.input_var (forward-pass input variable) + return_vars?: string[]; // NN.return_vars, one entry per returned variable + // (readers also accept the comma-separated string) +}; + +type NNReferenceNodeData = { + name: string; + referenceTarget?: string; // id of the referenced NNContainer node (the editor + // and the backend write the id; readers resolve + // id first, then a container name from older files) +}; +``` + +The keys used in `attributes` follow the **attribute slug** of the v3 element +type (without the layer suffix), normalized to `snake_case`: + +| v3 element type | v4 attribute key | +|---------------------------------------|-----------------------| +| `NameAttributeConv2D` | `name`* | +| `KernelDimAttributeConv2D` | `kernel_dim` | +| `OutChannelsAttributeConv2D` | `out_channels` | +| `StrideDimAttributeConv2D` | `stride_dim` | +| `InChannelsAttributeConv2D` | `in_channels` | +| `PaddingAmountAttributeConv2D` | `padding_amount` | +| `PaddingTypeAttributeConv2D` | `padding_type` | +| `ActvFuncAttributeConv2D` | `actv_func` | +| `NameModuleInputAttributeConv2D` | `name_module_input` | +| `InputReusedAttributeConv2D` | `input_reused` | +| `PermuteInAttributeConv2D` | `permute_in` | +| `PermuteOutAttributeConv2D` | `permute_out` | +| `HiddenSizeAttribute*` | `hidden_size` | +| `ReturnTypeAttribute*` | `return_type` | +| `InputSizeAttribute*` | `input_size` | +| `BidirectionalAttribute*` | `bidirectional` | +| `DropoutAttribute*` (within RNN/LSTM) | `dropout` | +| `BatchFirstAttribute*` | `batch_first` | +| `RateAttributeDropout` | `rate` | +| `OutFeaturesAttributeLinear` | `out_features` | +| `InFeaturesAttributeLinear` | `in_features` | +| `StartDimAttributeFlatten` | `start_dim` | +| `EndDimAttributeFlatten` | `end_dim` | +| `NumEmbeddingsAttributeEmbedding` | `num_embeddings` | +| `EmbeddingDimAttributeEmbedding` | `embedding_dim` | +| `NormalizedShapeAttributeLayerNormalization` | `normalized_shape` | +| `NumFeaturesAttributeBatchNormalization` | `num_features` | +| `DimensionAttributePooling` | `dimension` | +| `DimensionAttributeBatchNormalization`| `dimension` | +| `PoolingTypeAttributePooling` | `pooling_type` | +| `OutputDimAttributePooling` | `output_dim` | +| `TnsTypeAttributeTensorOp` | `tns_type` | +| `ConcatenateDimAttributeTensorOp` | `concatenate_dim` | +| `LayersOfTensorsAttributeTensorOp` | `layers_of_tensors` | +| `ReshapeDimAttributeTensorOp` | `reshape_dim` | +| `TransposeDimAttributeTensorOp` | `transpose_dim` | +| `PermuteDimAttributeTensorOp` | `permute_dim` | +| `BatchSizeAttributeConfiguration` | `batch_size` | +| `EpochsAttributeConfiguration` | `epochs` | +| `LearningRateAttributeConfiguration` | `learning_rate` | +| `OptimizerAttributeConfiguration` | `optimizer` | +| `LossFunctionAttributeConfiguration` | `loss_function` | +| `MetricsAttributeConfiguration` | `metrics` (bare bracketed list, `[accuracy, f1-score]`) | +| `WeightDecayAttributeConfiguration` | `weight_decay` | +| `MomentumAttributeConfiguration` | `momentum` | +| `PathDataAttributeDataset` | `path_data` | +| `TaskTypeAttributeDataset` | `task_type` | +| `InputFormatAttributeDataset` | `input_format` | +| `ShapeAttributeDataset` | `shape` | +| `NormalizeAttributeDataset` | `normalize` | +| `NameAttributeDataset` | `name`* | + +\* The `Name*` v3 attribute element holds the layer's **instance** name +(`conv1d_layer`, `l1`, …); the v3 layer element's own `name` is only the +palette label (`Conv1D Layer`). v4 keeps the instance name on both +`data.name` (what the canvas shows) and `data.attributes.name` (what +`json_to_buml/nn_diagram_processor.py` reads — it rejects a layer or dataset +without it). The migrator prefers the attribute value and falls back to the +layer name; the inspector keeps the two in sync. Default names are +lowercase identifiers (`conv1d_layer`, `pooling_layer`, `tensorop`, +`dataset`, …). + +Extended attribute keys (smart-generator; all optional, stored as strings / +booleans like the table above): + +| Layer kinds | v4 attribute keys | +|-------------|-------------------| +| every layer (inherited from `Layer`) | `is_layer_call`, `input_var`, `output_var` | +| Conv1D/2D/3D | `dilation`, `groups`, `bias` | +| Linear | `bias` | +| RNN / LSTM / GRU | `bias`, `hx_source`, `hidden_state_var`, `hidden_unused`, `hidden_subscript_source`, `hidden_subscript_target` | +| LSTM only | `cell_state_var`, `cell_unused` | +| Embedding | `padding_idx`, `permute_in`, `permute_out` | +| Dropout | `dimension` (plain key, `1D`/`2D`/`3D`), `permute_in`, `permute_out` | +| LayerNormalization | `eps`, `affine` | +| BatchNormalization | `eps`, `momentum`, `affine`, `track_running_stats`, `permute_in`, `permute_out` | +| TensorOp | `input_var`, `output_var`, `output_vars` (split), `permute_in`, `permute_out`, `reduce_dim`, `reduce_keepdims`, `shape_dim`, `actual_vars`, `subscript_indices` (JSON list of `{type: "index"\|"slice", …}`), `repeat_dim`, `interpolate_size`, `interpolate_scale`, `interpolate_mode`, `pad_amount` (`[[l, r], …]`), `pad_mode`, `pad_value`, `dropout_rate`, `dropout_training_aware`, `split_dim`, `split_sizes` | + +`tns_type` takes the metamodel's `ALLOWED_TENSOR_OP_TYPES` (reshape, +concatenate, transpose, permute, multiply, matmultiply, split, +binop_add/subtract/multiply/divide/floor_divide, mean, max, squeeze, +unsqueeze, shape_dim, normalize, repeat, zeros_like, interpolate, pad, +dropout, subscript, identity). `layers_of_tensors` is a list literal whose +items are quoted module names (or `'INPUT'`, the network input) or bare +numeric literals for the binary ops, e.g. `['conv_1', 1.5]`. Only the +Pooling and BatchNormalization `dimension` keys are qualified +(`pooling.dimension` / `batch_normalization.dimension`). + +The full attribute schema and validation defaults live at +`packages/library/lib/nodes/nnDiagram/nnAttributeWidgetConfig.ts` and +`nnValidationDefaults.ts` as data-only modules. + +### v4 edge types + +`'NNNext' | 'NNComposition' | 'NNAssociation'` + +```ts +type NNEdgeData = { + name?: string; + points: IPoint[]; +}; +``` + +### Mapping rules (NNDiagram) + +- For each v3 layer element, collect its attribute elements — the ids in the + layer's `attributes` list (what the old backend read) plus any element with + `owner === layerId` — whose `type` is one of the per-layer attribute + element types, or, failing that, whose `attributeName` names a field of the + layer's schema (the old backend matched on `attributeName`). Drop them from + the v4 node list, accumulate them into the parent's `data.attributes` keyed + by the snake_case slug above. Their `value` field becomes the value (string). +- Dropdown values outside the current whitelist (e.g. padding `zeros`, + optimizer `rmsprop`, loss `cross_entropy`) are preserved verbatim — never + coerced to a default — so the backend reports the real value as a + validation error, exactly as it did for the v3 file. +- For boolean attributes (`'true'`/`'false'`), normalize to JS `boolean` + in v4 — the widget config's `BOOLEAN_OPTIONS` is the source of truth for + which keys are boolean. +- For numeric attributes (e.g. `out_channels`, `kernel_dim`, + `learning_rate`), keep as **strings** in v4 to match the widget which + edits them as text — Python codegen parses with `int(...)` / `float(...)` + exactly as today. +- Layers nested under an `NNContainer` get `parentId: `. +- `NNReference` retains its `referenceTarget` as plain data; no edge + rewrite required. +- v3 `NNSectionTitle` and `NNSectionSeparator` are sidebar-only helpers — + the migrator drops them entirely. + +--- + +## BPMNDiagram + +Model `type` on the wire is **`"BPMNDiagram"`** (`UMLDiagramType.BPMN`); +readers also accept the legacy `"BPMN"`. The project-envelope bucket key is +`project.diagrams.BPMN` (not the model type). Backend constants: +`BPMN_DIAGRAM_TYPE`, `BPMN_DIAGRAM_TYPES`, `BPMN_PROJECT_DIAGRAM_KEY` in +`backend/constants/constants.py`. + +### v4 node types (BPMNDiagram) + +| v3 `type` | v4 `node.type` | `node.data` fields (besides `name`, colours, `highlight`) | +|-----------|----------------|------------------------------------------------------------| +| `BPMNTask` | `bpmnTask` | `taskType` (`default`/`user`/`service`/`send`/`receive`/`manual`/`business-rule`/`script`), `marker` (`none`/`loop`/`parallel multi instance`/`sequential multi instance`) | +| `BPMNSubprocess` / `BPMNTransaction` / `BPMNCallActivity` | `bpmnSubprocess` / `bpmnTransaction` / `bpmnCallActivity` | `marker`; `isExpanded?` (subprocess/transaction) | +| `BPMNStartEvent` / `BPMNIntermediateEvent` / `BPMNEndEvent` | `bpmnStartEvent` / `bpmnIntermediateEvent` / `bpmnEndEvent` | `eventType` (see `bpmn_event_mapping.py`) | +| `BPMNGateway` | `bpmnGateway` | `gatewayType` (`exclusive`/`parallel`/`inclusive`/`event-based`/`complex`) | +| `BPMNDataObject` / `BPMNDataStore` | `bpmnDataObject` / `bpmnDataStore` | — | +| `BPMNAnnotation` | `bpmnAnnotation` | `name` carries the annotation text | +| `BPMNGroup` | `bpmnGroup` | — | +| `BPMNPool` | `bpmnPool` | — | +| `BPMNSwimlane` | `bpmnSwimlane` | — (always `parentId` = its pool) | + +Containment is `parentId` (v3 `owner`): a lane's parent is a pool; a flow +node's parent is a lane, a pool, or a subprocess/transaction. React Flow moves +a node with a container only through `parentId`, and the backend assigns flow +nodes to a pool's process / lane only through `parentId` (an unparented node +lands in a synthetic top-level process). A top-level flow node, data object, +annotation or group whose bounds lie inside a pool / lane / expanded +subprocess is therefore adopted on load (`normalizeV4Model` and +`migrateBpmnDiagramV3ToV4` → `adoptBpmnContainment`, `utils/bpmnContainment.ts`): +parent = the smallest enclosing container (a straddling node in a laned pool +goes to the lane under its centre), position made parent-relative, lane header +strip kept clear. Already-parented nodes are never touched; parents precede +children in `nodes`. + +### Agentic BPMN fields (`node.data`) + +The agentic extension rides on the same nodes, with the v3 attribute names: + +| Node | Fields | B-UML | +|------|--------|-------| +| `bpmnTask` | `isAgentic: boolean`, `reflectionMode` (`none` / `self` / `cross` / `human`), `trustScore: 0..100`, `agentDiagramRef?: string`, `reflectionReviewerLaneId?: string` (a lane node id) | `AgenticTask` when `isAgentic` | +| `bpmnGateway` | `isAgentic: boolean`, `gatewayRole` (`diverging` / `merging`), `trustScore`, `governanceDsl?: string` (Governance DSL policy text, merging gateways) | `AgenticGateway` when `isAgentic` | +| `bpmnSwimlane` | `isAgentic: boolean`, `role` (`solution` / `supervision` / `collaboration` / `consensus`; legacy `worker` / `manager` read as `solution` / `supervision`), `trustScore`, `agentDiagramRef?: string` (AgentDiagram project-diagram id), `multiplicity: number` (swarm size, at least 1) | `AgenticLane` when `isAgentic` | + +`trustScore` is clamped to 0..100 and `multiplicity` to at least 1 on read. +The backend emits `isAgentic`, the role field and `trustScore` on every task, +gateway and lane (`false`, `none` / `diverging` / `solution`, `0`, and lane +`multiplicity: 1` when not agentic); the optional references only when set. +Flows carry no agentic fields. + +### v4 edge types (BPMNDiagram) + +One edge `type` per flow kind (v3 used a single `BPMNFlow` + `flowType`): +`BPMNSequenceFlow` (`sequence`), `BPMNMessageFlow` (`message`), +`BPMNAssociationFlow` (`association`), `BPMNDataAssociationFlow` +(`data association`). + +```ts +// edge.data +{ + name?: string; // backend reads name, falls back to label + label?: string; // BPMNDiagramEdge.tsx renders data.label; the backend emits both + isDefault?: boolean; // BPMNSequenceFlow only + isManuallyLayouted?: boolean; + points: IPoint[]; +} +``` + +### Mapping rules (BPMNDiagram) + +- v3 → v4: `BPMNFlow` + `flowType` picks the edge type. The old editor emitted + `'sequence' | 'message' | 'association' | 'data association'` (with a + space); the migrator also accepts `dataAssociation` / `data_association` / + `data-association`, and a missing `flowType` means `sequence`. v3 + `isDefault: true` becomes `edge.data.isDefault: true`. +- The backend rejects an edge whose `type` starts with `BPMN` but is none of + the four flow types (`ConversionError`, HTTP 400); any other edge type + (e.g. a `CommentLink`) is skipped with a warning. + +- `isDefault` is legal only on a sequence flow whose source is an activity or an + exclusive / inclusive / complex gateway, and a source has at most one default + flow. The editor clears the flag when a sibling is made default, when the + gateway type changes to parallel / event-based, and when a flip or endpoint + reconnect gives the flow an ineligible source; the backend downgrades an + illegal flag to `false` with a warning. +- Children of a `bpmnSwimlane` keep `position.x >= 30` (the lane header strip, + `LANE_HEADER_WIDTH`); lanes sit at `x = 40` (`POOL_HEADER_WIDTH`) inside their + pool, stacked vertically. +- The backend stashes `id`, `parentId`, geometry and colours in the metamodel's + opaque `layout` so JSON → B-UML → JSON keeps ids and positions; B-UML `.py` + import goes through the safe AST-allowlist loader (`safe_load_buml`). + +--- + +## ComponentDiagram + +Model `type` on the wire and project bucket key: **`"ComponentDiagram"`**. +Backed by the UML Component metamodel (`besser/BUML/metamodel/uml_component`); +converters `json_to_buml/component_diagram_processor.py` and +`buml_to_json/component_diagram_converter.py`. + +### v4 node types (ComponentDiagram) + +| v3 `type` | v4 `node.type` | `node.data` fields (besides `name`, colours) | +|-----------|----------------|-----------------------------------------------| +| `Component` | `component` | `stereotype: string`, `isComponentHeaderShown: boolean` (v3 `displayStereotype`), `realizes: string[]`, `processModelRefs: string[]`, `agentModelRef?: string` | +| `Subsystem` | `componentSubsystem` | `stereotype: string`, `isComponentSubsystemHeaderShown: boolean` (v3 `displayStereotype`) | +| `ComponentInterface` | `componentInterface` | — | + +- `stereotype` is the editor's free stereotype string, verbatim (v3 + `stereotype`; an empty string when absent). The backend tokenises it + (`services/converters/stereotype_tokens.py`): `skill` / `tool` / `llm` / + `db` / `rag` pick the `Skill` / `Tool` / `LLM` / `Database` / `RAG` class, + an agent-category token (`solution`, `supervision`, `collaboration`, `consensus`) + makes an `AgenticComponent`, a locality token (`local`, `external`, `hybrid`) sets + `locality`; every other token (including the editor defaults `component` / + `subsystem`) is kept and re-emitted. The backend always emits + `stereotype` on `component` / `componentSubsystem` (empty when none). +- Cross-diagram references, all opaque ids resolved at project level: + `realizes` -> class node ids of a ClassDiagram, `processModelRefs` -> BPMN + project-diagram ids, `agentModelRef` -> the AgentDiagram project-diagram id. +- Containment is `parentId`: a `component` (any subtype) inside a + `componentSubsystem`; position relative to the parent. An interface drawn + inside a subsystem keeps its `parentId` for layout only (the metamodel keeps + interfaces at the model root). + +### v4 edge types (ComponentDiagram) + +| v3 `type` | v4 `edge.type` | B-UML | +|-----------|----------------|-------| +| `ComponentDependency` | `ComponentDependency` | `ComponentDependency`, or `AgenticEdge` when `data.stereotype` carries an agentic-edge kind (`knows`, `uses`, `supervises`, `submits`, `collaborates`) | +| `ComponentInterfaceProvided` | `ComponentProvidedInterface` | `InterfaceProvided` | +| `ComponentInterfaceRequired` (+ `Quarter` / `ThreeQuarter`) | `ComponentRequiredInterface` (+ `ComponentRequiredQuarterInterface` / `ComponentRequiredThreeQuarterInterface`) | `InterfaceRequired`; the drawn variant is kept in the layout and re-emitted | + +```ts +// edge.data +{ + name?: string; // backend reads name, falls back to label; emits both + label?: string; + stereotype?: string; // v3 relationship `stereotype`, verbatim; e.g. "knows" or "«use»" + interfaceBinding?: { // KNOWS / USES only: componentInterface node ids + required: string; + provided: string; + }; + collaborationDirection?: "directed" | "reciprocal"; // COLLABORATES only + isManuallyLayouted?: boolean; + points: IPoint[]; +} +``` + +`interfaceBinding` and `collaborationDirection` are the v3 relationship fields of +the same name, moved into `data`. The importer reads the retired kinds of the +profile before 8.11: `has` from an agent to a skill as `knows`, `revises` from a +solution to a supervision agent as `submits` (other uses stay plain +dependencies), drops a `{permission: ...}` suffix on a typed dependency, and +reads two direction-less `collaborates` edges between the same agents in +opposite directions as one. An agentic dependency with a missing endpoint, or a +missing capability interface on its provider or requester, is a conversion error. + +## DeploymentDiagram + +Model `type` on the wire and project bucket key: **`"DeploymentDiagram"`** +(`DEPLOYMENT_DIAGRAM_TYPE`). Backed by the UML Deployment metamodel +(`besser/BUML/metamodel/uml_deployment`); the Docker Compose generator's input. + +### v4 node types (DeploymentDiagram) + +| v3 `type` | v4 `node.type` | `node.data` fields (besides `name`, colours) | +|-----------|----------------|-----------------------------------------------| +| `DeploymentNode` | `deploymentNode` | `stereotype: string` (kind / locality tokens, e.g. `node`, `device`, `executionEnvironment`, `docker host`), `isComponentHeaderShown: boolean` | +| `DeploymentArtifact` | `deploymentArtifact` | `manifests: string[]` (component node ids), `agentModelRef?: string` (AgentDiagram project-diagram id), `stereotype?: string` | +| `DeploymentComponent` | `deploymentComponent` | `stereotype: string`, `isComponentHeaderShown: boolean`, `manifests?: string[]`, `agentModelRef?: string` | +| `DeploymentInterface` | `deploymentInterface` | — | + +- An artifact's `name` carries its replica count as a suffix: `"Coder [3]"` + is three replicas (the multiplicity of its `DeploymentRelation`). +- Containment is `parentId`: nested `deploymentNode`s and artifacts on a + node. An artifact parented by a node is deployed on it (a + `DeploymentRelation`), with or without an explicit `DeploymentAssociation` + edge between them. +- `agentModelRef` on an artifact selects the AgentDiagram whose BAF agent is + baked into that artifact's Docker build context. + +### v4 edge types (DeploymentDiagram) + +| v3 `type` | v4 `edge.type` | B-UML | +|-----------|----------------|-------| +| `DeploymentAssociation` | `DeploymentAssociation` | Artifact -> Node: `DeploymentRelation`; Node <-> Node: `CommunicationPath`; anything else is rejected (400) | +| `DeploymentDependency` | `DeploymentDependency` | `DeploymentDependency` | +| `DeploymentInterfaceProvided` | `DeploymentProvidedInterface` | `InterfaceProvided` | +| `DeploymentInterfaceRequired` (+ `Quarter` / `ThreeQuarter`) | `DeploymentRequiredInterface` (+ `DeploymentRequiredQuarterInterface` / `DeploymentRequiredThreeQuarterInterface`) | `InterfaceRequired` | + +`edge.data` is the ComponentDiagram one (`name`, `label`, `stereotype?`, +`isManuallyLayouted`, `points`). + +### Mapping rules (ComponentDiagram, DeploymentDiagram) + +- v3 -> v4: every element attribute listed above moves into `node.data` + under the same name, except `displayStereotype`, which becomes the + header flag (`isComponentHeaderShown`, or `isComponentSubsystemHeaderShown` + on a subsystem). A relationship's `stereotype` moves into + `edge.data.stereotype`. The v3 subsystem element type is `Subsystem`. +- The backend stashes `id`, `parentId`, absolute `bounds`, the header flag + (as `displayStereotype`) and colours in the metamodel's opaque `layout` + (edges: `points`, handles, the drawn edge type), so JSON -> B-UML -> JSON + keeps ids, positions and the drawn variants. `.py` files exported by v8.1 + (v3 layout stash: `owner`, relative `path`) still import. +- A model built in Python without a layout gets non-overlapping positions: + children in a row inside their parent, which grows to enclose them, and + roots on a grid. + +--- + +## Conversion direction guarantees + +- **Frontend (TS)**: `migrate-uml-v3-to-v4.ts` reads a v3 model and emits a + v4 model. Pure, no IO. Agent transitions follow the same fallthrough rules + as the Python transition normalizer. +- **Backend (Python)**: `json_to_buml/_diagram_processor.py` + parses v4 directly. `buml_to_json/_diagram_converter.py` emits + v4 directly. The backend has no v3 emission path. +- **Backend rejects v3 on ingest.** The backend has no v3 *read* path + either, so a v3 UML model would convert to an empty B-UML model. Every + endpoint that takes diagram or project JSON therefore refuses one with + HTTP 400 (`LegacyDiagramFormatError`, a `ConversionError`; the check is + `services/validators/legacy_format.py`, run by the `DiagramInput` / + `SimulationSessionInput` model validators — so also for every diagram + nested in a `ProjectInput` — and explicitly on the raw-dict bodies of + `/github/deploy-webapp`, the `existing_model` of + `/get-json-model-from-image`, and the `userProfileModel` and + `personalizationMapping` models of the personalization endpoints, bare + or wrapped as `{title, model}`). `nodes` content decides first: a model + with a non-empty `nodes` list is v4 whatever its `version` says, as in + the editor. Otherwise a model is legacy when its `elements` / + `relationships` are populated (even beside an empty `nodes`), when it + has a UML `type` and a `version` starting with `3.`, or when it has + `elements` / `relationships` and no `nodes`; the same holds for an + object diagram's `referenceDiagramData`. + `GUINoCodeDiagram` (GrapesJS), `QuantumCircuitDiagram` and + `KnowledgeGraphDiagram` models keep their own formats and are never + treated as legacy; inside a project the bucket key decides this, not + the model's own `type`. The message tells the + user to open the diagram in the current editor, whose migrator upgrades it + on load, or to re-export it from there. Saving a v3 project to GitHub is + storage and still succeeds; `/github/project/save` skips the B-UML export + of its legacy diagrams. Each `process_` converter also refuses a + v3 model itself (`ConversionError`) instead of returning an empty model. +- **Backend rejects malformed v4 on ingest.** The same validators check the + shape: `nodes` / `edges` are lists of objects with a string `id`, `data` + (when present) is an object, and an edge's `source` / `target` are + strings. Anything else is an HTTP 400 `ConversionError` naming the + offending entry, not a 500 from deep inside a converter. + +Round-trip tests must hold for **every diagram type** for at least: + +1. v4 fixture → backend BUML → backend re-emit v4 → structural diff = 0. +2. v3 fixture → TS migrator → v4 → backend BUML → frozen golden diff = 0. + +--- + +## Visual deviations from v3 + +### NN layer cards + +`_NNLayerBase.tsx` renders the per-kind PNG +(`/images/nn-layers/.png`) above the stereotype/name header, like the +v3 layer icons, while keeping the v4 stereotype-card structure. The default +layer drop height is 140 px to make room. + +### Header underline on UserModelName + +`HeaderSection.tsx` now applies `textDecoration="underline"` on both +the parent `` element and the inner name ``. +Chromium-based browsers historically dropped underline on tspans when +the parent had a `dy` offset (which happens for cards with a stereotype +line above the name); explicit duplication on the +tspan keeps both the ObjectName and UserModelName headers correctly +underlined regardless of browser quirks. diff --git a/docs/source/web_editor.rst b/docs/source/web_editor.rst index fc9b895a4..a3639b603 100644 --- a/docs/source/web_editor.rst +++ b/docs/source/web_editor.rst @@ -174,3 +174,9 @@ The frontend is a Git submodule at web_editor_backend web_editor_github + +.. note:: + The BESSER Web Modeling Editor is built on `React Flow `_ + and `Zustand `_, packaged as the + ``@besser/wme`` editor library. The diagram engine lives in + ``packages/library`` and the React SPA that hosts it lives in ``packages/webapp``. diff --git a/docs/source/web_editor_backend.rst b/docs/source/web_editor_backend.rst index ebd1271ab..2c068ece0 100644 --- a/docs/source/web_editor_backend.rst +++ b/docs/source/web_editor_backend.rst @@ -33,7 +33,9 @@ Additional infrastructure: - **``middleware/request_logging.py``** -- Structured request logging with unique IDs and performance timing - **``services/cleanup.py``** -- Background temp-file cleanup (removes stale directories every hour) - **``services/exceptions.py``** -- Custom exception hierarchy: ``BesserError`` (base) with ``ConversionError``, ``ValidationError``, ``GenerationError``, ``ConfigurationError`` and ``UpstreamError`` (an external service such as GitHub refused or failed; carries the HTTP status). - ``CodeValidationError`` (invalid custom Python code in an agent) is a ``ValidationError`` and maps to HTTP 400. + ``CodeValidationError`` (invalid custom Python code in an agent) is a ``ValidationError`` and maps to HTTP 400; + ``LegacyDiagramFormatError`` (a diagram in the legacy v3 editor format, see `Diagram JSON Format`_) is a + ``ConversionError`` and maps to HTTP 400. - **Request validation (422)** -- ``backend.py`` replaces FastAPI's handler: each ``detail`` entry keeps ``type``, ``loc`` and ``msg`` but drops pydantic's ``input`` and ``ctx``, since a failing model validator puts the whole request body there, API keys included. - **``services/generation/``** -- Generator dispatch behind ``/generate-output`` and ``/generate-output-from-project``: ``dispatch.py`` picks the path from the generator's registry entry (``category``, ``required_diagram_type``, ``output_type``; ``needs_beyond_one_diagram`` refuses a generator one diagram cannot feed; generators with request options have a builder in ``_CLASS_DIAGRAM_BUILDERS``) and runs it, ``agents.py`` generates agents (BAF), ``downloads.py`` packs the output as a ``GeneratedOutput`` (a ZIP with its provenance file, or one file with its version comment, carrying the traces the generators recorded by path in the download), which the router sends as the download. Every path returns a ``Generation``: that download and the diagrams it was generated from (``DiagramRead``), which the traced endpoints turn into the trace of the run - **``services/kg/``** -- The machinery behind the Knowledge Graph endpoints: ``payloads.py`` (parsing a KG diagram from a request, the ``kgSignature`` check, report-to-response mapping), ``decisions.py`` (applying Refine-KG decisions), ``llm.py`` (reaching the user's own LLM provider under one request deadline) and ``validation.py`` (the consistency check under its concurrency cap, and the KG findings of ``/validate-diagram``) @@ -121,16 +123,65 @@ Supported diagram types (the project keys): ``ClassDiagram``, ``ObjectDiagram``, ``ComponentDiagram``, ``DeploymentDiagram``, and ``KnowledgeGraphDiagram``. A single BPMN diagram payload has type ``BPMNDiagram``. +Diagram JSON Format +^^^^^^^^^^^^^^^^^^^ + +UML diagrams (every type except ``GUINoCodeDiagram``, +``QuantumCircuitDiagram`` and ``KnowledgeGraphDiagram``) travel in the **v4** +React Flow shape, +``{"version": "4.x", "type": ..., "nodes": [...], "edges": [...]}``. The field +schema per diagram type is the `UML v4 wire shape +`__ document (``docs/source/migrations/uml-v4-shape.md`` in the +repository). The converters read only this shape. + +A diagram in the **legacy v3** editor format +(``{"version": "3.x", "elements": {...}, "relationships": {...}}``) is refused +with **HTTP 400**, because converting it would silently produce an empty model. +The response ``detail`` names the diagram and asks the user to open it in the +current editor, which upgrades v3 diagrams on load, or to re-export it from +there. A model with a non-empty ``nodes`` list is v4. Otherwise it counts as +legacy when its ``elements`` / ``relationships`` are populated, when it +declares a UML ``type`` and a ``version`` starting with ``3.``, or when it has +``elements`` / ``relationships`` and no ``nodes``. The check covers: + +- every endpoint taking a ``DiagramInput`` (``/generate-output``, + ``/export-buml``, ``/validate-diagram``, ``/deploy-app``, + ``/transform-agent-model-json``), including an object diagram's + ``referenceDiagramData``; +- every endpoint taking a project (``/generate-output-from-project``, + ``/export-project-as-buml``, ``/spec-driven/generate``, ``/spec-driven/preview``, + ``/spec-driven/resume/{run_id}``, ``/github/deploy-webapp``). A project is + refused when any of its UML diagrams is legacy; +- the agent simulator (``/simulation/validate``, ``/simulation/sessions``) and + the ``userProfileModel`` of ``/personalize-gui-page``, + ``/recommend-agent-config-llm`` and ``/recommend-agent-config-mapping``; +- models nested in an agent diagram's ``config``: the ``config.userProfileModel`` + of ``/transform-agent-model-json`` and every ``personalizationMapping`` entry's + ``user_profile`` and ``agent_model`` (agent generation through + ``/generate-output``, the Docker Compose project generator and + ``/github/deploy-webapp``), bare or wrapped as ``{title, model}``; +- the ``existing_model`` of ``/get-json-model-from-image``. + +GUI (GrapesJS), quantum-circuit and Knowledge Graph models keep their own +formats and are never checked; inside a project the bucket key decides this, +not the model's own ``type``. Saving a project to GitHub (``/github/project/save``, +``/github/project/create-repo``, ``/github/gist/create``) is storage, not +conversion: it stores the JSON unchanged whatever its format, and the B-UML +files that ``/github/project/save`` writes next to it skip legacy diagrams. + Class Diagrams: Element Timestamps ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Every structural B-UML element carries a ``timestamp`` (its creation time), which generators use to order members. The class-diagram converters keep it: -``class_buml_to_json`` writes an optional ISO 8601 ``timestamp`` string on the -diagram model, on each class, enumeration, attribute, enumeration literal, -method and OCL constraint element, on each association and inheritance -relationship, and on each association end (``source`` / ``target``). Only +``class_buml_to_json`` writes an optional ISO 8601 timestamp string on the +diagram model (``model.timestamp``), on each class, enumeration and OCL +constraint node (``node.data.timestamp``), on each attribute, enumeration +literal and method row (``timestamp`` on the row), on each association and +inheritance edge (``edge.data.timestamp``), and on each association end +(``edge.data.sourceTimestamp`` / ``edge.data.targetTimestamp``); see +``docs/source/migrations/uml-v4-shape.md``. Only explicit timestamps are written (``Element.has_explicit_timestamp``: given to the constructor, set later, or read from JSON); one that defaulted to the creation time is left out, so converting the same model twice gives the same @@ -139,13 +190,12 @@ JSON, and exporting a timestamp-less diagram to B-UML twice gives the same file. falls back to the creation time, and a value with a UTC offset is converted to UTC and stored naive, like the metamodel's own timestamps (UTC rather than the server's local time, so the same JSON gives the same B-UML on every host). -Method parameters live -in the method signature string, so they are recreated with a fresh timestamp. +Method parameter rows carry no timestamp, so parameters are recreated with a +fresh one. -The editor itself does not keep the field yet: its element model serializes a -fixed set of properties, so a diagram opened and saved in the editor loses its -timestamps. They survive conversions that do not pass through the editor, such -as importing a B-UML file and exporting it back. +The editor neither reads nor writes these fields. They survive conversions +that do not pass through the editor, such as importing a B-UML file and +exporting it back. Class Diagrams: Element Ids @@ -216,7 +266,7 @@ Neural Network Diagrams The backend treats ``NNDiagram`` as a self-contained diagram type (no cross-diagram references are required for code generation). The editor emits an NN diagram JSON whose top-level ``type`` is ``"NNDiagram"`` and whose -``elements``/``relationships`` describe layers, containers, sub-network +``nodes``/``edges`` describe layers, containers, sub-network references, tensor operations, configuration, and training/test datasets. **Generators.** The registered NN generators are ``pytorch`` and @@ -252,7 +302,7 @@ processor and surfaces ``ValueError`` as per-line validation errors rather than a 500 response. Only ``ValueError`` is caught: any other exception escaping the processor is mapped to a generic HTTP 500 by ``@handle_endpoint_errors``. The processor verifies whitelists for -``pooling_type``, ``return_type``, ``task_type``, ``input_format``, +``padding_type``, ``pooling_type``, ``return_type``, ``task_type``, ``input_format``, ``optimizer``, ``loss_function``, and ``metrics``, as well as conv layer ``kernel_dim`` / ``stride_dim`` lengths, and detects transitive ``NNReference`` cycles among sub-networks. @@ -359,8 +409,8 @@ the BPMN generator emits vendor-neutral BPMN 2.0 XML. The Agentic extension is represented by ``AgenticTask``, ``AgenticGateway``, -and ``AgenticLane`` subclasses. The converter consumes the WME ``isAgentic`` -flag and preserves ``reflectionMode``, ``reflectionReviewerLaneId``, +and ``AgenticLane`` subclasses. The converter consumes the ``isAgentic`` flag +on the node ``data`` and preserves ``reflectionMode``, ``reflectionReviewerLaneId``, ``gatewayRole``, ``trustScore``, lane ``role``, lane ``multiplicity`` (stored as ``AgenticLane.swarm_size``), ``agentDiagramRef``, and ``governanceDsl``. Flows stay standard BPMN flows and carry no agentic fields. @@ -387,17 +437,20 @@ whole-swarm structural and runtime-allocation views backing the They are standalone diagrams for normal import/export, and they also participate in project-level multi-agent system generation. -**Component dependency JSON.** A ``ComponentDependency`` carries its agentic -kind in the ``stereotype`` string. The five tokens are ``knows``, ``uses``, -``supervises``, ``submits`` and ``collaborates``. Use one kind per relationship. -For a collaboration, store one relationship per unordered pair of distinct -agents with the same effective role. The optional ``collaborationDirection`` +Their v4 node and edge types and ``data`` fields are listed in the +`UML v4 wire shape `__ document. + +**Component dependency JSON.** A ``ComponentDependency`` edge carries its agentic +kind in ``data.stereotype``. The five tokens are ``knows``, ``uses``, +``supervises``, ``submits`` and ``collaborates``. Use one kind per edge. +For a collaboration, store one edge per unordered pair of distinct +agents with the same effective role. The optional ``data.collaborationDirection`` field is exclusive to ``collaborates`` dependencies. Use ``"directed"`` for source-to-target traversal or ``"reciprocal"`` for traversal in either direction. An omitted field denotes a legacy reciprocal collaboration; two such -relationships between the same agents in opposite directions, as older editors +edges between the same agents in opposite directions, as older editors derived from BPMN lanes, load as one, with a warning. JSON and B-UML -round trips preserve the explicit direction, relationship ID, endpoint order +round trips preserve the explicit direction, edge ID, endpoint order and layout. Agent nodes carry one role token, including ``none`` for an unassigned role. An ordinary UML dependency can carry its own free-form stereotypes, such as ``«use»``. On a typed dependency, the JSON importer drops @@ -414,28 +467,30 @@ The B-UML importer reads a file saved with the older profile the same way drops ``Permission(...)``, ``permissions=`` and a ``GRANTED`` edge to a permission, and lists each change in the import's ``warnings``. -A dependency with an explicit capability binding has the following semantic -fields in the model's ``relationships`` map. Endpoint and interface references -are element IDs in the same diagram. +A dependency with an explicit capability binding is an edge of the model's +``edges`` list with the binding in ``data``. Endpoint and interface references +are node IDs in the same diagram. .. code-block:: json { "id": "search-dependency", "type": "ComponentDependency", - "stereotype": "knows", - "source": {"element": "agent"}, - "target": {"element": "search-skill"}, - "interfaceBinding": {"required": "agent-query", "provided": "skill-search"} + "source": "agent", + "target": "search-skill", + "data": { + "stereotype": "knows", + "interfaceBinding": {"required": "agent-query", "provided": "skill-search"} + } } -Both binding IDs must name ``ComponentInterface`` elements. Model ownership -with ``ComponentInterfaceRequired`` from ``agent`` to ``agent-query`` and -``ComponentInterfaceProvided`` from ``search-skill`` to ``skill-search``. +Both binding IDs must name ``componentInterface`` nodes. Model ownership +with a ``ComponentRequiredInterface`` edge from ``agent`` to ``agent-query`` and +a ``ComponentProvidedInterface`` edge from ``search-skill`` to ``skill-search``. Omit ``interfaceBinding`` for a capability with zero modeled interfaces or to use the single-interface shorthand. A provider exposing several interfaces requires an explicit pair. A missing component endpoint or a dangling -interface reference on a participating required or provided relationship +interface reference on a participating required or provided edge is a conversion error. The backend checks the agentic relationship rules before emitting JSON or Python. See the :doc:`UML Component model ` for the endpoint and role rules. @@ -713,13 +768,28 @@ Conversion - ``POST /get-json-model`` -- BUML Python file to JSON (auto-detects diagram type) - ``POST /get-project-json-model`` -- BUML project file to JSON. Both import endpoints answer 400 with the reason when a model cannot be read, and list in ``warnings`` (``{code, message}``) what they repaired to - load it, e.g. a composition whose owner end was not navigable. ``trace`` holds the trace file JSON of the - file's ``TRACEABILITY`` section (null when it has none). That section is loaded with the same AST - allowlist as the models, restricted to the traceability metamodel, with the size caps of a whole project - file (2 MB). The trace is best effort: a section that fails to load, or a file exported without its trace, - gives ``trace: null`` and a ``warnings`` entry with code ``trace-not-imported``; the project imports + load it, e.g. a composition whose owner end was not navigable. ``/get-json-model`` also lists the parts of an + agent file it could not read (``buml-import-partial``) rather than returning a shorter diagram silently. + ``trace`` holds the trace file JSON of the file's ``TRACEABILITY`` section (null when it has none). That section + is loaded with the same AST allowlist as the models, restricted to the traceability metamodel, with the size caps + of a whole project file (2 MB). The trace is best effort: a section that fails to load, or a file exported without + its trace, gives ``trace: null`` and a ``warnings`` entry with code ``trace-not-imported``; the project imports. A Component diagram that cannot be read is skipped with a ``buml-import-repaired`` warning that names it; the project's other diagrams import. + + Updating an existing diagram from a file: ``/get-json-model`` takes an optional ``existing_model`` form field, + the editor's v4 model of the diagram the file updates (as JSON text; a project diagram entry with the model + under ``model`` works too). For a Class, Agent or State Machine diagram the import is then laid out like it + (``services/converters/layout_adoption.py``): an element matched by id, or else by type and name inside its + matched parent, keeps its id, position and size (the size grows when its new content needs more room), as do + its attribute, method and body rows and the agent's components; a renamed element is recognised only when its + connections to matched neighbours are unchanged; a new element is placed next to a matched neighbour it is + connected to; a matched edge keeps its id, handles and bend points (the points are dropped when an end grew). + ``warnings`` reports the outcome: ``layout-adopted`` (summary and edge counts), ``element-renamed``, + ``element-added`` (with ``placedNextTo``) and ``element-not-in-import``, each with the ``elementId``, ``type`` + and ``name``. An ``existing_model`` that is not JSON, not a v4 model, of another diagram type, or of a type + without layout adoption leaves the import as is, with a ``layout-not-adopted`` warning saying why. Without the + field the response is unchanged - ``POST /get-json-model-from-image`` -- Image to ClassDiagram JSON (requires OpenAI API key) - ``POST /get-json-model-from-kg`` -- **Deprecated.** Knowledge graph (TTL/RDF/JSON) to ClassDiagram JSON through OpenAI (requires an OpenAI API key). Use ``/kg/import-owl`` and ``/kg/to-class-diagram`` instead - ``POST /csv-to-domain-model`` -- CSV **or XLSX** files to domain model JSON (both extensions are accepted; XLSX needs ``openpyxl``) diff --git a/tests/BUML/notations/kg_to_buml/test_bibo_regression.py b/tests/BUML/notations/kg_to_buml/test_bibo_regression.py index b82008b28..9c6c5c4d4 100644 --- a/tests/BUML/notations/kg_to_buml/test_bibo_regression.py +++ b/tests/BUML/notations/kg_to_buml/test_bibo_regression.py @@ -663,9 +663,7 @@ def test_model_round_trips_through_the_editor(result): ) diagram = class_buml_to_json(result.domain_model) - elements = diagram["elements"] - elements = list(elements.values()) if isinstance(elements, dict) else elements - blocks = [e["constraint"] for e in elements if e["type"] == "ClassOCLConstraint"] + blocks = [n["data"]["expression"] for n in diagram["nodes"] if n["type"] == "ClassOCLConstraint"] assert len(blocks) == len(result.domain_model.constraints) unreadable = [] diff --git a/tests/fixtures/v4/agent_diagram_basic.json b/tests/fixtures/v4/agent_diagram_basic.json new file mode 100644 index 000000000..8ed0f035d --- /dev/null +++ b/tests/fixtures/v4/agent_diagram_basic.json @@ -0,0 +1,108 @@ +{ + "title": "GreetBot", + "model": { + "version": "4.0.0", + "id": "agent-1", + "title": "GreetBot", + "type": "AgentDiagram", + "size": {"width": 1200, "height": 600}, + "nodes": [ + { + "id": "n-init", + "type": "StateInitialNode", + "position": {"x": 0, "y": 0}, + "width": 45, "height": 45, + "measured": {"width": 45, "height": 45}, + "data": {"name": ""} + }, + { + "id": "n-greeting", + "type": "AgentState", + "position": {"x": 100, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Greeting", + "replyType": "text", + "bodies": [ + {"id": "n-greeting-b-1", "name": "Hello!", "replyType": "text"} + ], + "fallbackBodies": [] + } + }, + { + "id": "n-aihelp", + "type": "AgentState", + "position": {"x": 400, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "AIHelp", + "replyType": "llm", + "bodies": [ + {"id": "n-aihelp-b-1", "name": "You are a friendly gym assistant.", "replyType": "llm"} + ], + "fallbackBodies": [] + } + }, + { + "id": "n-intent-greet", + "type": "AgentIntent", + "position": {"x": -200, "y": 200}, + "width": 200, "height": 100, + "measured": {"width": 200, "height": 100}, + "data": { + "name": "greet", + "intent_description": "Greeting intent", + "training_phrases": [ + {"id": "n-intent-greet-t-1", "name": "hi"}, + {"id": "n-intent-greet-t-2", "name": "hello"} + ] + } + }, + { + "id": "n-comment", + "type": "comment", + "position": {"x": -200, "y": -200}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Welcomes the user."} + } + ], + "edges": [ + { + "id": "e-init", + "source": "n-init", + "target": "n-greeting", + "type": "AgentStateTransitionInit", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"points": []} + }, + { + "id": "e-greet-ai", + "source": "n-greeting", + "target": "n-aihelp", + "type": "AgentStateTransition", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "transitionType": "predefined", + "predefined": {"predefinedType": "when_intent_matched", "intentName": "greet"}, + "points": [] + } + }, + { + "id": "e-comment", + "source": "n-comment", + "target": "n-greeting", + "type": "CommentLink", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"points": []} + } + ], + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {} + } +} diff --git a/tests/fixtures/v4/class_diagram_basic.json b/tests/fixtures/v4/class_diagram_basic.json new file mode 100644 index 000000000..96f91e77d --- /dev/null +++ b/tests/fixtures/v4/class_diagram_basic.json @@ -0,0 +1,108 @@ +{ + "title": "Library", + "model": { + "version": "4.0.0", + "id": "cd-1", + "title": "Library", + "type": "ClassDiagram", + "size": {"width": 1200, "height": 800}, + "nodes": [ + { + "id": "n-book", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 200, + "height": 140, + "measured": {"width": 200, "height": 140}, + "data": { + "name": "Book", + "stereotype": null, + "attributes": [ + {"id": "n-book-a-title", "name": "title", "attributeType": "str", "visibility": "public", "isOptional": false, "isId": true, "isExternalId": false, "isDerived": false}, + {"id": "n-book-a-pages", "name": "pages", "attributeType": "int", "visibility": "public", "isOptional": false, "isId": false, "isExternalId": false, "isDerived": false} + ], + "methods": [ + {"id": "n-book-m-summary", "name": "summary", "visibility": "public", "attributeType": "str", "returnType": "str", "parameters": [ + {"id": "n-book-m-summary-p-verbose", "name": "verbose", "parameterType": "bool"} + ]} + ] + } + }, + { + "id": "n-author", + "type": "class", + "position": {"x": 400, "y": 0}, + "width": 200, + "height": 120, + "measured": {"width": 200, "height": 120}, + "data": { + "name": "Author", + "stereotype": null, + "attributes": [ + {"id": "n-author-a-name", "name": "name", "attributeType": "str", "visibility": "public", "isOptional": false, "isId": false, "isExternalId": false, "isDerived": false} + ], + "methods": [] + } + }, + { + "id": "n-genre", + "type": "class", + "position": {"x": 0, "y": 300}, + "width": 200, + "height": 100, + "measured": {"width": 200, "height": 100}, + "data": { + "name": "Genre", + "stereotype": "Enumeration", + "attributes": [ + {"id": "n-genre-l-fiction", "name": "FICTION", "attributeType": "str", "visibility": "public"}, + {"id": "n-genre-l-nonfiction", "name": "NONFICTION", "attributeType": "str", "visibility": "public"} + ], + "methods": [] + } + }, + { + "id": "n-ocl-pages", + "type": "ClassOCLConstraint", + "position": {"x": 0, "y": 500}, + "width": 210, + "height": 90, + "measured": {"width": 210, "height": 90}, + "data": { + "name": "", + "expression": "context Book inv book_positive_pages: self.pages > 0", + "description": "" + } + } + ], + "edges": [ + { + "id": "e-book-author", + "source": "n-book", + "target": "n-author", + "type": "ClassBidirectional", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "wrote", + "sourceRole": "book", + "sourceMultiplicity": "1..*", + "targetRole": "author", + "targetMultiplicity": "1..1", + "points": [] + } + }, + { + "id": "e-ocl-pages", + "source": "n-ocl-pages", + "target": "n-book", + "type": "ClassOCLLink", + "sourceHandle": "right", + "targetHandle": "left", + "data": {"label": "", "points": []} + } + ], + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {} + } +} diff --git a/tests/fixtures/v4/deploy_project.json b/tests/fixtures/v4/deploy_project.json new file mode 100644 index 000000000..15fbbeed8 --- /dev/null +++ b/tests/fixtures/v4/deploy_project.json @@ -0,0 +1,144 @@ +{ + "id": "deploy-project-1", + "type": "project", + "name": "deploy_webapp", + "description": "Minimal v4 deploy-shaped body for /github/deploy-webapp. Exercises ClassDiagram (v4 nodes/edges) + GUINoCodeDiagram (GrapesJS pages/frames). Mirrors what the frontend POSTs as the request body — so it includes deploy_config + settings + currentDiagramIndices alongside the diagrams map.", + "createdAt": "2026-05-08T00:00:00Z", + "currentDiagramType": "ClassDiagram", + "currentDiagramIndices": { + "ClassDiagram": 0, + "GUINoCodeDiagram": 0 + }, + "diagrams": { + "ClassDiagram": [ + { + "id": "cd-1", + "title": "Library", + "model": { + "version": "4.0.0", + "id": "cd-1", + "title": "Library", + "type": "ClassDiagram", + "size": {"width": 1200, "height": 800}, + "nodes": [ + { + "id": "n-book", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 200, + "height": 140, + "measured": {"width": 200, "height": 140}, + "data": { + "name": "Book", + "stereotype": null, + "attributes": [ + {"id": "n-book-a-title", "name": "title", "attributeType": "str", "visibility": "public", "isOptional": false, "isId": true, "isExternalId": false, "isDerived": false}, + {"id": "n-book-a-pages", "name": "pages", "attributeType": "int", "visibility": "public", "isOptional": false, "isId": false, "isExternalId": false, "isDerived": false} + ], + "methods": [] + } + }, + { + "id": "n-author", + "type": "class", + "position": {"x": 400, "y": 0}, + "width": 200, + "height": 120, + "measured": {"width": 200, "height": 120}, + "data": { + "name": "Author", + "stereotype": null, + "attributes": [ + {"id": "n-author-a-name", "name": "name", "attributeType": "str", "visibility": "public", "isOptional": false, "isId": true, "isExternalId": false, "isDerived": false} + ], + "methods": [] + } + } + ], + "edges": [ + { + "id": "e-book-author", + "source": "n-book", + "target": "n-author", + "type": "ClassBidirectional", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "wrote", + "sourceRole": "book", + "sourceMultiplicity": "1..*", + "targetRole": "author", + "targetMultiplicity": "1..1", + "points": [] + } + } + ], + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {} + } + } + ], + "GUINoCodeDiagram": [ + { + "id": "gui-1", + "title": "LibraryUI", + "references": {"ClassDiagram": "cd-1"}, + "model": { + "title": "LibraryUI", + "type": "GUINoCodeDiagram", + "pages": [ + { + "id": "page-home", + "name": "Home", + "attributes": {"screen-size": "Medium"}, + "frames": [ + { + "component": { + "type": "wrapper", + "tagName": "body", + "components": [ + { + "type": "text", + "tagName": "h1", + "attributes": {"id": "title-heading", "name": "title-heading"}, + "components": [ + {"type": "textnode", "content": "Library"} + ] + }, + { + "type": "button", + "tagName": "button", + "attributes": { + "id": "create-book-btn", + "name": "create-book-btn", + "action-button-type": "create", + "entity-class-id": "n-book" + }, + "components": [ + {"type": "textnode", "content": "Add Book"} + ] + } + ] + } + } + ] + } + ], + "styles": [] + } + } + ] + }, + "settings": { + "generator": "web_app", + "config": {} + }, + "deploy_config": { + "target": "webapp", + "repo_name": "besser-deploy-smoke", + "description": "Generated by BESSER WME deploy smoke fixture", + "is_private": false, + "use_existing": false, + "commit_message": "" + } +} diff --git a/tests/fixtures/v4/library_ocl_template.json b/tests/fixtures/v4/library_ocl_template.json new file mode 100644 index 000000000..c506cedcc --- /dev/null +++ b/tests/fixtures/v4/library_ocl_template.json @@ -0,0 +1,700 @@ +{ + "version": "4.0.0", + "id": "converted-diagram-1778241725877", + "title": "", + "type": "ClassDiagram", + "nodes": [ + { + "id": "class_oho5ergc3_mjikkmod", + "width": 270, + "height": 250, + "type": "class", + "position": { + "x": 570, + "y": 200 + }, + "data": { + "name": "Book", + "methods": [ + { + "id": "method_rb01uirsh_mjikkmod", + "name": "+ decrease_stock(qty: int)", + "visibility": "public", + "attributeType": "int): any", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "attributes": [ + { + "id": "attr_a87fqdtdi_mjikkmod", + "name": "title", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_v6ve12d44_mjikkmod", + "name": "pages", + "visibility": "public", + "attributeType": "int", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_edi3c3l8k_mjikkmod", + "name": "stock", + "visibility": "public", + "attributeType": "int", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_mczftcqfb_mjikkmod", + "name": "price", + "visibility": "public", + "attributeType": "float", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_785suq5yn_mjikkmod", + "name": "release", + "visibility": "public", + "attributeType": "date", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_urp7jb0c0_mjikkmod", + "name": "genre", + "visibility": "public", + "attributeType": "Genre", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ] + }, + "measured": { + "width": 270 + } + }, + { + "id": "class_06blhjj3h_mjikkmod", + "width": 350, + "height": 190, + "type": "class", + "position": { + "x": 731.0000406901042, + "y": 584.6666564941406 + }, + "data": { + "name": "Library", + "methods": [ + { + "id": "35ef5329-889b-40f0-89ce-9836936fd8a9", + "name": "+ cheapest_book_by(author:Author): str", + "visibility": "public", + "attributeType": "str", + "code": "def cheapest_book_by(author:Author) -> str {\n cheapest:Book = null;\n\tprice = 1000000000.0;\n\tfor(book in this.books){\n if(book.authors.contains(author)\n\t\t\t&& book.price <= price){\n cheapest = book;\n\t\t\tprice = book.price;\n\t\t}\n }\n\treturn cheapest.title;\n}", + "implementationType": "bal", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "attributes": [ + { + "id": "attr_eryfh37kl_mjikkmod", + "name": "name", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "f9608e0e-745d-4113-85ad-cd06b1900c09", + "name": "web_page", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "4391886d-13b5-4fa0-9894-09f1894af27f", + "name": "address", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "a487fd85-dec0-47b9-bd37-71ff92026963", + "name": "telephone", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ] + }, + "measured": { + "width": 350, + "height": 190 + } + }, + { + "id": "class_d3f0di6lb_mjikkmoe", + "width": 220, + "height": 100, + "type": "class", + "position": { + "x": 1020, + "y": 275 + }, + "data": { + "name": "Author", + "methods": [], + "attributes": [ + { + "id": "attr_p3zqpt65k_mjikkmoe", + "name": "name", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "4321afe8-8ec2-48da-a0ec-b2ce9ccaf1db", + "name": "birth", + "visibility": "public", + "attributeType": "date", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ] + }, + "measured": { + "width": 220, + "height": 100 + } + }, + { + "id": "50ffa27f-f8a9-438b-b81b-174266f39952", + "width": 160, + "height": 350, + "type": "class", + "position": { + "x": 1204, + "y": 456 + }, + "data": { + "name": "Genre", + "methods": [], + "attributes": [ + { + "id": "bfadf7ef-e6a4-43e3-b267-672be745c9c7", + "name": "Poetry", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "15d10eca-11e8-4894-8b27-d815dbc62596", + "name": "Thriller", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "55346119-1f08-48c5-9629-b5223ea766e0", + "name": "History", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "67e73142-470c-4795-8864-96f08365ce49", + "name": "Technology", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "4ba07b68-1fd2-40fc-ad63-05766965aaad", + "name": "Romance", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "52114e47-c8c1-404a-847c-0b877de007e0", + "name": "Horror", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "65937dfa-011b-425e-a292-7d66dff5cd36", + "name": "Adventure", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "994869fb-9b98-450f-add4-a2ee88a15c7f", + "name": "Philosophy", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "45fa6842-da64-4878-b875-c536f06f1d50", + "name": "Cookbooks", + "visibility": "public", + "attributeType": "str" + }, + { + "id": "6d81aaec-327a-42b9-89db-a17e54bb7b5a", + "name": "Fantasy", + "visibility": "public", + "attributeType": "str" + } + ], + "stereotype": "Enumeration" + }, + "measured": { + "width": 160, + "height": 350 + } + }, + { + "id": "ocl-example-00", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 40, + "y": 180 + }, + "data": { + "name": "", + "expression": "context Book inv book_positive_pages: self.pages > 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-01", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 40, + "y": 280 + }, + "data": { + "name": "", + "expression": "context Book inv book_nonneg_stock: self.stock >= 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-02", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 40, + "y": 380 + }, + "data": { + "name": "", + "expression": "context Book inv book_nonneg_price: self.price >= 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-03", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 40, + "y": 80 + }, + "data": { + "name": "", + "expression": "context Book inv book_has_title: self.title.size() > 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-04", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 975, + "y": 840 + }, + "data": { + "name": "", + "expression": "context Library inv library_named: self.name.size() > 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-05", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 635, + "y": 840 + }, + "data": { + "name": "", + "expression": "context Library inv library_has_books: self.books->size() > 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-06", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 1025, + "y": 145 + }, + "data": { + "name": "", + "expression": "context Author inv author_named: self.name.size() > 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-07", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 40, + "y": 580 + }, + "data": { + "name": "", + "expression": "context Book::decrease_stock(qty: int) pre: qty > 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-08", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 40, + "y": 480 + }, + "data": { + "name": "", + "expression": "context Book::decrease_stock(qty: int) pre: self.stock >= qty", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-09", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 40, + "y": 685 + }, + "data": { + "name": "", + "expression": "context Book::decrease_stock(qty: int) post: self.stock >= 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + }, + { + "id": "ocl-example-10", + "width": 210, + "height": 90, + "type": "ClassOCLConstraint", + "position": { + "x": 800, + "y": 940 + }, + "data": { + "name": "", + "expression": "context Library::cheapest_book_by(author: Author) pre: self.books->size() > 0", + "description": "" + }, + "measured": { + "width": 210, + "height": 90 + } + } + ], + "edges": [ + { + "id": "rel_z26fdxrdq_mjikkmoe", + "source": "class_06blhjj3h_mjikkmod", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassBidirectional", + "sourceHandle": "top", + "targetHandle": "bottom", + "data": { + "label": "books", + "name": "books", + "sourceMultiplicity": "1..*", + "targetMultiplicity": "*", + "sourceRole": "library", + "targetRole": "books", + "isManuallyLayouted": false, + "messages": [], + "points": [] + } + }, + { + "id": "rel_0ys2qxzq1_mjikkmoe", + "source": "class_d3f0di6lb_mjikkmoe", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassBidirectional", + "sourceHandle": "left", + "targetHandle": "right", + "data": { + "label": "books", + "name": "books", + "sourceMultiplicity": "1..*", + "targetMultiplicity": "*", + "sourceRole": "authors", + "targetRole": "books", + "isManuallyLayouted": false, + "messages": [], + "points": [] + } + }, + { + "id": "ocl-link-00", + "source": "ocl-example-00", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-01", + "source": "ocl-example-01", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-02", + "source": "ocl-example-02", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-03", + "source": "ocl-example-03", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-04", + "source": "ocl-example-04", + "target": "class_06blhjj3h_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "top", + "targetHandle": "bottom-right", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-05", + "source": "ocl-example-05", + "target": "class_06blhjj3h_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "top", + "targetHandle": "bottom-left", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-06", + "source": "ocl-example-06", + "target": "class_d3f0di6lb_mjikkmoe", + "type": "ClassOCLLink", + "sourceHandle": "bottom", + "targetHandle": "top", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-07", + "source": "ocl-example-07", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-08", + "source": "ocl-example-08", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-09", + "source": "ocl-example-09", + "target": "class_oho5ergc3_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "points": [] + } + }, + { + "id": "ocl-link-10", + "source": "ocl-example-10", + "target": "class_06blhjj3h_mjikkmod", + "type": "ClassOCLLink", + "sourceHandle": "top", + "targetHandle": "bottom", + "data": { + "label": "", + "points": [] + } + } + ], + "assessments": {} +} diff --git a/tests/fixtures/v4/nn_diagram_basic.json b/tests/fixtures/v4/nn_diagram_basic.json new file mode 100644 index 000000000..1a49fb360 --- /dev/null +++ b/tests/fixtures/v4/nn_diagram_basic.json @@ -0,0 +1,66 @@ +{ + "title": "TinyMLP", + "model": { + "version": "4.0.0", + "id": "nn-1", + "title": "TinyMLP", + "type": "NNDiagram", + "size": {"width": 1500, "height": 800}, + "nodes": [ + { + "id": "n-container", + "type": "NNContainer", + "position": {"x": 0, "y": 0}, + "width": 600, "height": 600, + "measured": {"width": 600, "height": 600}, + "data": {"name": "TinyMLP"} + }, + { + "id": "n-l1", + "type": "LinearLayer", + "position": {"x": 50, "y": 100}, + "width": 200, "height": 120, + "measured": {"width": 200, "height": 120}, + "parentId": "n-container", + "data": { + "name": "fc1", + "attributes": { + "name": "fc1", + "in_features": "784", + "out_features": "128", + "actv_func": "relu" + } + } + }, + { + "id": "n-l2", + "type": "LinearLayer", + "position": {"x": 300, "y": 100}, + "width": 200, "height": 120, + "measured": {"width": 200, "height": 120}, + "parentId": "n-container", + "data": { + "name": "fc2", + "attributes": { + "name": "fc2", + "in_features": "128", + "out_features": "10" + } + } + } + ], + "edges": [ + { + "id": "e-l1-l2", + "source": "n-l1", + "target": "n-l2", + "type": "NNNext", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"points": []} + } + ], + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {} + } +} diff --git a/tests/fixtures/v4/object_diagram_basic.json b/tests/fixtures/v4/object_diagram_basic.json new file mode 100644 index 000000000..065852667 --- /dev/null +++ b/tests/fixtures/v4/object_diagram_basic.json @@ -0,0 +1,54 @@ +{ + "title": "LibraryInstances", + "model": { + "version": "4.0.0", + "id": "od-1", + "title": "LibraryInstances", + "type": "ObjectDiagram", + "size": {"width": 1000, "height": 600}, + "nodes": [ + { + "id": "n-mybook", + "type": "objectName", + "position": {"x": 0, "y": 0}, + "width": 200, "height": 100, + "measured": {"width": 200, "height": 100}, + "data": { + "name": "myBook", + "classId": "n-book", + "attributes": [ + {"id": "n-mybook-a-title", "name": "title", "attributeType": "str", "value": "1984"}, + {"id": "n-mybook-a-pages", "name": "pages", "attributeType": "int", "value": "328"} + ], + "methods": [] + } + } + ], + "edges": [], + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {}, + "referenceDiagramData": { + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-book", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 200, "height": 120, + "measured": {"width": 200, "height": 120}, + "data": { + "name": "Book", + "stereotype": null, + "attributes": [ + {"id": "n-book-a-title", "name": "title", "attributeType": "str", "visibility": "public"}, + {"id": "n-book-a-pages", "name": "pages", "attributeType": "int", "visibility": "public"} + ], + "methods": [] + } + } + ], + "edges": [] + } + } +} diff --git a/tests/fixtures/v4/state_machine_basic.json b/tests/fixtures/v4/state_machine_basic.json new file mode 100644 index 000000000..a2556d85d --- /dev/null +++ b/tests/fixtures/v4/state_machine_basic.json @@ -0,0 +1,58 @@ +{ + "title": "TrafficLight", + "model": { + "version": "4.0.0", + "id": "sm-1", + "title": "TrafficLight", + "type": "StateMachineDiagram", + "size": {"width": 1200, "height": 600}, + "nodes": [ + { + "id": "n-init", + "type": "StateInitialNode", + "position": {"x": 0, "y": 0}, + "width": 45, "height": 45, + "measured": {"width": 45, "height": 45}, + "data": {"name": ""} + }, + { + "id": "n-red", + "type": "State", + "position": {"x": 100, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Red", "bodies": [], "fallbackBodies": []} + }, + { + "id": "n-green", + "type": "State", + "position": {"x": 400, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Green", "bodies": [], "fallbackBodies": []} + } + ], + "edges": [ + { + "id": "e-init", + "source": "n-init", + "target": "n-red", + "type": "StateTransition", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"name": "", "points": []} + }, + { + "id": "e-red-green", + "source": "n-red", + "target": "n-green", + "type": "StateTransition", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"name": "go", "points": []} + } + ], + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {} + } +} diff --git a/tests/fixtures/v4/webapp_smoke_project.json b/tests/fixtures/v4/webapp_smoke_project.json new file mode 100644 index 000000000..b8ee3987f --- /dev/null +++ b/tests/fixtures/v4/webapp_smoke_project.json @@ -0,0 +1,136 @@ +{ + "id": "smoke-project-1", + "type": "project", + "name": "smoke_webapp", + "description": "Minimal v4 ProjectInput fixture exercising WebApp generation (ClassDiagram + GUINoCodeDiagram).", + "createdAt": "2026-05-08T00:00:00Z", + "currentDiagramType": "ClassDiagram", + "currentDiagramIndices": { + "ClassDiagram": 0, + "GUINoCodeDiagram": 0 + }, + "diagrams": { + "ClassDiagram": [ + { + "id": "cd-1", + "title": "Library", + "model": { + "version": "4.0.0", + "id": "cd-1", + "title": "Library", + "type": "ClassDiagram", + "size": {"width": 1200, "height": 800}, + "nodes": [ + { + "id": "n-book", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 200, + "height": 140, + "measured": {"width": 200, "height": 140}, + "data": { + "name": "Book", + "stereotype": null, + "attributes": [ + {"id": "n-book-a-title", "name": "title", "attributeType": "str", "visibility": "public", "isOptional": false, "isId": true, "isExternalId": false, "isDerived": false}, + {"id": "n-book-a-pages", "name": "pages", "attributeType": "int", "visibility": "public", "isOptional": false, "isId": false, "isExternalId": false, "isDerived": false} + ], + "methods": [] + } + }, + { + "id": "n-author", + "type": "class", + "position": {"x": 400, "y": 0}, + "width": 200, + "height": 120, + "measured": {"width": 200, "height": 120}, + "data": { + "name": "Author", + "stereotype": null, + "attributes": [ + {"id": "n-author-a-name", "name": "name", "attributeType": "str", "visibility": "public", "isOptional": false, "isId": true, "isExternalId": false, "isDerived": false} + ], + "methods": [] + } + } + ], + "edges": [ + { + "id": "e-book-author", + "source": "n-book", + "target": "n-author", + "type": "ClassBidirectional", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "wrote", + "sourceRole": "book", + "sourceMultiplicity": "1..*", + "targetRole": "author", + "targetMultiplicity": "1..1", + "points": [] + } + } + ], + "interactive": {"elements": {}, "relationships": {}}, + "assessments": {} + } + } + ], + "GUINoCodeDiagram": [ + { + "id": "gui-1", + "title": "LibraryUI", + "references": {"ClassDiagram": "cd-1"}, + "model": { + "title": "LibraryUI", + "type": "GUINoCodeDiagram", + "pages": [ + { + "id": "page-home", + "name": "Home", + "attributes": {"screen-size": "Medium"}, + "frames": [ + { + "component": { + "type": "wrapper", + "tagName": "body", + "components": [ + { + "type": "text", + "tagName": "h1", + "attributes": {"id": "title-heading", "name": "title-heading"}, + "components": [ + {"type": "textnode", "content": "Library"} + ] + }, + { + "type": "button", + "tagName": "button", + "attributes": { + "id": "create-book-btn", + "name": "create-book-btn", + "action-button-type": "create", + "entity-class-id": "n-book" + }, + "components": [ + {"type": "textnode", "content": "Add Book"} + ] + } + ] + } + } + ] + } + ], + "styles": [] + } + } + ] + }, + "settings": { + "generator": "web_app", + "config": {} + } +} diff --git a/tests/generators/agents/test_baf_generator_reasoning.py b/tests/generators/agents/test_baf_generator_reasoning.py index 470961204..ca86499b2 100644 --- a/tests/generators/agents/test_baf_generator_reasoning.py +++ b/tests/generators/agents/test_baf_generator_reasoning.py @@ -122,6 +122,8 @@ def test_emits_tool_registration(self, reasoning_agent_model, tmp_path): with open(tools_path, "r", encoding="utf-8") as f: tools_code = f.read() assert "def ping" in tools_code + # Tools are loaded from tools.py, never registered inline. + assert "agent.new_tool(" not in agent_code def test_emits_skill_registration(self, reasoning_agent_model, tmp_path): agent_path = _generate(reasoning_agent_model, str(tmp_path)) @@ -136,6 +138,10 @@ def test_emits_skill_registration(self, reasoning_agent_model, tmp_path): with open(skill_file, "r", encoding="utf-8") as f: skill_content = f.read() assert "Always greet the user by name when introduced." in skill_content + # Skills are not registered inline: no ``new_skill(..., content=...)`` + # call (BAF's new_skill takes the text as positional ``source``). + assert "agent.new_skill(" not in agent_code + assert "content=" not in agent_code def test_emits_workspace_registration(self, reasoning_agent_model, tmp_path): path = _generate(reasoning_agent_model, str(tmp_path)) @@ -179,6 +185,8 @@ def test_plain_agent_does_not_import_reasoning(self, tmp_path): assert "from baf.library.state import new_reasoning_state" not in code assert "agent.load_tools(" not in code assert "agent.load_skills(" not in code + assert "agent.new_tool(" not in code + assert "agent.new_skill(" not in code assert "agent.new_workspace(" not in code def test_test_mode_still_generates_reasoning_assets(self, reasoning_agent_model, tmp_path): diff --git a/tests/generators/bpmn/test_bpmn_generator_di.py b/tests/generators/bpmn/test_bpmn_generator_di.py index 68c8dbb2a..7d96c3675 100644 --- a/tests/generators/bpmn/test_bpmn_generator_di.py +++ b/tests/generators/bpmn/test_bpmn_generator_di.py @@ -243,38 +243,36 @@ def test_path_kept_when_endpoint_shapes_unknown(self, tmp_path): def _assistant_style_json(n_tasks=9): """A start event, ``n_tasks`` sequential tasks each fed by a data object, and an end event -- with the placeholder flow geometry the modeling assistant emits.""" - elements, relationships = {}, {} - - def node(elem_id, type_, name, x, y, w, h, **extra): - elements[elem_id] = {"id": elem_id, "name": name, "type": type_, "owner": None, - "bounds": _bounds(x, y, w, h), **extra} - - def rel(rel_id, source, target, flow_type): - relationships[rel_id] = { - "id": rel_id, "name": "", "type": "BPMNFlow", "owner": None, - "bounds": _bounds(0, 0, 100, 1), "path": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], - "source": {"element": source, "direction": "Right"}, - "target": {"element": target, "direction": "Left"}, - "isManuallyLayouted": False, "flowType": flow_type, "isDefault": False, - } - - node("start", "BPMNStartEvent", "Cell production started", -1000, 10, 40, 40, + nodes, edges = [], [] + + def node(node_id, type_, name, x, y, w, h, **extra): + nodes.append({"id": node_id, "type": type_, "position": {"x": x, "y": y}, + "width": w, "height": h, "data": {"name": name, **extra}}) + + def edge(edge_id, source, target, edge_type): + edges.append({ + "id": edge_id, "type": edge_type, "source": source, "target": target, + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "", "points": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], + "isManuallyLayouted": False}, + }) + + node("start", "bpmnStartEvent", "Cell production started", -1000, 10, 40, 40, eventType="default") previous = "start" for i in range(n_tasks): - node(f"t{i}", "BPMNTask", f"Step {i + 1}", -780 + i * 220, 0, 140, 60, + node(f"t{i}", "bpmnTask", f"Step {i + 1}", -780 + i * 220, 0, 140, 60, taskType="default", marker="none") - node(f"d{i}", "BPMNDataObject", f"Input {i + 1}", -730 + i * 220, 120, 40, 50) - rel(f"f{i}", previous, f"t{i}", "sequence") - rel(f"a{i}", f"d{i}", f"t{i}", "data association") + node(f"d{i}", "bpmnDataObject", f"Input {i + 1}", -730 + i * 220, 120, 40, 50) + edge(f"f{i}", previous, f"t{i}", "BPMNSequenceFlow") + edge(f"a{i}", f"d{i}", f"t{i}", "BPMNDataAssociationFlow") previous = f"t{i}" - node("end", "BPMNEndEvent", "Cell ready", -780 + n_tasks * 220, 10, 40, 40, + node("end", "bpmnEndEvent", "Cell ready", -780 + n_tasks * 220, 10, 40, 40, eventType="default") - rel("f_end", previous, "end", "sequence") + edge("f_end", previous, "end", "BPMNSequenceFlow") return {"title": "Cell production", "model": { - "version": "3.0.0", "type": "BPMNDiagram", "size": {"width": 2400, "height": 400}, - "elements": elements, "relationships": relationships, - "interactive": {"elements": {}, "relationships": {}}, "assessments": {}}} + "version": "4.0.0", "type": "BPMNDiagram", "nodes": nodes, "edges": edges, + "assessments": {}}} def test_issue_627_export_is_connected_and_keeps_data_objects(tmp_path): diff --git a/tests/generators/bpmn/test_bpmn_trace.py b/tests/generators/bpmn/test_bpmn_trace.py index cfbf575f9..5bce59ea0 100644 --- a/tests/generators/bpmn/test_bpmn_trace.py +++ b/tests/generators/bpmn/test_bpmn_trace.py @@ -12,38 +12,32 @@ from tests.bpmn_models import _subprocess_model, _two_pool_model -def _bounds(x, y, w, h): - return {"x": x, "y": y, "width": w, "height": h} - - def _editor_diagram() -> dict: """A start event, two tasks each fed by a data object, and an end event, as the web editor sends them.""" - elements, relationships = {}, {} + nodes, edges = [], [] - def node(elem_id, type_, name, x, y, w, h, **extra): - elements[elem_id] = {"id": elem_id, "name": name, "type": type_, "owner": None, - "bounds": _bounds(x, y, w, h), **extra} + def node(node_id, type_, name, x, y, w, h, **data): + nodes.append({"id": node_id, "type": type_, "position": {"x": x, "y": y}, "width": w, "height": h, + "data": {"name": name, **data}}) - def rel(rel_id, source, target, flow_type): - relationships[rel_id] = { - "id": rel_id, "name": "", "type": "BPMNFlow", "owner": None, "bounds": _bounds(0, 0, 100, 1), - "path": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], "source": {"element": source, "direction": "Right"}, - "target": {"element": target, "direction": "Left"}, "isManuallyLayouted": False, "flowType": flow_type, - "isDefault": False} + def edge(edge_id, source, target, edge_type): + edges.append({"id": edge_id, "type": edge_type, "source": source, "target": target, + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "", "isManuallyLayouted": False, "isDefault": False, + "points": [{"x": 0, "y": 0}, {"x": 100, "y": 0}]}}) - node("start", "BPMNStartEvent", "Started", -300, 10, 40, 40, eventType="default") + node("start", "bpmnStartEvent", "Started", -300, 10, 40, 40, eventType="default") previous = "start" for i in range(2): - node(f"t{i}", "BPMNTask", f"Step {i + 1}", -200 + i * 220, 0, 140, 60, taskType="default", marker="none") - node(f"d{i}", "BPMNDataObject", f"Input {i + 1}", -150 + i * 220, 120, 40, 50) - rel(f"f{i}", previous, f"t{i}", "sequence") - rel(f"a{i}", f"d{i}", f"t{i}", "data association") + node(f"t{i}", "bpmnTask", f"Step {i + 1}", -200 + i * 220, 0, 140, 60, taskType="default", marker="none") + node(f"d{i}", "bpmnDataObject", f"Input {i + 1}", -150 + i * 220, 120, 40, 50) + edge(f"f{i}", previous, f"t{i}", "BPMNSequenceFlow") + edge(f"a{i}", f"d{i}", f"t{i}", "BPMNDataAssociationFlow") previous = f"t{i}" - node("end", "BPMNEndEvent", "Ready", 300, 10, 40, 40, eventType="default") - rel("f_end", previous, "end", "sequence") - return {"title": "Cell", "model": {"version": "3.0.0", "type": "BPMNDiagram", "size": {"width": 800, "height": 400}, - "elements": elements, "relationships": relationships, - "interactive": {"elements": {}, "relationships": {}}, "assessments": {}}} + node("end", "bpmnEndEvent", "Ready", 300, 10, 40, 40, eventType="default") + edge("f_end", previous, "end", "BPMNSequenceFlow") + return {"title": "Cell", "model": {"version": "4.0.0", "type": "BPMNDiagram", "nodes": nodes, "edges": edges, + "assessments": {}}} def _generate(model, out, file_name="bpmn_diagram.bpmn"): diff --git a/tests/generators/django/test_django_ocl_constraints.py b/tests/generators/django/test_django_ocl_constraints.py index c1a3f460d..fbe2a9f46 100644 --- a/tests/generators/django/test_django_ocl_constraints.py +++ b/tests/generators/django/test_django_ocl_constraints.py @@ -20,6 +20,7 @@ Property, Constraint, IntegerType, + Method, StringType, ) from besser.generators.django import DjangoGenerator @@ -200,3 +201,35 @@ def test_unconstrained_sibling_has_no_clean_method(self): assert "def clean(self):" in player_block assert "def clean(self):" not in team_block + + +class TestConstraintWithMethods: + """clean() followed by methods: the first method used to be glued to + ``raise ValidationError(errors)`` on the same line (SyntaxError).""" + + def _model(self, methods): + age_attr = Property(name="age", type=IntegerType) + player = Class(name="Player", attributes={age_attr}, methods=set(methods)) + return DomainModel( + name="M", + types={player}, + constraints={ + Constraint( + name="min_age", + context=player, + expression="context Player inv: self.age > 10", + language="OCL", + ) + }, + ) + + def test_method_with_code_after_clean_compiles(self): + birthday = Method(name="birthday", code="def birthday(self):\n self.age += 1\n return self.age\n") + output = _render_models(self._model([birthday])) + compile(output, "", "exec") + assert " raise ValidationError(errors)\n\n def birthday(self):" in output + + def test_method_without_code_after_clean_compiles(self): + output = _render_models(self._model([Method(name="older")])) + compile(output, "", "exec") + assert " def older(self):" in output diff --git a/tests/generators/docker_compose/test_docker_compose_generator.py b/tests/generators/docker_compose/test_docker_compose_generator.py index debb55726..1aba0e138 100644 --- a/tests/generators/docker_compose/test_docker_compose_generator.py +++ b/tests/generators/docker_compose/test_docker_compose_generator.py @@ -329,19 +329,22 @@ def test_a1_end_to_end_bracket_n_to_replicas(tmp_path): json_data = { "title": "A1 swarm test", "model": { - "elements": { - "node-001": { - "type": "DeploymentNode", - "name": "Backend", - "stereotype": "executionEnvironment", + "version": "4.0.0", + "type": "DeploymentDiagram", + "nodes": [ + { + "id": "node-001", + "type": "deploymentNode", + "data": {"name": "Backend", "stereotype": "executionEnvironment"}, }, - "artifact-001": { - "type": "DeploymentArtifact", - "name": "Foo [3]", - "owner": "node-001", + { + "id": "artifact-001", + "type": "deploymentArtifact", + "parentId": "node-001", + "data": {"name": "Foo [3]"}, }, - }, - "relationships": {}, + ], + "edges": [], }, } diff --git a/tests/generators/docker_compose/test_docker_runtime_config.py b/tests/generators/docker_compose/test_docker_runtime_config.py index e9be42eb8..3745090f9 100644 --- a/tests/generators/docker_compose/test_docker_runtime_config.py +++ b/tests/generators/docker_compose/test_docker_runtime_config.py @@ -16,6 +16,10 @@ from besser.generators.docker_compose.runtime_config import resolve_runtime_yaml +# A non-empty v4 AgentDiagram model (the route skips diagrams without nodes). +_AGENT_MODEL = {'version': '4.0.0', 'type': 'AgentDiagram', 'nodes': [{'id': 'dummy'}], 'edges': []} + + def _yaml(a2a=8000, websocket=8765, streamlit=5000): return yaml.safe_dump({ 'nlp': {'language': 'ca', 'openai': {'api_key': 'test-only-placeholder'}}, @@ -132,9 +136,9 @@ def test_deployment_route_forwards_uuid_settings_and_normalizes_profiles(monkeyp captured = {} normalized = [] - entries = [DiagramInput(id='first', title='First', model={'elements': {'dummy': {}}}, + entries = [DiagramInput(id='first', title='First', model=_AGENT_MODEL, config={'agentPlatform': 'websocket'}, configYaml=_yaml(a2a=9001)), - DiagramInput(id='second', title='Second', model={'elements': {'dummy': {}}}, + DiagramInput(id='second', title='Second', model=_AGENT_MODEL, config={'personalizationMapping': [{'user_profile': {'raw': True}}]}, configYaml=_yaml(a2a=9002))] saved = deepcopy(entries) diff --git a/tests/generators/fixtures/library_template_agent_diagram.json b/tests/generators/fixtures/library_template_agent_diagram.json index 8291e8d73..82bc6f810 100644 --- a/tests/generators/fixtures/library_template_agent_diagram.json +++ b/tests/generators/fixtures/library_template_agent_diagram.json @@ -1,674 +1,582 @@ { "title": "Library Agent", "model": { - "version": "3.0.0", + "version": "4.0.0", + "id": "converted-diagram-1778241725884", + "title": "", "type": "AgentDiagram", - "size": { - "width": 1660, - "height": 640 - }, - "interactive": { - "elements": {}, - "relationships": {} - }, - "elements": { - "initial_72th6ksf3_mm9b38u1": { - "id": "initial_72th6ksf3_mm9b38u1", - "name": "", - "type": "StateInitialNode", - "owner": null, - "bounds": { - "x": -810, - "y": -130, - "width": 45, - "height": 45 - } - }, - "state_zl3bfe65n_mm9b38u1": { + "nodes": [ + { "id": "state_zl3bfe65n_mm9b38u1", - "name": "Idle", "type": "AgentState", - "owner": null, - "bounds": { + "position": { "x": -170, - "y": -30, + "y": -30 + }, + "width": 260, + "height": 70, + "measured": { "width": 260, "height": 70 }, - "stateType": "standard", - "fallbackBodyEnabled": true, - "actions": [ - "body_wybm5pc31_mm9b38u1" - ], - "fallbackActions": [], - "bodies": [ - "body_wybm5pc31_mm9b38u1" - ], - "fallbackBodies": [] - }, - "body_wybm5pc31_mm9b38u1": { - "id": "body_wybm5pc31_mm9b38u1", - "name": "How can I assist you today?", - "type": "AgentStateBody", - "owner": "state_zl3bfe65n_mm9b38u1", - "bounds": { - "x": -169.5, - "y": 10.5, - "width": 259, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" + "data": { + "name": "Idle", + "replyType": "text", + "stateType": "standard", + "fallbackBodyEnabled": true, + "bodies": [ + { + "id": "body_wybm5pc31_mm9b38u1", + "name": "How can I assist you today?", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + } + ] + } }, - "state_j5tnma02n_mm9b38u1": { + { "id": "state_j5tnma02n_mm9b38u1", - "name": "OpeningHoursState", "type": "AgentState", - "owner": null, - "bounds": { + "position": { "x": 390, - "y": -40, + "y": -40 + }, + "width": 420, + "height": 100, + "measured": { "width": 420, "height": 100 }, - "stateType": "standard", - "fallbackBodyEnabled": true, - "actions": [ - "body_a8ph8sxrt_mm9b38u1", - "fb1432f7-1778-4c8b-90f3-e471e86cec31" - ], - "fallbackActions": [], - "bodies": [ - "body_a8ph8sxrt_mm9b38u1", - "fb1432f7-1778-4c8b-90f3-e471e86cec31" - ], - "fallbackBodies": [] - }, - "body_a8ph8sxrt_mm9b38u1": { - "id": "body_a8ph8sxrt_mm9b38u1", - "name": "Our opening hours are Monday\u2013Friday 9 AM\u20136 PM.", - "type": "AgentStateBody", - "owner": "state_j5tnma02n_mm9b38u1", - "bounds": { - "x": 390.5, - "y": 0.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" - }, - "fb1432f7-1778-4c8b-90f3-e471e86cec31": { - "id": "fb1432f7-1778-4c8b-90f3-e471e86cec31", - "name": "Saturday 10 AM\u20134 PM. Closed Sunday.", - "type": "AgentStateBody", - "owner": "state_j5tnma02n_mm9b38u1", - "bounds": { - "x": 390.5, - "y": 30.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" + "data": { + "name": "OpeningHoursState", + "replyType": "text", + "stateType": "standard", + "fallbackBodyEnabled": true, + "bodies": [ + { + "id": "body_a8ph8sxrt_mm9b38u1", + "name": "Our opening hours are Monday–Friday 9 AM–6 PM.", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + }, + { + "id": "fb1432f7-1778-4c8b-90f3-e471e86cec31", + "name": "Saturday 10 AM–4 PM. Closed Sunday.", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + } + ] + } }, - "state_krso67h8q_mm9b38u1": { + { "id": "state_krso67h8q_mm9b38u1", - "name": "CheapestBookState", "type": "AgentState", - "owner": null, - "bounds": { + "position": { "x": 390, - "y": -260, + "y": -260 + }, + "width": 420, + "height": 190, + "measured": { "width": 420, "height": 190 }, - "stateType": "standard", - "fallbackBodyEnabled": true, - "actions": [ - "body_38x5jthwr_mm9b38u1", - "body_0yl3shkws_mm9b38u1", - "b533e6a5-cc51-4f0d-a269-98bf81a02c31", - "7c8e27fb-8cce-4f3d-9cc4-19ef5a963b8a", - "b779be48-1bc4-4984-9274-00c91203552a" - ], - "fallbackActions": [], - "bodies": [ - "body_38x5jthwr_mm9b38u1", - "body_0yl3shkws_mm9b38u1", - "b533e6a5-cc51-4f0d-a269-98bf81a02c31", - "7c8e27fb-8cce-4f3d-9cc4-19ef5a963b8a", - "b779be48-1bc4-4984-9274-00c91203552a" - ], - "fallbackBodies": [] - }, - "body_38x5jthwr_mm9b38u1": { - "id": "body_38x5jthwr_mm9b38u1", - "name": "To get the cheapest book of an author, follow these steps:", - "type": "AgentStateBody", - "owner": "state_krso67h8q_mm9b38u1", - "bounds": { - "x": 390.5, - "y": -219.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" - }, - "body_0yl3shkws_mm9b38u1": { - "id": "body_0yl3shkws_mm9b38u1", - "name": "1. Go to the Library tab.", - "type": "AgentStateBody", - "owner": "state_krso67h8q_mm9b38u1", - "bounds": { - "x": 390.5, - "y": -189.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" - }, - "b533e6a5-cc51-4f0d-a269-98bf81a02c31": { - "id": "b533e6a5-cc51-4f0d-a269-98bf81a02c31", - "name": "2. In the table, select the library where you want to search.", - "type": "AgentStateBody", - "owner": "state_krso67h8q_mm9b38u1", - "bounds": { - "x": 390.5, - "y": -159.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" - }, - "7c8e27fb-8cce-4f3d-9cc4-19ef5a963b8a": { - "id": "7c8e27fb-8cce-4f3d-9cc4-19ef5a963b8a", - "name": "3. Click on \u201cCheapest Book\u201d.", - "type": "AgentStateBody", - "owner": "state_krso67h8q_mm9b38u1", - "bounds": { - "x": 390.5, - "y": -129.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" - }, - "b779be48-1bc4-4984-9274-00c91203552a": { - "id": "b779be48-1bc4-4984-9274-00c91203552a", - "name": "4. Select an author and click \u201cExecute\u201d.", - "type": "AgentStateBody", - "owner": "state_krso67h8q_mm9b38u1", - "bounds": { - "x": 390.5, - "y": -99.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" + "data": { + "name": "CheapestBookState", + "replyType": "text", + "stateType": "standard", + "fallbackBodyEnabled": true, + "bodies": [ + { + "id": "body_38x5jthwr_mm9b38u1", + "name": "To get the cheapest book of an author, follow these steps:", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + }, + { + "id": "body_0yl3shkws_mm9b38u1", + "name": "1. Go to the Library tab.", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + }, + { + "id": "b533e6a5-cc51-4f0d-a269-98bf81a02c31", + "name": "2. In the table, select the library where you want to search.", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + }, + { + "id": "7c8e27fb-8cce-4f3d-9cc4-19ef5a963b8a", + "name": "3. Click on “Cheapest Book”.", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + }, + { + "id": "b779be48-1bc4-4984-9274-00c91203552a", + "name": "4. Select an author and click “Execute”.", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + } + ] + } }, - "state_5emfhqwzt_mm9b38u1": { + { "id": "state_5emfhqwzt_mm9b38u1", - "name": "ContactState", "type": "AgentState", - "owner": null, - "bounds": { + "position": { "x": 390, - "y": 160, + "y": 160 + }, + "width": 420, + "height": 100, + "measured": { "width": 420, "height": 100 }, - "stateType": "standard", - "fallbackBodyEnabled": true, - "actions": [ - "body_b6vkku4r1_mm9b38u1", - "body_8i8n5kbs0_mm9b38u1" - ], - "fallbackActions": [], - "bodies": [ - "body_b6vkku4r1_mm9b38u1", - "body_8i8n5kbs0_mm9b38u1" - ], - "fallbackBodies": [] - }, - "body_b6vkku4r1_mm9b38u1": { - "id": "body_b6vkku4r1_mm9b38u1", - "name": "You can contact a librarian at library@example.com or call +1 555-123-4567.", - "type": "AgentStateBody", - "owner": "state_5emfhqwzt_mm9b38u1", - "bounds": { - "x": 390.5, - "y": 200.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" - }, - "body_8i8n5kbs0_mm9b38u1": { - "id": "body_8i8n5kbs0_mm9b38u1", - "name": "They will get back to you shortly.", - "type": "AgentStateBody", - "owner": "state_5emfhqwzt_mm9b38u1", - "bounds": { - "x": 390.5, - "y": 230.5, - "width": 419, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" + "data": { + "name": "ContactState", + "replyType": "text", + "stateType": "standard", + "fallbackBodyEnabled": true, + "bodies": [ + { + "id": "body_b6vkku4r1_mm9b38u1", + "name": "You can contact a librarian at library@example.com or call +1 555-123-4567.", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + }, + { + "id": "body_8i8n5kbs0_mm9b38u1", + "name": "They will get back to you shortly.", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + } + ] + } }, - "46badadf-e50d-481e-8246-3ba2393fce47": { + { "id": "46badadf-e50d-481e-8246-3ba2393fce47", - "name": "Greeting", "type": "AgentState", - "owner": null, - "bounds": { + "position": { "x": -670, - "y": -140, + "y": -140 + }, + "width": 340, + "height": 70, + "measured": { "width": 340, "height": 70 }, - "stateType": "standard", - "fallbackBodyEnabled": true, - "actions": [ - "e3aad61a-89b4-46a6-8c16-6f80b861d717" - ], - "fallbackActions": [], - "bodies": [ - "e3aad61a-89b4-46a6-8c16-6f80b861d717" - ], - "fallbackBodies": [] + "data": { + "name": "Greeting", + "replyType": "text", + "stateType": "standard", + "fallbackBodyEnabled": true, + "bodies": [ + { + "id": "e3aad61a-89b4-46a6-8c16-6f80b861d717", + "name": "Welcome to the library support system!", + "replyType": "text", + "actionType": "TextReplyAction", + "useSessionVars": false, + "llm_name": "" + } + ] + } }, - "e3aad61a-89b4-46a6-8c16-6f80b861d717": { - "id": "e3aad61a-89b4-46a6-8c16-6f80b861d717", - "name": "Welcome to the library support system!", - "type": "AgentStateBody", - "owner": "46badadf-e50d-481e-8246-3ba2393fce47", - "bounds": { - "x": -669.5, - "y": -99.5, - "width": 339, - "height": 30 - }, - "actionType": "TextReplyAction", - "replyType": "text", - "useSessionVars": false, - "llm_name": "" - } - }, - "relationships": { - "transition_ixdyt9fr7_mm9b38u1": { - "id": "transition_ixdyt9fr7_mm9b38u1", - "name": "", - "type": "AgentStateTransitionInit", - "owner": null, - "bounds": { - "x": -765, - "y": -107.5, - "width": 95, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 95, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "initial_72th6ksf3_mm9b38u1" + { + "id": "46badadf-e50d-481e-8246-3ba2393fce47__initial", + "type": "StateInitialNode", + "position": { + "x": -790, + "y": -127.5 }, - "target": { - "direction": "Left", - "element": "46badadf-e50d-481e-8246-3ba2393fce47" + "width": 45, + "height": 45, + "measured": { + "width": 45, + "height": 45 }, - "isManuallyLayouted": false - }, - "transition_x8h483xz2_mm9b38u1": { + "data": { + "name": "" + } + } + ], + "edges": [ + { "id": "transition_x8h483xz2_mm9b38u1", - "name": "", + "source": "state_zl3bfe65n_mm9b38u1", + "target": "state_j5tnma02n_mm9b38u1", "type": "AgentStateTransition", - "owner": null, - "bounds": { - "x": 90, - "y": 5, - "width": 300, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 + "sourceHandle": "right-top", + "targetHandle": "left-top", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "transitionType": "predefined", + "predefined": { + "predefinedType": "when_intent_matched", + "intentName": "OpeningHours" }, - { - "x": 300, - "y": 0 - } - ], - "source": { - "direction": "Upright", - "element": "state_zl3bfe65n_mm9b38u1" - }, - "target": { - "direction": "Upleft", - "element": "state_j5tnma02n_mm9b38u1" - }, - "isManuallyLayouted": false, - "transitionType": "predefined", - "predefined": { - "predefinedType": "when_intent_matched", - "intentName": "OpeningHours" - }, - "custom": { - "condition": [] + "legacyShape": 1, + "legacy": { + "transitionType": "predefined", + "predefined": { + "predefinedType": "when_intent_matched", + "intentName": "OpeningHours" + }, + "custom": { + "condition": [] + } + }, + "points": [ + { + "x": 90, + "y": 5 + }, + { + "x": 390, + "y": 5 + } + ] } }, - "transition_53oz6z5cc_mm9b38u1": { + { "id": "transition_53oz6z5cc_mm9b38u1", - "name": "", + "source": "state_zl3bfe65n_mm9b38u1", + "target": "state_krso67h8q_mm9b38u1", "type": "AgentStateTransition", - "owner": null, - "bounds": { - "x": 25, - "y": -165, - "width": 365, - "height": 135 - }, - "path": [ - { - "x": 0, - "y": 135 + "sourceHandle": "top-right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "transitionType": "predefined", + "predefined": { + "predefinedType": "when_intent_matched", + "intentName": "CheapestBook" }, - { - "x": 0, - "y": 0 + "legacyShape": 1, + "legacy": { + "transitionType": "predefined", + "predefined": { + "predefinedType": "when_intent_matched", + "intentName": "CheapestBook" + }, + "custom": { + "condition": [] + } }, - { - "x": 365, - "y": 0 - } - ], - "source": { - "direction": "Topright", - "element": "state_zl3bfe65n_mm9b38u1" - }, - "target": { - "direction": "Left", - "element": "state_krso67h8q_mm9b38u1" - }, - "isManuallyLayouted": false, - "transitionType": "predefined", - "predefined": { - "predefinedType": "when_intent_matched", - "intentName": "CheapestBook" - }, - "custom": { - "condition": [] + "points": [ + { + "x": 25, + "y": -30 + }, + { + "x": 25, + "y": -165 + }, + { + "x": 390, + "y": -165 + } + ] } }, - "transition_jc0mk7kpn_mm9b38u1": { + { "id": "transition_jc0mk7kpn_mm9b38u1", - "name": "", + "source": "state_zl3bfe65n_mm9b38u1", + "target": "state_5emfhqwzt_mm9b38u1", "type": "AgentStateTransition", - "owner": null, - "bounds": { - "x": 25, - "y": 40, - "width": 365, - "height": 170 - }, - "path": [ - { - "x": 0, - "y": 0 + "sourceHandle": "bottom-right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "transitionType": "predefined", + "predefined": { + "predefinedType": "when_intent_matched", + "intentName": "Contact" }, - { - "x": 0, - "y": 170 + "legacyShape": 1, + "legacy": { + "transitionType": "predefined", + "predefined": { + "predefinedType": "when_intent_matched", + "intentName": "Contact" + }, + "custom": { + "condition": [] + } }, - { - "x": 365, - "y": 170 - } - ], - "source": { - "direction": "Bottomright", - "element": "state_zl3bfe65n_mm9b38u1" - }, - "target": { - "direction": "Left", - "element": "state_5emfhqwzt_mm9b38u1" - }, - "isManuallyLayouted": false, - "transitionType": "predefined", - "predefined": { - "predefinedType": "when_intent_matched", - "intentName": "Contact" - }, - "custom": { - "condition": [] + "points": [ + { + "x": 25, + "y": 40 + }, + { + "x": 25, + "y": 210 + }, + { + "x": 390, + "y": 210 + } + ] } }, - "transition_zuuhzl5f9_mm9b38u1": { + { "id": "transition_zuuhzl5f9_mm9b38u1", - "name": "", + "source": "state_krso67h8q_mm9b38u1", + "target": "state_zl3bfe65n_mm9b38u1", "type": "AgentStateTransition", - "owner": null, - "bounds": { - "x": -40, - "y": -212.5, - "width": 430, - "height": 182.5 - }, - "path": [ - { - "x": 430, - "y": 0 + "sourceHandle": "left-top", + "targetHandle": "top", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "transitionType": "predefined", + "predefined": { + "predefinedType": "auto", + "conditionValue": "" }, - { - "x": 0, - "y": 0 + "legacyShape": 1, + "legacy": { + "transitionType": "predefined", + "predefined": { + "predefinedType": "auto", + "conditionValue": "" + }, + "custom": { + "condition": [] + } }, - { - "x": 0, - "y": 182.5 - } - ], - "source": { - "direction": "Upleft", - "element": "state_krso67h8q_mm9b38u1" - }, - "target": { - "direction": "Up", - "element": "state_zl3bfe65n_mm9b38u1" - }, - "isManuallyLayouted": false, - "transitionType": "predefined", - "predefined": { - "predefinedType": "auto", - "conditionValue": "" - }, - "custom": { - "condition": [] + "points": [ + { + "x": 390, + "y": -212.5 + }, + { + "x": -40, + "y": -212.5 + }, + { + "x": -40, + "y": -30 + } + ] } }, - "transition_rjozmqoco_mm9b38u1": { + { "id": "transition_rjozmqoco_mm9b38u1", - "name": "", + "source": "state_5emfhqwzt_mm9b38u1", + "target": "state_zl3bfe65n_mm9b38u1", "type": "AgentStateTransition", - "owner": null, - "bounds": { - "x": -40, - "y": 40, - "width": 640, - "height": 260 - }, - "path": [ - { - "x": 640, - "y": 220 - }, - { - "x": 640, - "y": 260 + "sourceHandle": "bottom", + "targetHandle": "bottom", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "transitionType": "predefined", + "predefined": { + "predefinedType": "auto", + "conditionValue": "" }, - { - "x": 0, - "y": 260 + "legacyShape": 1, + "legacy": { + "transitionType": "predefined", + "predefined": { + "predefinedType": "auto", + "conditionValue": "" + }, + "custom": { + "condition": [] + } }, - { - "x": 0, - "y": 0 - } - ], - "source": { - "direction": "Down", - "element": "state_5emfhqwzt_mm9b38u1" - }, - "target": { - "direction": "Down", - "element": "state_zl3bfe65n_mm9b38u1" - }, - "isManuallyLayouted": false, - "transitionType": "predefined", - "predefined": { - "predefinedType": "auto", - "conditionValue": "" - }, - "custom": { - "condition": [] + "points": [ + { + "x": 600, + "y": 260 + }, + { + "x": 600, + "y": 300 + }, + { + "x": -40, + "y": 300 + }, + { + "x": -40, + "y": 40 + } + ] } }, - "5f574d18-6641-4c80-bd19-92b862b47b7c": { + { "id": "5f574d18-6641-4c80-bd19-92b862b47b7c", - "name": "", + "source": "state_j5tnma02n_mm9b38u1", + "target": "state_zl3bfe65n_mm9b38u1", "type": "AgentStateTransition", - "owner": null, - "bounds": { - "x": 90, - "y": 22.5, - "width": 405, - "height": 77.5 - }, - "path": [ - { - "x": 405, - "y": 37.5 - }, - { - "x": 405, - "y": 77.5 - }, - { - "x": 150, - "y": 77.5 + "sourceHandle": "bottom-left", + "targetHandle": "right-bottom", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "transitionType": "predefined", + "predefined": { + "predefinedType": "auto", + "conditionValue": "" }, - { - "x": 150, - "y": 0 + "legacyShape": 1, + "legacy": { + "transitionType": "predefined", + "predefined": { + "predefinedType": "auto", + "conditionValue": "" + }, + "custom": { + "condition": [] + } }, - { - "x": 0, - "y": 0 - } - ], - "source": { - "direction": "Bottomleft", - "element": "state_j5tnma02n_mm9b38u1" - }, - "target": { - "direction": "Downright", - "element": "state_zl3bfe65n_mm9b38u1" - }, - "isManuallyLayouted": false, - "transitionType": "predefined", - "predefined": { - "predefinedType": "auto", - "conditionValue": "" - }, - "custom": { - "condition": [] + "points": [ + { + "x": 495, + "y": 60 + }, + { + "x": 495, + "y": 100 + }, + { + "x": 240, + "y": 100 + }, + { + "x": 240, + "y": 22.5 + }, + { + "x": 90, + "y": 22.5 + } + ] } }, - "5cf30015-c8cf-47be-8ad0-80bbba94d35e": { + { "id": "5cf30015-c8cf-47be-8ad0-80bbba94d35e", - "name": "", + "source": "46badadf-e50d-481e-8246-3ba2393fce47", + "target": "state_zl3bfe65n_mm9b38u1", "type": "AgentStateTransition", - "owner": null, - "bounds": { - "x": -330, - "y": -87.5, - "width": 160, - "height": 92.5 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 80, - "y": 0 + "sourceHandle": "right-bottom", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "transitionType": "predefined", + "predefined": { + "predefinedType": "auto", + "conditionValue": "" }, - { - "x": 80, - "y": 92.5 + "legacyShape": 1, + "legacy": { + "transitionType": "predefined", + "predefined": { + "predefinedType": "auto", + "conditionValue": "" + }, + "custom": { + "condition": [] + } }, - { - "x": 160, - "y": 92.5 - } - ], - "source": { - "direction": "Downright", - "element": "46badadf-e50d-481e-8246-3ba2393fce47" - }, - "target": { - "direction": "Left", - "element": "state_zl3bfe65n_mm9b38u1" - }, - "isManuallyLayouted": false, - "transitionType": "predefined", - "predefined": { - "predefinedType": "auto", - "conditionValue": "" - }, - "custom": { - "condition": [] + "points": [ + { + "x": -330, + "y": -87.5 + }, + { + "x": -250, + "y": -87.5 + }, + { + "x": -250, + "y": 5 + }, + { + "x": -170, + "y": 5 + } + ] + } + }, + { + "id": "46badadf-e50d-481e-8246-3ba2393fce47__initial-edge", + "type": "AgentStateTransitionInit", + "source": "46badadf-e50d-481e-8246-3ba2393fce47__initial", + "target": "46badadf-e50d-481e-8246-3ba2393fce47", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "params": {}, + "points": [] } } - }, + ], "assessments": {}, "components": { "7018084a-2566-49a9-ac3b-2f8c353c3d63": { diff --git a/tests/generators/fixtures/library_template_class_diagram.json b/tests/generators/fixtures/library_template_class_diagram.json index 222844f51..be4811df9 100644 --- a/tests/generators/fixtures/library_template_class_diagram.json +++ b/tests/generators/fixtures/library_template_class_diagram.json @@ -1,753 +1,487 @@ { "title": "Library", "model": { - "version": "3.0.0", + "version": "4.0.0", + "id": "converted-diagram-1778241725884", + "title": "", "type": "ClassDiagram", - "size": { - "width": 1460, - "height": 800 - }, - "interactive": { - "elements": {}, - "relationships": {} - }, - "elements": { - "class_oho5ergc3_mjikkmod": { + "nodes": [ + { "id": "class_oho5ergc3_mjikkmod", - "name": "Book", - "type": "Class", - "owner": null, - "bounds": { + "type": "class", + "position": { "x": -434, - "y": -345, + "y": -345 + }, + "width": 240, + "height": 215, + "measured": { "width": 240, "height": 215 }, - "attributes": [ - "attr_a87fqdtdi_mjikkmod", - "attr_v6ve12d44_mjikkmod", - "attr_edi3c3l8k_mjikkmod", - "attr_mczftcqfb_mjikkmod", - "attr_785suq5yn_mjikkmod", - "attr_urp7jb0c0_mjikkmod" - ], - "methods": [ - "method_rb01uirsh_mjikkmod" - ] - }, - "attr_a87fqdtdi_mjikkmod": { - "id": "attr_a87fqdtdi_mjikkmod", - "name": "title", - "type": "ClassAttribute", - "owner": "class_oho5ergc3_mjikkmod", - "bounds": { - "x": -433.5, - "y": -304.5, - "width": 239, - "height": 25 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "attr_v6ve12d44_mjikkmod": { - "id": "attr_v6ve12d44_mjikkmod", - "name": "pages", - "type": "ClassAttribute", - "owner": "class_oho5ergc3_mjikkmod", - "bounds": { - "x": -433.5, - "y": -279.5, - "width": 239, - "height": 25 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "attr_edi3c3l8k_mjikkmod": { - "id": "attr_edi3c3l8k_mjikkmod", - "name": "stock", - "type": "ClassAttribute", - "owner": "class_oho5ergc3_mjikkmod", - "bounds": { - "x": -433.5, - "y": -254.5, - "width": 239, - "height": 25 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "attr_mczftcqfb_mjikkmod": { - "id": "attr_mczftcqfb_mjikkmod", - "name": "price", - "type": "ClassAttribute", - "owner": "class_oho5ergc3_mjikkmod", - "bounds": { - "x": -433.5, - "y": -229.5, - "width": 239, - "height": 25 - }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "attr_785suq5yn_mjikkmod": { - "id": "attr_785suq5yn_mjikkmod", - "name": "release", - "type": "ClassAttribute", - "owner": "class_oho5ergc3_mjikkmod", - "bounds": { - "x": -433.5, - "y": -204.5, - "width": 239, - "height": 25 - }, - "code": "", - "visibility": "public", - "attributeType": "date", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "attr_urp7jb0c0_mjikkmod": { - "id": "attr_urp7jb0c0_mjikkmod", - "name": "genre", - "type": "ClassAttribute", - "owner": "class_oho5ergc3_mjikkmod", - "bounds": { - "x": -433.5, - "y": -179.5, - "width": 239, - "height": 25 - }, - "code": "", - "visibility": "public", - "attributeType": "Genre", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "method_rb01uirsh_mjikkmod": { - "id": "method_rb01uirsh_mjikkmod", - "name": "+ decrease_stock(qty: int)", - "type": "ClassMethod", - "owner": "class_oho5ergc3_mjikkmod", - "bounds": { - "x": -433.5, - "y": -154.5, - "width": 239, - "height": 25 - }, - "code": "def decrease_stock(self, qty: int):\n \"\"\"\n Decrease the available stock by the given quantity.\n\n :param qty: Number of items to remove from stock\n :raises ValueError: If qty is negative or exceeds available stock\n \"\"\"\n if qty <= 0:\n raise ValueError(\"Quantity must be a positive integer\")\n\n if qty > self.stock:\n raise ValueError(\n f\"Cannot decrease stock by {qty}. Only {self.stock} items available.\"\n )\n\n self.stock -= qty\n\n", - "visibility": "public", - "attributeType": "int): any", - "implementationType": "code", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false + "data": { + "name": "Book", + "methods": [ + { + "id": "method_rb01uirsh_mjikkmod", + "name": "decrease_stock", + "visibility": "public", + "attributeType": "", + "code": "def decrease_stock(self, qty: int):\n \"\"\"\n Decrease the available stock by the given quantity.\n\n :param qty: Number of items to remove from stock\n :raises ValueError: If qty is negative or exceeds available stock\n \"\"\"\n if qty <= 0:\n raise ValueError(\"Quantity must be a positive integer\")\n\n if qty > self.stock:\n raise ValueError(\n f\"Cannot decrease stock by {qty}. Only {self.stock} items available.\"\n )\n\n self.stock -= qty\n\n", + "implementationType": "code", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false, + "returnType": "", + "parameters": [ + { + "name": "qty", + "parameterType": "int", + "id": "method_rb01uirsh_mjikkmod-param-0" + } + ] + } + ], + "attributes": [ + { + "id": "attr_a87fqdtdi_mjikkmod", + "name": "title", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_v6ve12d44_mjikkmod", + "name": "pages", + "visibility": "public", + "attributeType": "int", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_edi3c3l8k_mjikkmod", + "name": "stock", + "visibility": "public", + "attributeType": "int", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_mczftcqfb_mjikkmod", + "name": "price", + "visibility": "public", + "attributeType": "float", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_785suq5yn_mjikkmod", + "name": "release", + "visibility": "public", + "attributeType": "date", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_urp7jb0c0_mjikkmod", + "name": "genre", + "visibility": "public", + "attributeType": "Genre", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ] + } }, - "class_06blhjj3h_mjikkmod": { + { "id": "class_06blhjj3h_mjikkmod", - "name": "Library", - "type": "Class", - "owner": null, - "bounds": { + "type": "class", + "position": { "x": -60, - "y": -150, + "y": -150 + }, + "width": 350, + "height": 185, + "measured": { "width": 350, "height": 185 }, - "attributes": [ - "attr_eryfh37kl_mjikkmod", - "f9608e0e-745d-4113-85ad-cd06b1900c09", - "4391886d-13b5-4fa0-9894-09f1894af27f", - "a487fd85-dec0-47b9-bd37-71ff92026963" - ], - "methods": [ - "35ef5329-889b-40f0-89ce-9836936fd8a9" - ] - }, - "attr_eryfh37kl_mjikkmod": { - "id": "attr_eryfh37kl_mjikkmod", - "name": "name", - "type": "ClassAttribute", - "owner": "class_06blhjj3h_mjikkmod", - "bounds": { - "x": -59.5, - "y": -109.5, - "width": 349, - "height": 25 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "f9608e0e-745d-4113-85ad-cd06b1900c09": { - "id": "f9608e0e-745d-4113-85ad-cd06b1900c09", - "name": "web_page", - "type": "ClassAttribute", - "owner": "class_06blhjj3h_mjikkmod", - "bounds": { - "x": -59.5, - "y": -84.5, - "width": 349, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "4391886d-13b5-4fa0-9894-09f1894af27f": { - "id": "4391886d-13b5-4fa0-9894-09f1894af27f", - "name": "address", - "type": "ClassAttribute", - "owner": "class_06blhjj3h_mjikkmod", - "bounds": { - "x": -59.5, - "y": -54.5, - "width": 349, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false + "data": { + "name": "Library", + "methods": [ + { + "id": "35ef5329-889b-40f0-89ce-9836936fd8a9", + "name": "cheapest_book_by", + "visibility": "public", + "attributeType": "str", + "code": "def cheapest_book_by(author:Author) -> str {\n cheapest:Book = null;\n\tprice = 1000000000.0;\n\tfor(book in this.books){\n if(book.authors.contains(author)\n\t\t\t&& book.price <= price){\n cheapest = book;\n\t\t\tprice = book.price;\n\t\t}\n }\n\treturn cheapest.title;\n}", + "implementationType": "bal", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false, + "returnType": "str", + "parameters": [ + { + "name": "author", + "parameterType": "Author", + "id": "35ef5329-889b-40f0-89ce-9836936fd8a9-param-0" + } + ] + } + ], + "attributes": [ + { + "id": "attr_eryfh37kl_mjikkmod", + "name": "name", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "f9608e0e-745d-4113-85ad-cd06b1900c09", + "name": "web_page", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "4391886d-13b5-4fa0-9894-09f1894af27f", + "name": "address", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "a487fd85-dec0-47b9-bd37-71ff92026963", + "name": "telephone", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ] + } }, - "a487fd85-dec0-47b9-bd37-71ff92026963": { - "id": "a487fd85-dec0-47b9-bd37-71ff92026963", - "name": "telephone", - "type": "ClassAttribute", - "owner": "class_06blhjj3h_mjikkmod", - "bounds": { - "x": -59.5, - "y": -24.5, - "width": 349, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "35ef5329-889b-40f0-89ce-9836936fd8a9": { - "id": "35ef5329-889b-40f0-89ce-9836936fd8a9", - "name": "+ cheapest_book_by(author:Author): str", - "type": "ClassMethod", - "owner": "class_06blhjj3h_mjikkmod", - "bounds": { - "x": -59.5, - "y": 5.5, - "width": 349, - "height": 30 - }, - "code": "def cheapest_book_by(author:Author) -> str {\n cheapest:Book = null;\n\tprice = 1000000000.0;\n\tfor(book in this.books){\n if(book.authors.contains(author)\n\t\t\t&& book.price <= price){\n cheapest = book;\n\t\t\tprice = book.price;\n\t\t}\n }\n\treturn cheapest.title;\n}", - "visibility": "public", - "attributeType": "str", - "implementationType": "bal", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "class_d3f0di6lb_mjikkmoe": { + { "id": "class_d3f0di6lb_mjikkmoe", - "name": "Author", - "type": "Class", - "owner": null, - "bounds": { + "type": "class", + "position": { "x": 10, - "y": -380, + "y": -380 + }, + "width": 220, + "height": 95, + "measured": { "width": 220, "height": 95 }, - "attributes": [ - "attr_p3zqpt65k_mjikkmoe", - "4321afe8-8ec2-48da-a0ec-b2ce9ccaf1db" - ], - "methods": [] + "data": { + "name": "Author", + "methods": [], + "attributes": [ + { + "id": "attr_p3zqpt65k_mjikkmoe", + "name": "name", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "4321afe8-8ec2-48da-a0ec-b2ce9ccaf1db", + "name": "birth", + "visibility": "public", + "attributeType": "date", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ] + } }, - "attr_p3zqpt65k_mjikkmoe": { - "id": "attr_p3zqpt65k_mjikkmoe", - "name": "name", - "type": "ClassAttribute", - "owner": "class_d3f0di6lb_mjikkmoe", - "bounds": { - "x": 10.5, - "y": -339.5, - "width": 219, - "height": 25 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "4321afe8-8ec2-48da-a0ec-b2ce9ccaf1db": { - "id": "4321afe8-8ec2-48da-a0ec-b2ce9ccaf1db", - "name": "birth", - "type": "ClassAttribute", - "owner": "class_d3f0di6lb_mjikkmoe", - "bounds": { - "x": 10.5, - "y": -314.5, - "width": 219, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "date", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "50ffa27f-f8a9-438b-b81b-174266f39952": { + { "id": "50ffa27f-f8a9-438b-b81b-174266f39952", - "name": "Genre", - "type": "Enumeration", - "owner": null, - "bounds": { + "type": "class", + "position": { "x": -710, - "y": -220, + "y": -220 + }, + "width": 160, + "height": 350, + "measured": { "width": 160, "height": 350 }, - "attributes": [ - "bfadf7ef-e6a4-43e3-b267-672be745c9c7", - "15d10eca-11e8-4894-8b27-d815dbc62596", - "55346119-1f08-48c5-9629-b5223ea766e0", - "67e73142-470c-4795-8864-96f08365ce49", - "4ba07b68-1fd2-40fc-ad63-05766965aaad", - "52114e47-c8c1-404a-847c-0b877de007e0", - "65937dfa-011b-425e-a292-7d66dff5cd36", - "994869fb-9b98-450f-add4-a2ee88a15c7f", - "45fa6842-da64-4878-b875-c536f06f1d50", - "6d81aaec-327a-42b9-89db-a17e54bb7b5a" - ], - "methods": [] - }, - "bfadf7ef-e6a4-43e3-b267-672be745c9c7": { - "id": "bfadf7ef-e6a4-43e3-b267-672be745c9c7", - "name": "Poetry", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": -169.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "15d10eca-11e8-4894-8b27-d815dbc62596": { - "id": "15d10eca-11e8-4894-8b27-d815dbc62596", - "name": "Thriller", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": -139.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "55346119-1f08-48c5-9629-b5223ea766e0": { - "id": "55346119-1f08-48c5-9629-b5223ea766e0", - "name": "History", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": -109.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false + "data": { + "name": "Genre", + "methods": [], + "attributes": [ + { + "id": "bfadf7ef-e6a4-43e3-b267-672be745c9c7", + "name": "Poetry", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "15d10eca-11e8-4894-8b27-d815dbc62596", + "name": "Thriller", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "55346119-1f08-48c5-9629-b5223ea766e0", + "name": "History", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "67e73142-470c-4795-8864-96f08365ce49", + "name": "Technology", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "4ba07b68-1fd2-40fc-ad63-05766965aaad", + "name": "Romance", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "52114e47-c8c1-404a-847c-0b877de007e0", + "name": "Horror", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "65937dfa-011b-425e-a292-7d66dff5cd36", + "name": "Adventure", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "994869fb-9b98-450f-add4-a2ee88a15c7f", + "name": "Philosophy", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "45fa6842-da64-4878-b875-c536f06f1d50", + "name": "Cookbooks", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "6d81aaec-327a-42b9-89db-a17e54bb7b5a", + "name": "Fantasy", + "visibility": "public", + "attributeType": "str", + "code": "", + "implementationType": "none", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "stereotype": "Enumeration" + } }, - "67e73142-470c-4795-8864-96f08365ce49": { - "id": "67e73142-470c-4795-8864-96f08365ce49", - "name": "Technology", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": -79.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "4ba07b68-1fd2-40fc-ad63-05766965aaad": { - "id": "4ba07b68-1fd2-40fc-ad63-05766965aaad", - "name": "Romance", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": -49.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "52114e47-c8c1-404a-847c-0b877de007e0": { - "id": "52114e47-c8c1-404a-847c-0b877de007e0", - "name": "Horror", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": -19.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "65937dfa-011b-425e-a292-7d66dff5cd36": { - "id": "65937dfa-011b-425e-a292-7d66dff5cd36", - "name": "Adventure", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": 10.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "994869fb-9b98-450f-add4-a2ee88a15c7f": { - "id": "994869fb-9b98-450f-add4-a2ee88a15c7f", - "name": "Philosophy", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": 40.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "45fa6842-da64-4878-b875-c536f06f1d50": { - "id": "45fa6842-da64-4878-b875-c536f06f1d50", - "name": "Cookbooks", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": 70.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "6d81aaec-327a-42b9-89db-a17e54bb7b5a": { - "id": "6d81aaec-327a-42b9-89db-a17e54bb7b5a", - "name": "Fantasy", - "type": "ClassAttribute", - "owner": "50ffa27f-f8a9-438b-b81b-174266f39952", - "bounds": { - "x": -709.5, - "y": 100.5, - "width": 159, - "height": 30 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false - }, - "de57bf9a-a91f-4c69-9ad0-4879e2222edd": { + { "id": "de57bf9a-a91f-4c69-9ad0-4879e2222edd", - "name": "", "type": "ClassOCLConstraint", - "owner": null, - "bounds": { + "position": { "x": -710, - "y": -380, + "y": -380 + }, + "width": 210, + "height": 90, + "measured": { "width": 210, "height": 90 }, - "constraint": "context Book inv inv1: self.pages> 10" + "data": { + "name": "", + "expression": "context Book inv inv1: self.pages> 10" + } } - }, - "relationships": { - "rel_z26fdxrdq_mjikkmoe": { + ], + "edges": [ + { "id": "rel_z26fdxrdq_mjikkmoe", - "name": "books", + "source": "class_06blhjj3h_mjikkmod", + "target": "class_oho5ergc3_mjikkmod", "type": "ClassBidirectional", - "owner": null, - "bounds": { - "x": -194, - "y": -247.5, - "width": 134, - "height": 228 - }, - "path": [ - { - "x": 134, - "y": 190 - }, - { - "x": 67, - "y": 190 - }, - { - "x": 67, - "y": 10 - }, - { - "x": 0, - "y": 10 - } - ], - "source": { - "direction": "Left", - "element": "class_06blhjj3h_mjikkmod", - "multiplicity": "1..*", - "role": "library", - "bounds": { - "x": 0, - "y": 0, - "width": 0, - "height": 0 - }, - "navigable": true - }, - "target": { - "direction": "Right", - "element": "class_oho5ergc3_mjikkmod", - "multiplicity": "*", - "role": "books", - "bounds": { - "x": 0, - "y": 0, - "width": 0, - "height": 0 - }, - "navigable": true - }, - "isManuallyLayouted": false + "sourceHandle": "left", + "targetHandle": "right", + "data": { + "label": "books", + "name": "books", + "sourceMultiplicity": "1..*", + "targetMultiplicity": "*", + "sourceRole": "library", + "targetRole": "books", + "sourceNavigable": true, + "targetNavigable": true, + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -60, + "y": -57.5 + }, + { + "x": -127, + "y": -57.5 + }, + { + "x": -127, + "y": -237.5 + }, + { + "x": -194, + "y": -237.5 + } + ] + } }, - "rel_0ys2qxzq1_mjikkmoe": { + { "id": "rel_0ys2qxzq1_mjikkmoe", - "name": "books", + "source": "class_d3f0di6lb_mjikkmoe", + "target": "class_oho5ergc3_mjikkmod", "type": "ClassBidirectional", - "owner": null, - "bounds": { - "x": -194, - "y": -325, - "width": 204, - "height": 48 - }, - "path": [ - { - "x": 204, - "y": 10 - }, - { - "x": 0, - "y": 10 - } - ], - "source": { - "direction": "Left", - "element": "class_d3f0di6lb_mjikkmoe", - "multiplicity": "1..*", - "role": "authors", - "bounds": { - "x": 0, - "y": 0, - "width": 0, - "height": 0 - }, - "navigable": true - }, - "target": { - "direction": "Right", - "element": "class_oho5ergc3_mjikkmod", - "multiplicity": "*", - "role": "books", - "bounds": { - "x": 0, - "y": 0, - "width": 0, - "height": 0 - }, - "navigable": true - }, - "isManuallyLayouted": false + "sourceHandle": "left", + "targetHandle": "right", + "data": { + "label": "books", + "name": "books", + "sourceMultiplicity": "1..*", + "targetMultiplicity": "*", + "sourceRole": "authors", + "targetRole": "books", + "sourceNavigable": true, + "targetNavigable": true, + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": 10, + "y": -315 + }, + { + "x": -194, + "y": -315 + } + ] + } } - }, + ], "assessments": {} } -} \ No newline at end of file +} diff --git a/tests/generators/nn/test_nn_generation_regressions.py b/tests/generators/nn/test_nn_generation_regressions.py index 2a3d329cb..2060e5137 100644 --- a/tests/generators/nn/test_nn_generation_regressions.py +++ b/tests/generators/nn/test_nn_generation_regressions.py @@ -10,11 +10,13 @@ from besser.BUML.metamodel.nn import ( NN, + Conv2D, FlattenLayer, LinearLayer, PoolingLayer, TensorOp, ) +from besser.generators.nn.pytorch.pytorch_code_generator import PytorchGenerator from besser.generators.nn.tf.tf_code_generator import TFGenerator from besser.generators.nn.tf.utils_tf import get_tensorop_syntax @@ -110,3 +112,28 @@ def test_tf_pad_rejects_untranslatable_shapes(): input_var="x") with pytest.raises(ValueError, match="pad_amount"): get_tensorop_syntax(op, {}, in_var="x") + + +@pytest.mark.parametrize("generator_cls, file_name", [ + (PytorchGenerator, "pytorch_nn_sequential.py"), + (TFGenerator, "tf_nn_sequential.py"), +]) +def test_sequential_generation_with_a_sub_network(tmp_path, generator_cls, file_name): + """AlexNet-style ``features`` block: a sub-NN's details are a dict, so + reading ``details[1]`` as its output variable raised KeyError (HTTP 500).""" + features: NN = NN(name="features") + features.add_layer(Conv2D(name="c1", kernel_dim=[3, 3], in_channels=3, out_channels=8, + actv_func="relu")) + features.add_layer(PoolingLayer(name="p1", pooling_type="max", dimension="2D", + kernel_dim=[2, 2])) + nn_model: NN = NN(name="alex") + nn_model.add_sub_nn(features) + nn_model.add_layer(FlattenLayer(name="f1")) + nn_model.add_layer(LinearLayer(name="l1", in_features=8, out_features=2)) + + out_dir = str(tmp_path / "seq") + generator_cls(model=nn_model, output_dir=out_dir, generation_type="sequential").generate() + with open(os.path.join(out_dir, file_name), encoding="utf-8") as f: + code = f.read() + compile(code, file_name, "exec") + assert "features" in code diff --git a/tests/generators/pydantic/fixtures/hotel_class_diagram.json b/tests/generators/pydantic/fixtures/hotel_class_diagram.json index 11d9dc519..bd96693dd 100644 --- a/tests/generators/pydantic/fixtures/hotel_class_diagram.json +++ b/tests/generators/pydantic/fixtures/hotel_class_diagram.json @@ -1,72 +1,862 @@ { "title": "Class Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class_2vb9jr4yc_mu7ieunf_l9p": {"id": "class_2vb9jr4yc_mu7ieunf_l9p", "name": "Person", "type": "Class", "owner": null, "attributes": ["attr_137b7ofxo_mu7ieunf_tqx", "attr_7rrd8b60h_mu7ieunf_w69", "attr_5radimdwq_mu7ieunf_irj", "attr_tzv5eeb38_mu7ieunf_osf", "attr_kfrst3v1i_mu7ieunf_5az", "attr_s6gbyez5r_mu7ieunf_3yr"], "methods": []}, - "attr_137b7ofxo_mu7ieunf_tqx": {"id": "attr_137b7ofxo_mu7ieunf_tqx", "name": "id", "type": "ClassAttribute", "owner": "class_2vb9jr4yc_mu7ieunf_l9p", "code": "", "visibility": "public", "attributeType": "int", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_7rrd8b60h_mu7ieunf_w69": {"id": "attr_7rrd8b60h_mu7ieunf_w69", "name": "identifyingNumber", "type": "ClassAttribute", "owner": "class_2vb9jr4yc_mu7ieunf_l9p", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": true}, - "attr_5radimdwq_mu7ieunf_irj": {"id": "attr_5radimdwq_mu7ieunf_irj", "name": "firstName", "type": "ClassAttribute", "owner": "class_2vb9jr4yc_mu7ieunf_l9p", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_tzv5eeb38_mu7ieunf_osf": {"id": "attr_tzv5eeb38_mu7ieunf_osf", "name": "familyName", "type": "ClassAttribute", "owner": "class_2vb9jr4yc_mu7ieunf_l9p", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_kfrst3v1i_mu7ieunf_5az": {"id": "attr_kfrst3v1i_mu7ieunf_5az", "name": "phone", "type": "ClassAttribute", "owner": "class_2vb9jr4yc_mu7ieunf_l9p", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_s6gbyez5r_mu7ieunf_3yr": {"id": "attr_s6gbyez5r_mu7ieunf_3yr", "name": "email", "type": "ClassAttribute", "owner": "class_2vb9jr4yc_mu7ieunf_l9p", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "class_trt2pfaa4_mu7ieunf_kvf": {"id": "class_trt2pfaa4_mu7ieunf_kvf", "name": "Employee", "type": "AbstractClass", "owner": null, "attributes": [], "methods": []}, - "class_t166jgxi2_mu7ieunf_4d2": {"id": "class_t166jgxi2_mu7ieunf_4d2", "name": "Guest", "type": "AbstractClass", "owner": null, "attributes": [], "methods": []}, - "class_e9ggzl13o_mu7ieunf_qqw": {"id": "class_e9ggzl13o_mu7ieunf_qqw", "name": "Room", "type": "Class", "owner": null, "attributes": ["attr_m0jgiuvsi_mu7ieunf_3mx", "attr_7xsc9sdlj_mu7ieunf_6gn", "attr_licqewbw0_mu7ieunf_drb", "attr_fuqjak27r_mu7ieunf_f1f", "attr_01zkkthc0_mu7ieunf_6uq"], "methods": []}, - "attr_m0jgiuvsi_mu7ieunf_3mx": {"id": "attr_m0jgiuvsi_mu7ieunf_3mx", "name": "id", "type": "ClassAttribute", "owner": "class_e9ggzl13o_mu7ieunf_qqw", "code": "", "visibility": "public", "attributeType": "int", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_7xsc9sdlj_mu7ieunf_6gn": {"id": "attr_7xsc9sdlj_mu7ieunf_6gn", "name": "roomNumber", "type": "ClassAttribute", "owner": "class_e9ggzl13o_mu7ieunf_qqw", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": true}, - "attr_licqewbw0_mu7ieunf_drb": {"id": "attr_licqewbw0_mu7ieunf_drb", "name": "maxOccupancy", "type": "ClassAttribute", "owner": "class_e9ggzl13o_mu7ieunf_qqw", "code": "", "visibility": "public", "attributeType": "int", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_fuqjak27r_mu7ieunf_f1f": {"id": "attr_fuqjak27r_mu7ieunf_f1f", "name": "description", "type": "ClassAttribute", "owner": "class_e9ggzl13o_mu7ieunf_qqw", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_01zkkthc0_mu7ieunf_6uq": {"id": "attr_01zkkthc0_mu7ieunf_6uq", "name": "standardPrice", "type": "ClassAttribute", "owner": "class_e9ggzl13o_mu7ieunf_qqw", "code": "", "visibility": "public", "attributeType": "float", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "class_bsml8y91t_mu7ieunf_dut": {"id": "class_bsml8y91t_mu7ieunf_dut", "name": "BookingCommercialStatus", "type": "Enumeration", "owner": null, "attributes": ["attr_9shat154a_mu7ieunf_mze", "attr_8g0f5vw4g_mu7ieunf_xbh", "attr_wiq6ajqql_mu7ieunf_81z"], "methods": []}, - "attr_9shat154a_mu7ieunf_mze": {"id": "attr_9shat154a_mu7ieunf_mze", "name": "AWAITING_PAYMENT", "type": "ClassAttribute", "owner": "class_bsml8y91t_mu7ieunf_dut", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_8g0f5vw4g_mu7ieunf_xbh": {"id": "attr_8g0f5vw4g_mu7ieunf_xbh", "name": "CONFIRMED", "type": "ClassAttribute", "owner": "class_bsml8y91t_mu7ieunf_dut", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_wiq6ajqql_mu7ieunf_81z": {"id": "attr_wiq6ajqql_mu7ieunf_81z", "name": "CANCELLED", "type": "ClassAttribute", "owner": "class_bsml8y91t_mu7ieunf_dut", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "class_cyxh0umwq_mu7ieunf_6z0": {"id": "class_cyxh0umwq_mu7ieunf_6z0", "name": "BookingPhysicalStatus", "type": "Enumeration", "owner": null, "attributes": ["attr_bu8gxc5eb_mu7ieunf_xhp", "attr_69i5nboz0_mu7ieunf_ggk", "attr_68lnp8t5w_mu7ieunf_kj7"], "methods": []}, - "attr_bu8gxc5eb_mu7ieunf_xhp": {"id": "attr_bu8gxc5eb_mu7ieunf_xhp", "name": "NOT_YET_ARRIVED", "type": "ClassAttribute", "owner": "class_cyxh0umwq_mu7ieunf_6z0", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_69i5nboz0_mu7ieunf_ggk": {"id": "attr_69i5nboz0_mu7ieunf_ggk", "name": "CHECKED_IN", "type": "ClassAttribute", "owner": "class_cyxh0umwq_mu7ieunf_6z0", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_68lnp8t5w_mu7ieunf_kj7": {"id": "attr_68lnp8t5w_mu7ieunf_kj7", "name": "CHECKED_OUT", "type": "ClassAttribute", "owner": "class_cyxh0umwq_mu7ieunf_6z0", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "class_jqybaoo04_mu7ieunf_bn5": {"id": "class_jqybaoo04_mu7ieunf_bn5", "name": "Booking", "type": "Class", "owner": null, "attributes": ["attr_6a1f1yofy_mu7ieunf_w4t", "attr_feli1gfcg_mu7ieunf_ovc", "attr_5zlkf2g43_mu7ieunf_ag3", "attr_bxw45qgw3_mu7ieunf_ve8", "attr_y0adojddk_mu7ieunf_f5t", "attr_vij8lkjey_mu7ieunf_16b", "attr_8x509eted_mu7ieunf_00c"], "methods": ["method_jb5tcyrhs_mu7ieunf_s68", "method_bk03s2lz8_mu7ieunf_r2j", "method_z4jkxnodk_mu7ieunf_8cq", "method_m0e9tte3r_mu7ieunf_fm7", "method_5mwmxnci5_mu7ieunf_n9p"]}, - "attr_6a1f1yofy_mu7ieunf_w4t": {"id": "attr_6a1f1yofy_mu7ieunf_w4t", "name": "id", "type": "ClassAttribute", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "int", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_feli1gfcg_mu7ieunf_ovc": {"id": "attr_feli1gfcg_mu7ieunf_ovc", "name": "bookingNumber", "type": "ClassAttribute", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": true}, - "attr_5zlkf2g43_mu7ieunf_ag3": {"id": "attr_5zlkf2g43_mu7ieunf_ag3", "name": "arrivalDate", "type": "ClassAttribute", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "date", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_bxw45qgw3_mu7ieunf_ve8": {"id": "attr_bxw45qgw3_mu7ieunf_ve8", "name": "departureDate", "type": "ClassAttribute", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "date", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_y0adojddk_mu7ieunf_f5t": {"id": "attr_y0adojddk_mu7ieunf_f5t", "name": "commercialStatus", "type": "ClassAttribute", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "BookingCommercialStatus", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": true, "isId": false, "isExternalId": false}, - "attr_vij8lkjey_mu7ieunf_16b": {"id": "attr_vij8lkjey_mu7ieunf_16b", "name": "physicalStatus", "type": "ClassAttribute", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "BookingPhysicalStatus", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": true, "isId": false, "isExternalId": false}, - "attr_8x509eted_mu7ieunf_00c": {"id": "attr_8x509eted_mu7ieunf_00c", "name": "totalPrice", "type": "ClassAttribute", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "float", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": true, "isId": false, "isExternalId": false}, - "method_jb5tcyrhs_mu7ieunf_s68": {"id": "method_jb5tcyrhs_mu7ieunf_s68", "name": "produceBill()", "type": "ClassMethod", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "bool", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "method_bk03s2lz8_mu7ieunf_r2j": {"id": "method_bk03s2lz8_mu7ieunf_r2j", "name": "registerArrival()", "type": "ClassMethod", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "bool", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "method_z4jkxnodk_mu7ieunf_8cq": {"id": "method_z4jkxnodk_mu7ieunf_8cq", "name": "registerDeparture()", "type": "ClassMethod", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "bool", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "method_m0e9tte3r_mu7ieunf_fm7": {"id": "method_m0e9tte3r_mu7ieunf_fm7", "name": "cancel()", "type": "ClassMethod", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "bool", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "method_5mwmxnci5_mu7ieunf_n9p": {"id": "method_5mwmxnci5_mu7ieunf_n9p", "name": "computeAmountOwed()", "type": "ClassMethod", "owner": "class_jqybaoo04_mu7ieunf_bn5", "code": "", "visibility": "public", "attributeType": "float", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "class_r8t9pltt6_mu7ieunf_gy1": {"id": "class_r8t9pltt6_mu7ieunf_gy1", "name": "ReservedRoom", "type": "Class", "owner": null, "attributes": ["attr_dqalotw5n_mu7ieunf_bo2", "attr_v5mryd86p_mu7ieunf_d73", "attr_3qwx8xg51_mu7ieunf_cvb"], "methods": []}, - "attr_dqalotw5n_mu7ieunf_bo2": {"id": "attr_dqalotw5n_mu7ieunf_bo2", "name": "id", "type": "ClassAttribute", "owner": "class_r8t9pltt6_mu7ieunf_gy1", "code": "", "visibility": "public", "attributeType": "int", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_v5mryd86p_mu7ieunf_d73": {"id": "attr_v5mryd86p_mu7ieunf_d73", "name": "agreedPrice", "type": "ClassAttribute", "owner": "class_r8t9pltt6_mu7ieunf_gy1", "code": "", "visibility": "public", "attributeType": "float", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_3qwx8xg51_mu7ieunf_cvb": {"id": "attr_3qwx8xg51_mu7ieunf_cvb", "name": "extraCharges", "type": "ClassAttribute", "owner": "class_r8t9pltt6_mu7ieunf_gy1", "code": "", "visibility": "public", "attributeType": "float", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "class_1wpg30up3_mu7ieung_bh0": {"id": "class_1wpg30up3_mu7ieung_bh0", "name": "Bill", "type": "Class", "owner": null, "attributes": ["attr_gqwnbk0w6_mu7ieung_u3j", "attr_nxck0rx7x_mu7ieung_st0", "attr_ybm2vklnb_mu7ieung_i2f", "attr_tm6xohy8j_mu7ieung_tb7", "attr_vuqe7i9iz_mu7ieung_k55"], "methods": ["method_k7ttve4vr_mu7ieung_rkc"]}, - "attr_gqwnbk0w6_mu7ieung_u3j": {"id": "attr_gqwnbk0w6_mu7ieung_u3j", "name": "id", "type": "ClassAttribute", "owner": "class_1wpg30up3_mu7ieung_bh0", "code": "", "visibility": "public", "attributeType": "int", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_nxck0rx7x_mu7ieung_st0": {"id": "attr_nxck0rx7x_mu7ieung_st0", "name": "billNumber", "type": "ClassAttribute", "owner": "class_1wpg30up3_mu7ieung_bh0", "code": "", "visibility": "public", "attributeType": "str", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": true}, - "attr_ybm2vklnb_mu7ieung_i2f": {"id": "attr_ybm2vklnb_mu7ieung_i2f", "name": "issuedDate", "type": "ClassAttribute", "owner": "class_1wpg30up3_mu7ieung_bh0", "code": "", "visibility": "public", "attributeType": "date", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_tm6xohy8j_mu7ieung_tb7": {"id": "attr_tm6xohy8j_mu7ieung_tb7", "name": "totalAmountDue", "type": "ClassAttribute", "owner": "class_1wpg30up3_mu7ieung_bh0", "code": "", "visibility": "public", "attributeType": "float", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "attr_vuqe7i9iz_mu7ieung_k55": {"id": "attr_vuqe7i9iz_mu7ieung_k55", "name": "settled", "type": "ClassAttribute", "owner": "class_1wpg30up3_mu7ieung_bh0", "code": "", "visibility": "public", "attributeType": "bool", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "method_k7ttve4vr_mu7ieung_rkc": {"id": "method_k7ttve4vr_mu7ieung_rkc", "name": "registerPayment()", "type": "ClassMethod", "owner": "class_1wpg30up3_mu7ieung_bh0", "code": "", "visibility": "public", "attributeType": "bool", "implementationType": "none", "stateMachineId": "", "quantumCircuitId": "", "isOptional": false, "isDerived": false, "isId": false, "isExternalId": false}, - "ocl_6nabls1jg_mu7ieung_w37": {"id": "ocl_6nabls1jg_mu7ieung_w37", "name": "", "type": "ClassOCLConstraint", "owner": null, "description": "", "constraint": "context Person inv validEmail: self.email.matches('^[^\\s@]+@[^\\s@]+\\.[A-Za-z]{2,}$')\n\ncontext Person inv validPhone: self.phone.matches('^\\+?[0-9]{7,15}$')"}, - "ocl_jyb9dtxcg_mu7ieung_q6e": {"id": "ocl_jyb9dtxcg_mu7ieung_q6e", "name": "", "type": "ClassOCLConstraint", "owner": null, "description": "", "constraint": "context Booking inv arrivalBeforeDeparture: self.arrivalDate <= self.departureDate\n\ncontext Booking inv guestsWithinCapacity: self.guests->size() <= self.rooms->collect(maxOccupancy)->sum()"}, - "ocl_ccum3m92y_mu7ieung_fz6": {"id": "ocl_ccum3m92y_mu7ieung_fz6", "name": "", "type": "ClassOCLConstraint", "owner": null, "description": "", "constraint": "context Room inv noOverlappingBookings: self.bookings->forAll(b1, b2 | b1 <> b2 implies b1.departureDate <= b2.arrivalDate or b2.departureDate <= b1.arrivalDate)"} - }, - "relationships": { - "rel_4l5240nbt_mu7ieung_taq": {"id": "rel_4l5240nbt_mu7ieung_taq", "name": "", "type": "ClassInheritance", "owner": null, "source": {"element": "class_trt2pfaa4_mu7ieunf_kvf", "multiplicity": "1", "role": ""}, "target": {"element": "class_2vb9jr4yc_mu7ieunf_l9p", "multiplicity": "1", "role": ""}}, - "rel_yedxwj2il_mu7ieung_85d": {"id": "rel_yedxwj2il_mu7ieung_85d", "name": "", "type": "ClassInheritance", "owner": null, "source": {"element": "class_t166jgxi2_mu7ieunf_4d2", "multiplicity": "1", "role": ""}, "target": {"element": "class_2vb9jr4yc_mu7ieunf_l9p", "multiplicity": "1", "role": ""}}, - "rel_4aqarvgdw_mu7ieung_h6s": {"id": "rel_4aqarvgdw_mu7ieung_h6s", "name": "contact", "type": "ClassBidirectional", "owner": null, "source": {"element": "class_jqybaoo04_mu7ieunf_bn5", "multiplicity": "0..*", "role": ""}, "target": {"element": "class_2vb9jr4yc_mu7ieunf_l9p", "multiplicity": "1", "role": "contact"}}, - "rel_cx29ls8vv_mu7ieung_j44": {"id": "rel_cx29ls8vv_mu7ieung_j44", "name": "guests", "type": "ClassBidirectional", "owner": null, "source": {"element": "class_t166jgxi2_mu7ieunf_4d2", "multiplicity": "1..*", "role": ""}, "target": {"element": "class_jqybaoo04_mu7ieunf_bn5", "multiplicity": "0..*", "role": "guests"}}, - "rel_2985ttxpf_mu7ieung_iin": {"id": "rel_2985ttxpf_mu7ieung_iin", "name": "handledBy", "type": "ClassBidirectional", "owner": null, "source": {"element": "class_trt2pfaa4_mu7ieunf_kvf", "multiplicity": "1", "role": ""}, "target": {"element": "class_jqybaoo04_mu7ieunf_bn5", "multiplicity": "0..*", "role": "handledBy"}}, - "rel_6rre31swa_mu7ieung_6bv": {"id": "rel_6rre31swa_mu7ieung_6bv", "name": "rooms", "type": "ClassBidirectional", "owner": null, "source": {"element": "class_jqybaoo04_mu7ieunf_bn5", "multiplicity": "0..*", "role": ""}, "target": {"element": "class_e9ggzl13o_mu7ieunf_qqw", "multiplicity": "1..*", "role": "rooms"}}, - "classlink_d882tel7g_mu7ieung_9sy": {"id": "classlink_d882tel7g_mu7ieung_9sy", "name": "", "type": "ClassLinkRel", "owner": null, "source": {"element": "class_r8t9pltt6_mu7ieunf_gy1", "multiplicity": "", "role": ""}, "target": {"element": "rel_6rre31swa_mu7ieung_6bv", "multiplicity": "", "role": ""}}, - "rel_del02h87r_mu7ieung_496": {"id": "rel_del02h87r_mu7ieung_496", "name": "bill", "type": "ClassBidirectional", "owner": null, "source": {"element": "class_jqybaoo04_mu7ieunf_bn5", "multiplicity": "1", "role": ""}, "target": {"element": "class_1wpg30up3_mu7ieung_bh0", "multiplicity": "0..1", "role": "bill"}}, - "ocllink_hbjv76j5m_mu7ieung_pq3": {"id": "ocllink_hbjv76j5m_mu7ieung_pq3", "name": "", "type": "ClassOCLLink", "owner": null, "source": {"element": "ocl_6nabls1jg_mu7ieung_w37", "multiplicity": "", "role": ""}, "target": {"element": "class_2vb9jr4yc_mu7ieunf_l9p", "multiplicity": "", "role": ""}}, - "ocllink_2vn83brhi_mu7ieung_ddx": {"id": "ocllink_2vn83brhi_mu7ieung_ddx", "name": "", "type": "ClassOCLLink", "owner": null, "source": {"element": "ocl_jyb9dtxcg_mu7ieung_q6e", "multiplicity": "", "role": ""}, "target": {"element": "class_jqybaoo04_mu7ieunf_bn5", "multiplicity": "", "role": ""}}, - "ocllink_um3738yr7_mu7ieung_gez": {"id": "ocllink_um3738yr7_mu7ieung_gez", "name": "", "type": "ClassOCLLink", "owner": null, "source": {"element": "ocl_ccum3m92y_mu7ieung_fz6", "multiplicity": "", "role": ""}, "target": {"element": "class_e9ggzl13o_mu7ieunf_qqw", "multiplicity": "", "role": ""}} - } + "nodes": [ + { + "id": "class_2vb9jr4yc_mu7ieunf_l9p", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "Person", + "stereotype": null, + "attributes": [ + { + "id": "attr_137b7ofxo_mu7ieunf_tqx", + "name": "id", + "code": "", + "visibility": "public", + "attributeType": "int", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_7rrd8b60h_mu7ieunf_w69", + "name": "identifyingNumber", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": true + }, + { + "id": "attr_5radimdwq_mu7ieunf_irj", + "name": "firstName", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_tzv5eeb38_mu7ieunf_osf", + "name": "familyName", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_kfrst3v1i_mu7ieunf_5az", + "name": "phone", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_s6gbyez5r_mu7ieunf_3yr", + "name": "email", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "methods": [] + } + }, + { + "id": "class_trt2pfaa4_mu7ieunf_kvf", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "Employee", + "stereotype": "Abstract", + "attributes": [], + "methods": [] + } + }, + { + "id": "class_t166jgxi2_mu7ieunf_4d2", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "Guest", + "stereotype": "Abstract", + "attributes": [], + "methods": [] + } + }, + { + "id": "class_e9ggzl13o_mu7ieunf_qqw", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "Room", + "stereotype": null, + "attributes": [ + { + "id": "attr_m0jgiuvsi_mu7ieunf_3mx", + "name": "id", + "code": "", + "visibility": "public", + "attributeType": "int", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_7xsc9sdlj_mu7ieunf_6gn", + "name": "roomNumber", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": true + }, + { + "id": "attr_licqewbw0_mu7ieunf_drb", + "name": "maxOccupancy", + "code": "", + "visibility": "public", + "attributeType": "int", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_fuqjak27r_mu7ieunf_f1f", + "name": "description", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_01zkkthc0_mu7ieunf_6uq", + "name": "standardPrice", + "code": "", + "visibility": "public", + "attributeType": "float", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "methods": [] + } + }, + { + "id": "class_bsml8y91t_mu7ieunf_dut", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "BookingCommercialStatus", + "stereotype": "Enumeration", + "attributes": [ + { + "id": "attr_9shat154a_mu7ieunf_mze", + "name": "AWAITING_PAYMENT", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_8g0f5vw4g_mu7ieunf_xbh", + "name": "CONFIRMED", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_wiq6ajqql_mu7ieunf_81z", + "name": "CANCELLED", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "methods": [] + } + }, + { + "id": "class_cyxh0umwq_mu7ieunf_6z0", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "BookingPhysicalStatus", + "stereotype": "Enumeration", + "attributes": [ + { + "id": "attr_bu8gxc5eb_mu7ieunf_xhp", + "name": "NOT_YET_ARRIVED", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_69i5nboz0_mu7ieunf_ggk", + "name": "CHECKED_IN", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_68lnp8t5w_mu7ieunf_kj7", + "name": "CHECKED_OUT", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "methods": [] + } + }, + { + "id": "class_jqybaoo04_mu7ieunf_bn5", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "Booking", + "stereotype": null, + "attributes": [ + { + "id": "attr_6a1f1yofy_mu7ieunf_w4t", + "name": "id", + "code": "", + "visibility": "public", + "attributeType": "int", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_feli1gfcg_mu7ieunf_ovc", + "name": "bookingNumber", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": true + }, + { + "id": "attr_5zlkf2g43_mu7ieunf_ag3", + "name": "arrivalDate", + "code": "", + "visibility": "public", + "attributeType": "date", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_bxw45qgw3_mu7ieunf_ve8", + "name": "departureDate", + "code": "", + "visibility": "public", + "attributeType": "date", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_y0adojddk_mu7ieunf_f5t", + "name": "commercialStatus", + "code": "", + "visibility": "public", + "attributeType": "BookingCommercialStatus", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": true, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_vij8lkjey_mu7ieunf_16b", + "name": "physicalStatus", + "code": "", + "visibility": "public", + "attributeType": "BookingPhysicalStatus", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": true, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_8x509eted_mu7ieunf_00c", + "name": "totalPrice", + "code": "", + "visibility": "public", + "attributeType": "float", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": true, + "isId": false, + "isExternalId": false + } + ], + "methods": [ + { + "id": "method_jb5tcyrhs_mu7ieunf_s68", + "name": "produceBill()", + "code": "", + "visibility": "public", + "attributeType": "bool", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "method_bk03s2lz8_mu7ieunf_r2j", + "name": "registerArrival()", + "code": "", + "visibility": "public", + "attributeType": "bool", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "method_z4jkxnodk_mu7ieunf_8cq", + "name": "registerDeparture()", + "code": "", + "visibility": "public", + "attributeType": "bool", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "method_m0e9tte3r_mu7ieunf_fm7", + "name": "cancel()", + "code": "", + "visibility": "public", + "attributeType": "bool", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "method_5mwmxnci5_mu7ieunf_n9p", + "name": "computeAmountOwed()", + "code": "", + "visibility": "public", + "attributeType": "float", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ] + } + }, + { + "id": "class_r8t9pltt6_mu7ieunf_gy1", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "ReservedRoom", + "stereotype": null, + "attributes": [ + { + "id": "attr_dqalotw5n_mu7ieunf_bo2", + "name": "id", + "code": "", + "visibility": "public", + "attributeType": "int", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_v5mryd86p_mu7ieunf_d73", + "name": "agreedPrice", + "code": "", + "visibility": "public", + "attributeType": "float", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_3qwx8xg51_mu7ieunf_cvb", + "name": "extraCharges", + "code": "", + "visibility": "public", + "attributeType": "float", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "methods": [] + } + }, + { + "id": "class_1wpg30up3_mu7ieung_bh0", + "type": "class", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "Bill", + "stereotype": null, + "attributes": [ + { + "id": "attr_gqwnbk0w6_mu7ieung_u3j", + "name": "id", + "code": "", + "visibility": "public", + "attributeType": "int", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_nxck0rx7x_mu7ieung_st0", + "name": "billNumber", + "code": "", + "visibility": "public", + "attributeType": "str", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": true + }, + { + "id": "attr_ybm2vklnb_mu7ieung_i2f", + "name": "issuedDate", + "code": "", + "visibility": "public", + "attributeType": "date", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_tm6xohy8j_mu7ieung_tb7", + "name": "totalAmountDue", + "code": "", + "visibility": "public", + "attributeType": "float", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + }, + { + "id": "attr_vuqe7i9iz_mu7ieung_k55", + "name": "settled", + "code": "", + "visibility": "public", + "attributeType": "bool", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ], + "methods": [ + { + "id": "method_k7ttve4vr_mu7ieung_rkc", + "name": "registerPayment()", + "code": "", + "visibility": "public", + "attributeType": "bool", + "implementationType": "none", + "stateMachineId": "", + "quantumCircuitId": "", + "isOptional": false, + "isDerived": false, + "isId": false, + "isExternalId": false + } + ] + } + }, + { + "id": "ocl_6nabls1jg_mu7ieung_w37", + "type": "ClassOCLConstraint", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "", + "expression": "context Person inv validEmail: self.email.matches('^[^\\s@]+@[^\\s@]+\\.[A-Za-z]{2,}$')\n\ncontext Person inv validPhone: self.phone.matches('^\\+?[0-9]{7,15}$')" + } + }, + { + "id": "ocl_jyb9dtxcg_mu7ieung_q6e", + "type": "ClassOCLConstraint", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "", + "expression": "context Booking inv arrivalBeforeDeparture: self.arrivalDate <= self.departureDate\n\ncontext Booking inv guestsWithinCapacity: self.guests->size() <= self.rooms->collect(maxOccupancy)->sum()" + } + }, + { + "id": "ocl_ccum3m92y_mu7ieung_fz6", + "type": "ClassOCLConstraint", + "position": { + "x": 0, + "y": 0 + }, + "width": 160, + "height": 100, + "data": { + "name": "", + "expression": "context Room inv noOverlappingBookings: self.bookings->forAll(b1, b2 | b1 <> b2 implies b1.departureDate <= b2.arrivalDate or b2.departureDate <= b1.arrivalDate)" + } + } + ], + "edges": [ + { + "id": "rel_4l5240nbt_mu7ieung_taq", + "type": "ClassInheritance", + "source": "class_trt2pfaa4_mu7ieunf_kvf", + "target": "class_2vb9jr4yc_mu7ieunf_l9p", + "data": { + "points": [] + } + }, + { + "id": "rel_yedxwj2il_mu7ieung_85d", + "type": "ClassInheritance", + "source": "class_t166jgxi2_mu7ieunf_4d2", + "target": "class_2vb9jr4yc_mu7ieunf_l9p", + "data": { + "points": [] + } + }, + { + "id": "rel_4aqarvgdw_mu7ieung_h6s", + "type": "ClassBidirectional", + "source": "class_jqybaoo04_mu7ieunf_bn5", + "target": "class_2vb9jr4yc_mu7ieunf_l9p", + "data": { + "points": [], + "name": "contact", + "sourceRole": "", + "sourceMultiplicity": "0..*", + "targetRole": "contact", + "targetMultiplicity": "1" + } + }, + { + "id": "rel_cx29ls8vv_mu7ieung_j44", + "type": "ClassBidirectional", + "source": "class_t166jgxi2_mu7ieunf_4d2", + "target": "class_jqybaoo04_mu7ieunf_bn5", + "data": { + "points": [], + "name": "guests", + "sourceRole": "", + "sourceMultiplicity": "1..*", + "targetRole": "guests", + "targetMultiplicity": "0..*" + } + }, + { + "id": "rel_2985ttxpf_mu7ieung_iin", + "type": "ClassBidirectional", + "source": "class_trt2pfaa4_mu7ieunf_kvf", + "target": "class_jqybaoo04_mu7ieunf_bn5", + "data": { + "points": [], + "name": "handledBy", + "sourceRole": "", + "sourceMultiplicity": "1", + "targetRole": "handledBy", + "targetMultiplicity": "0..*" + } + }, + { + "id": "rel_6rre31swa_mu7ieung_6bv", + "type": "ClassBidirectional", + "source": "class_jqybaoo04_mu7ieunf_bn5", + "target": "class_e9ggzl13o_mu7ieunf_qqw", + "data": { + "points": [], + "name": "rooms", + "sourceRole": "", + "sourceMultiplicity": "0..*", + "targetRole": "rooms", + "targetMultiplicity": "1..*" + } + }, + { + "id": "classlink_d882tel7g_mu7ieung_9sy", + "type": "ClassLinkRel", + "source": "class_r8t9pltt6_mu7ieunf_gy1", + "target": "rel_6rre31swa_mu7ieung_6bv", + "data": { + "points": [] + } + }, + { + "id": "rel_del02h87r_mu7ieung_496", + "type": "ClassBidirectional", + "source": "class_jqybaoo04_mu7ieunf_bn5", + "target": "class_1wpg30up3_mu7ieung_bh0", + "data": { + "points": [], + "name": "bill", + "sourceRole": "", + "sourceMultiplicity": "1", + "targetRole": "bill", + "targetMultiplicity": "0..1" + } + }, + { + "id": "ocllink_hbjv76j5m_mu7ieung_pq3", + "type": "ClassOCLLink", + "source": "ocl_6nabls1jg_mu7ieung_w37", + "target": "class_2vb9jr4yc_mu7ieunf_l9p", + "data": { + "points": [] + } + }, + { + "id": "ocllink_2vn83brhi_mu7ieung_ddx", + "type": "ClassOCLLink", + "source": "ocl_jyb9dtxcg_mu7ieung_q6e", + "target": "class_jqybaoo04_mu7ieunf_bn5", + "data": { + "points": [] + } + }, + { + "id": "ocllink_um3738yr7_mu7ieung_gez", + "type": "ClassOCLLink", + "source": "ocl_ccum3m92y_mu7ieung_fz6", + "target": "class_e9ggzl13o_mu7ieunf_qqw", + "data": { + "points": [] + } + } + ] } } diff --git a/tests/generators/react/conftest.py b/tests/generators/react/conftest.py index 67e290109..8f1b2e00e 100644 --- a/tests/generators/react/conftest.py +++ b/tests/generators/react/conftest.py @@ -14,39 +14,40 @@ def class_diagram(classes, associations=()): - """Apollon class diagram JSON. ``classes`` = {Name: [(attr, type), ...]}, an - attribute optionally with a dict of extra fields (``{"isExternalId": True}``); + """v4 class diagram JSON (``{nodes, edges}``). ``classes`` = {Name: [(attr, type), ...]}, + an attribute optionally with a dict of extra fields (``{"isExternalId": True}``); the class id is ``cls-`` and an attribute id ``attr--``. ``associations`` = [(name, (Class, role, multiplicity), (Class, role, multiplicity)), ...].""" - elements = {} + nodes = [] for index, (class_name, attributes) in enumerate(classes.items()): class_id = f"cls-{class_name}" - attribute_ids = [] - for attr_name, attr_type, *extra in attributes: - attr_id = f"attr-{class_name}-{attr_name}" - attribute_ids.append(attr_id) - elements[attr_id] = { - "id": attr_id, "name": attr_name, "type": "ClassAttribute", "owner": class_id, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 30}, "visibility": "public", - "attributeType": attr_type, "isOptional": False, "isDerived": False, "isId": False, + rows = [ + { + "id": f"attr-{class_name}-{attr_name}", "name": attr_name, + "visibility": "public", "attributeType": attr_type, + "isOptional": False, "isDerived": False, "isId": False, **(extra[0] if extra else {}), } - elements[class_id] = { - "id": class_id, "name": class_name, "type": "Class", "owner": None, - "bounds": {"x": index * 300, "y": 0, "width": 220, "height": 200}, - "attributes": attribute_ids, "methods": [], - } - relationships = { - f"rel-{name}": { - "id": f"rel-{name}", "name": name, "type": "ClassBidirectional", - **{side: {"element": f"cls-{class_name}", "role": role, "multiplicity": multiplicity} - for side, (class_name, role, multiplicity) in (("source", source), ("target", target))}, + for attr_name, attr_type, *extra in attributes + ] + nodes.append({ + "id": class_id, "type": "class", + "position": {"x": index * 300, "y": 0}, "width": 220, "height": 200, + "data": {"name": class_name, "stereotype": None, "attributes": rows, "methods": []}, + }) + edges = [ + { + "id": f"rel-{name}", "type": "ClassBidirectional", + "source": f"cls-{source[0]}", "target": f"cls-{target[0]}", + "sourceHandle": "right", "targetHandle": "left", + "data": {"name": name, "sourceRole": source[1], "sourceMultiplicity": source[2], + "targetRole": target[1], "targetMultiplicity": target[2], "points": []}, } for name, source, target in associations - } - return {"version": "3.0.0", "type": "ClassDiagram", "size": {"width": 2000, "height": 1000}, - "interactive": {"elements": {}, "relationships": {}}, "elements": elements, - "relationships": relationships, "assessments": {}} + ] + return {"version": "4.0.0", "type": "ClassDiagram", "size": {"width": 2000, "height": 1000}, + "nodes": nodes, "edges": edges, "interactive": {"elements": {}, "relationships": {}}, + "assessments": {}} def gui_json(pages): @@ -87,10 +88,10 @@ def build(classes, pages, associations=(), link_classes=None): association class of that association.""" class_json = class_diagram(classes, associations) for association, class_name in (link_classes or {}).items(): - class_json["relationships"][f"link-{class_name}"] = { - "id": f"link-{class_name}", "name": "", "type": "ClassLinkRel", - "source": {"element": f"rel-{association}"}, "target": {"element": f"cls-{class_name}"}, - } + class_json["edges"].append({ + "id": f"link-{class_name}", "type": "ClassLinkRel", + "source": f"rel-{association}", "target": f"cls-{class_name}", "data": {"points": []}, + }) project_gui = gui_json(pages) domain = process_class_diagram({"title": "Domain", "model": class_json}) gui_model = process_gui_diagram(project_gui, class_json, domain) diff --git a/tests/generators/snapshots/web_editor_generators.json b/tests/generators/snapshots/web_editor_generators.json index acad188ba..216411d8f 100644 --- a/tests/generators/snapshots/web_editor_generators.json +++ b/tests/generators/snapshots/web_editor_generators.json @@ -254,7 +254,7 @@ "file_extension": ".bpmn", "category": "business_process", "requires_class_diagram": false, - "required_diagram_type": "BPMNDiagram", + "required_diagram_type": "BPMN", "download_filename": "bpmn_diagram.bpmn", "keep_generated_filename": false, "needs_beyond_one_diagram": null diff --git a/tests/generators/test_generator_registry.py b/tests/generators/test_generator_registry.py index da85e8743..ebbf9c613 100644 --- a/tests/generators/test_generator_registry.py +++ b/tests/generators/test_generator_registry.py @@ -23,7 +23,7 @@ from besser.utilities.web_modeling_editor.backend.config import generators as backend_config from besser.utilities.web_modeling_editor.backend.constants.constants import ( AGENT_OUTPUT_FILENAME, - BPMN_DIAGRAM_TYPE, + BPMN_PROJECT_DIAGRAM_KEY, DEPLOYMENT_DIAGRAM_TYPE, ) @@ -104,7 +104,7 @@ def test_importing_the_registry_imports_no_generator(): def test_values_shared_with_the_backend_constants(): by_id = {spec.id: spec for spec in GENERATORS} assert by_id["agent"].download_filename == AGENT_OUTPUT_FILENAME - assert by_id["bpmn"].required_diagram_type == BPMN_DIAGRAM_TYPE + assert by_id["bpmn"].required_diagram_type == BPMN_PROJECT_DIAGRAM_KEY assert by_id["docker_compose"].required_diagram_type == DEPLOYMENT_DIAGRAM_TYPE diff --git a/tests/generators/test_identifier_gate.py b/tests/generators/test_identifier_gate.py index 89c89a112..75c6172d8 100644 --- a/tests/generators/test_identifier_gate.py +++ b/tests/generators/test_identifier_gate.py @@ -80,12 +80,16 @@ def _no_subprocess(*args, **kwargs): "title": "Library", "generator": "sql", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "enum-1": {"type": "Enumeration", "name": "Status", "attributes": ["lit-1"], "methods": []}, - "lit-1": {"type": "ClassAttribute", "name": CODE_SHAPED_NAME}, - }, - "relationships": {}, + "nodes": [{ + "id": "enum-1", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": { + "name": "Status", "stereotype": "Enumeration", + "attributes": [{"id": "lit-1", "name": CODE_SHAPED_NAME}], "methods": [], + }, + }], + "edges": [], }, } diff --git a/tests/generators/web_app/test_web_app_packaging.py b/tests/generators/web_app/test_web_app_packaging.py index 08e266ba7..641f04e0c 100644 --- a/tests/generators/web_app/test_web_app_packaging.py +++ b/tests/generators/web_app/test_web_app_packaging.py @@ -164,11 +164,9 @@ def _isolate_cwd(tmp_path, monkeypatch): def test_the_editor_passes_the_project_name(_isolate_cwd): - class_model = {"version": "3.0.0", "type": "ClassDiagram", "size": {"width": 800, "height": 600}, - "interactive": {"elements": {}, "relationships": {}}, "relationships": {}, "assessments": {}, - "elements": {"c1": {"id": "c1", "name": "Book", "type": "Class", "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}, - "attributes": [], "methods": []}}} + class_model = {"version": "4.0.0", "type": "ClassDiagram", "edges": [], "assessments": {}, + "nodes": [{"id": "c1", "type": "class", "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": {"name": "Book", "stereotype": None, "attributes": [], "methods": []}}]} gui_model = {"pages": [{"id": "home", "name": "Home", "frames": [{"component": { "type": "wrapper", "components": [{"tagName": "p", "content": "Welcome"}]}}]}], "styles": []} project = ProjectInput( diff --git a/tests/spec_driven_agent/test_modify_model_sync.py b/tests/spec_driven_agent/test_modify_model_sync.py index 86f17512b..6352e5263 100644 --- a/tests/spec_driven_agent/test_modify_model_sync.py +++ b/tests/spec_driven_agent/test_modify_model_sync.py @@ -113,9 +113,10 @@ def _source_export() -> dict: "id": "cd1", "title": "Library", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, } ] @@ -223,9 +224,9 @@ def test_new_class_applied_and_slotted_into_export(tmp_path): # class_buml_to_json reflects the new class. serialized = class_buml_to_json(orch.domain_model) class_element_names = { - e.get("name") - for e in serialized["elements"].values() - if e.get("type") == "Class" + (n.get("data") or {}).get("name") + for n in serialized["nodes"] + if n.get("type") == "class" } assert "User" in class_element_names assert "Book" in class_element_names @@ -237,9 +238,9 @@ def test_new_class_applied_and_slotted_into_export(tmp_path): orch._updated_project_export["diagrams"]["ClassDiagram"][0]["model"] ) exported_names = { - e.get("name") - for e in entry_model["elements"].values() - if e.get("type") == "Class" + (n.get("data") or {}).get("name") + for n in entry_model["nodes"] + if n.get("type") == "class" } assert "User" in exported_names @@ -372,17 +373,15 @@ def test_model_sync_keeps_existing_element_ids(tmp_path): get_element_by_id, ) - bounds = {"x": 0, "y": 0, "width": 160, "height": 100} class_model = { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "cls-book": {"id": "cls-book", "name": "Book", "type": "Class", "owner": None, - "bounds": bounds, "attributes": ["attr-title"], "methods": []}, - "attr-title": {"id": "attr-title", "name": "title", "type": "ClassAttribute", - "owner": "cls-book", "bounds": bounds, - "visibility": "public", "attributeType": "str"}, - }, - "relationships": {}, + "nodes": [{ + "id": "cls-book", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Book", "methods": [], "attributes": [ + {"id": "attr-title", "name": "title", "visibility": "public", "attributeType": "str"}]}, + }], + "edges": [], } export = _source_export() export["diagrams"]["ClassDiagram"][0]["model"] = class_model @@ -402,12 +401,13 @@ def test_model_sync_keeps_existing_element_ids(tmp_path): orch._derive_and_apply_model_deltas("add users") updated = orch._updated_project_export["diagrams"]["ClassDiagram"][0]["model"] - assert updated["elements"]["cls-book"]["name"] == "Book" - assert updated["elements"]["attr-title"]["owner"] == "cls-book" + book = next(n for n in updated["nodes"] if n["id"] == "cls-book") + assert book["data"]["name"] == "Book" + assert [row["id"] for row in book["data"]["attributes"]] == ["attr-title"] gui_ref = orch._updated_project_export["diagrams"]["GUINoCodeDiagram"][0]["model"][ "pages"][0]["frames"][0]["component"]["components"][0]["attributes"]["data-source"] assert get_element_by_id(updated, gui_ref)["name"] == "Book" - user_ids = [k for k, e in updated["elements"].items() if e.get("name") == "User"] + user_ids = [n["id"] for n in updated["nodes"] if n["data"].get("name") == "User"] assert len(user_ids) == 1 and user_ids[0] not in ("cls-book", "attr-title") @@ -772,8 +772,9 @@ def test_model_sync_adds_attributes_and_literals_to_existing_elements(tmp_path): assert "attributes_of_existing_classes" not in orch._model_sync["not_covered"] # The push writes buml/ from the updated model. - exported = orch._updated_project_export["diagrams"]["ClassDiagram"][0]["model"]["elements"] - assert {"rating", "Podcast", "Game"} <= {e.get("name") for e in exported.values()} + exported = orch._updated_project_export["diagrams"]["ClassDiagram"][0]["model"]["nodes"] + rows = {row.get("name") for n in exported for row in (n.get("data") or {}).get("attributes") or []} + assert {"rating", "Podcast", "Game"} <= rows def test_model_sync_of_existing_elements_reaches_the_run_summary(): diff --git a/tests/utilities/buml_code_builder/test_agent_condition_identifier.py b/tests/utilities/buml_code_builder/test_agent_condition_identifier.py index 3ab708620..859995790 100644 --- a/tests/utilities/buml_code_builder/test_agent_condition_identifier.py +++ b/tests/utilities/buml_code_builder/test_agent_condition_identifier.py @@ -32,8 +32,9 @@ def _export(condition_name, directory): def _custom_conditions(json_model): - return [r["custom"]["condition"] for r in json_model["relationships"].values() - if r.get("transitionType") == "custom"] + # v4 wire shape: transitions are edges whose canonical trigger lives in ``edge.data``. + return [e["data"]["custom"]["condition"] for e in json_model["edges"] + if (e.get("data") or {}).get("transitionType") == "custom"] @pytest.mark.parametrize("condition_name", ["is.ready", "if"]) diff --git a/tests/utilities/buml_code_builder/test_builders.py b/tests/utilities/buml_code_builder/test_builders.py index edb63ffcf..dbb6dc76f 100644 --- a/tests/utilities/buml_code_builder/test_builders.py +++ b/tests/utilities/buml_code_builder/test_builders.py @@ -1242,12 +1242,14 @@ def test_keyword_named_screen_compiles(self, tmp_path): # project_builder.py # --------------------------------------------------------------------------- from besser.BUML.metamodel.project import Project +from besser.BUML.metamodel.bpmn import BPMNModel from besser.BUML.metamodel.object import ( Object, AttributeLink, DataValue, ObjectModel, ) from besser.BUML.metamodel.uml_component import ComponentModel from besser.BUML.metamodel.uml_deployment import DeploymentModel from besser.utilities.buml_code_builder.project_builder import project_to_code +from tests.bpmn_models import _poolless_model class TestProjectBuilder: @@ -1492,6 +1494,59 @@ def test_project_with_quantum(self, tmp_path): assert "SimpleQC" in code assert "QuantumCircuit" in code + def test_project_with_bpmn(self, tmp_path): + """Project containing a BPMNModel generates a '# BPMN MODEL #' section + that round-trips through exec().""" + bpmn = _poolless_model() + + cls = Class(name="Baz") + dm = DomainModel(name="BazModel", types={cls}, associations=set()) + + meta = Metadata(description="BPMN project") + project = Project( + name="BPMNProject", + models=[dm, bpmn], + owner="tester", + metadata=meta, + ) + + file_path = str(tmp_path / "bpmn_proj.py") + project_to_code(project, file_path) + + with open(file_path, "r", encoding="utf-8") as f: + code = f.read() + + compile(code, file_path, "exec") + assert "BPMN MODEL" in code + assert "Poolless" in code + + namespace = {} + exec(code, namespace) + + recreated = namespace["project"] + assert isinstance(recreated, Project) + assert any(isinstance(m, BPMNModel) for m in recreated.models) + + def test_several_bpmn_models_keep_their_titles(self, tmp_path): + """With more than one BPMN model each section carries a numbered, + titled header, which project_to_json reads back as the diagram title.""" + from tests.bpmn_models import _gateway_model + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.project_converter import ( + project_to_json, + ) + first, second = _poolless_model(), _gateway_model() + first.name, second.name = "OrderFlow", "Approval" + project = Project(name="Flows", models=[DomainModel(name="D", types={Class(name="C")}), first, second], + owner="tester", metadata=Metadata(description="two flows")) + + file_path = str(tmp_path / "flows.py") + project_to_code(project, file_path) + with open(file_path, "r", encoding="utf-8") as f: + diagrams = project_to_json(f.read())["diagrams"]["BPMN"] + + assert [d["title"] for d in diagrams] == ["OrderFlow", "Approval"] + assert all(d["model"]["nodes"] for d in diagrams) + def test_owner_in_code(self, tmp_path): """Owner field appears in generated project code.""" project = self._build_simple_project() @@ -1582,6 +1637,53 @@ def test_project_multiple_object_models_are_exported(self, tmp_path): object_models = [m for m in recreated.models if isinstance(m, ObjectModel)] assert len(object_models) == 2 + def test_object_names_with_spaces_and_colons_roundtrip(self, tmp_path): + """Object names are user text: ``"my Book : Book"`` must not leak into + an identifier. The exported file must compile, and the link and the + ObjectModel must reference the same sanitized variables.""" + from besser.BUML.metamodel.object import Link, LinkEnd + + title = Property(name="title", type=StringType) + book = Class(name="Book", attributes={title}) + library = Class(name="Library", attributes=set()) + book_end = Property(name="books", type=book, multiplicity=Multiplicity(0, "*")) + library_end = Property(name="library", type=library, multiplicity=Multiplicity(1, 1)) + holds = BinaryAssociation(name="holds", ends={book_end, library_end}) + dm = DomainModel(name="LibraryModel", types={library, book}, associations={holds}) + + my_book = Object( + name="my Book : Book", + classifier=book, + slots=[AttributeLink(attribute=title, value=DataValue(classifier=StringType, value="1984"))], + ) + # Linked objects: the metamodel derives the re-created Link's name + # from both object names, and NamedElement forbids spaces there, so + # these use colons/dots only. + city_lib = Object(name="cityLib:Library", classifier=library) + other_book = Object(name="book.2:Book", classifier=book) + Link(name="holds_link", association=holds, connections=[ + LinkEnd(name="library", association_end=library_end, object=city_lib), + LinkEnd(name="books", association_end=book_end, object=other_book), + ]) + om = ObjectModel(name="Instances", objects={my_book, city_lib, other_book}) + + file_path = str(tmp_path / "odd_object_names.py") + project_to_code(Project( + name="OddNames", models=[dm, om], owner="tester", metadata=Metadata(description="odd names"), + ), file_path) + with open(file_path, "r", encoding="utf-8") as f: + code = f.read() + + compile(code, file_path, "exec") + assert "my_book_book_obj = " in code + assert "citylib_library_obj.books = book_2_book_obj" in code + + namespace: dict = {} + exec(code, namespace) + recreated = next(m for m in namespace["project"].models if isinstance(m, ObjectModel)) + assert {obj.name for obj in recreated.objects} == {"my Book : Book", "cityLib:Library", "book.2:Book"} + assert len(recreated.links) == 1 + def test_project_multiple_object_models_roundtrip_no_empty_diagrams(self, tmp_path): """Regression for the WME #161 follow-up (round-trip import). @@ -1632,7 +1734,7 @@ def test_project_multiple_object_models_roundtrip_no_empty_diagrams(self, tmp_pa assert {d["title"] for d in object_diagrams} == {"ObjectModelOne", "ObjectModelTwo"} # Each diagram carries real content, not an empty import-only shell. for d in object_diagrams: - assert d["model"]["elements"], f"object diagram {d['title']!r} came back empty" + assert d["model"]["nodes"], f"object diagram {d['title']!r} came back empty" # --------------------------------------------------------------------------- diff --git a/tests/utilities/sdmx_to_buml/roundtrip.py b/tests/utilities/sdmx_to_buml/roundtrip.py index f9907e5d9..23734a6c9 100644 --- a/tests/utilities/sdmx_to_buml/roundtrip.py +++ b/tests/utilities/sdmx_to_buml/roundtrip.py @@ -10,8 +10,7 @@ def signature(model: DomainModel) -> dict: """What the round trip must keep: classes (with their metadata URI), attributes, enumerations, associations. - The class descriptions are compared by ``test_class_descriptions_survive_the_editor``: the editor - converters currently append a copy of each description on every round trip. + The class descriptions are compared by ``test_class_descriptions_survive_the_editor``. """ classes = { t.name: (sorted((a.name, a.type.name, bool(a.is_id), bool(a.is_optional)) for a in t.attributes), diff --git a/tests/utilities/sdmx_to_buml/test_sdmx_to_buml.py b/tests/utilities/sdmx_to_buml/test_sdmx_to_buml.py index aec9d1287..0df7e8081 100644 --- a/tests/utilities/sdmx_to_buml/test_sdmx_to_buml.py +++ b/tests/utilities/sdmx_to_buml/test_sdmx_to_buml.py @@ -179,9 +179,6 @@ def test_round_trip_of_the_synthetic_model(structure_xml): assert round_trip_differences(model) == [] -@pytest.mark.xfail(strict=True, reason="class_buml_to_json writes a class description as its description and as a " - "linked comment, and process_class_diagram appends the comment to it: a " - "converter bug outside this importer, to fix separately") def test_class_descriptions_survive_the_editor(structure_xml): model, _ = structure_to_buml(parse_structure(structure_xml, "DF_TEST")) before = {t.name: t.metadata.description for t in model.types if isinstance(t, Class)} diff --git a/tests/utilities/test_generation_provenance.py b/tests/utilities/test_generation_provenance.py index afffda1af..b0c091891 100644 --- a/tests/utilities/test_generation_provenance.py +++ b/tests/utilities/test_generation_provenance.py @@ -42,21 +42,51 @@ VERSION = _SETUP_CFG["metadata"]["version"] HEADER = f"# Generated by BESSER {VERSION}\n" +def _class_node(node_id, name, attr_id, attr_name, x): + return { + "id": node_id, + "type": "class", + "position": {"x": x, "y": 0}, + "width": 160, + "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": name, + "stereotype": None, + "attributes": [ + {"id": attr_id, "name": attr_name, "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, + } + + CLASS_MODEL = { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": {"type": "Class", "name": "Author", "attributes": ["attr-1"], "methods": []}, - "attr-1": {"type": "Attribute", "name": "+ name: str"}, - "class-2": {"type": "Class", "name": "Book", "attributes": ["attr-2"], "methods": []}, - "attr-2": {"type": "Attribute", "name": "+ title: str"}, - }, - "relationships": { - "rel-1": { + "nodes": [ + _class_node("class-1", "Author", "attr-1", "name", 0), + _class_node("class-2", "Book", "attr-2", "title", 400), + ], + "edges": [ + { + "id": "rel-1", + "source": "class-1", + "target": "class-2", "type": "ClassBidirectional", - "source": {"element": "class-1", "multiplicity": "1..*", "role": "authors"}, - "target": {"element": "class-2", "multiplicity": "0..*", "role": "books"}, + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "points": [], + "sourceMultiplicity": "1..*", + "sourceRole": "authors", + "targetMultiplicity": "0..*", + "targetRole": "books", + "sourceNavigable": True, + "targetNavigable": True, + }, }, - }, + ], } @@ -213,7 +243,7 @@ def test_project_file_has_one_version_header_and_round_trips(self, tmp_path): assert code.startswith(HEADER) assert code.count("Generated by BESSER") == 1 diagrams = project_to_json(code)["diagrams"]["ClassDiagram"] - names = {e["name"] for e in diagrams[0]["model"]["elements"].values() if e["type"] == "Class"} + names = {n["data"]["name"] for n in diagrams[0]["model"]["nodes"] if n["type"] == "class"} assert names == {"Author", "Book"} diff --git a/tests/utilities/test_kg_llm_to_buml.py b/tests/utilities/test_kg_llm_to_buml.py index a9cc978f4..9b1bf1acf 100644 --- a/tests/utilities/test_kg_llm_to_buml.py +++ b/tests/utilities/test_kg_llm_to_buml.py @@ -168,28 +168,27 @@ def test_parse_json_safely_invalid_json(): # --- Tests for convert_spec_json_to_buml --- def test_convert_spec_json_to_buml_creates_valid_structure(): - """Test that convert_spec_json_to_buml creates proper Apollon/BUML JSON""" + """Test that convert_spec_json_to_buml creates proper BESSER WME / BUML JSON""" system_spec = _mock_system_spec() result = convert_spec_json_to_buml(system_spec) # Verify top-level structure assert "title" in result assert "model" in result - assert "elements" in result["model"] - assert "relationships" in result["model"] + assert "nodes" in result["model"] + assert "edges" in result["model"] # Verify classes are created - elements = result["model"]["elements"] - class_elements = {k: v for k, v in elements.items() if v.get("type") == "Class"} - assert len(class_elements) >= 2 # Person and Car + class_nodes = [n for n in result["model"]["nodes"] if n.get("type") == "class"] + assert len(class_nodes) >= 2 # Person and Car # Verify attributes are created - attr_elements = {k: v for k, v in elements.items() if v.get("type") == "ClassAttribute"} - assert len(attr_elements) >= 4 # name, age for Person; model, year for Car + attributes = [a for n in class_nodes for a in n["data"]["attributes"]] + assert len(attributes) >= 4 # name, age for Person; model, year for Car # Verify methods are created - method_elements = {k: v for k, v in elements.items() if v.get("type") == "ClassMethod"} - assert len(method_elements) >= 1 # getName for Person + methods = [m for n in class_nodes for m in n["data"]["methods"]] + assert len(methods) >= 1 # getName for Person def test_convert_spec_json_to_buml_handles_void_return_type(): @@ -214,13 +213,12 @@ def test_convert_spec_json_to_buml_handles_void_return_type(): } result = convert_spec_json_to_buml(system_spec) - elements = result["model"]["elements"] - # Find the method element - method_elements = {k: v for k, v in elements.items() if v.get("type") == "ClassMethod"} - assert len(method_elements) == 1 + # Find the method row + methods = [m for n in result["model"]["nodes"] for m in n["data"]["methods"]] + assert len(methods) == 1 - method = list(method_elements.values())[0] + method = methods[0] # Void return type should result in empty string at the end assert method["name"].endswith(": ") @@ -230,16 +228,16 @@ def test_convert_spec_json_to_buml_creates_relationships(): system_spec = _mock_system_spec() result = convert_spec_json_to_buml(system_spec) - relationships = result["model"]["relationships"] - assert len(relationships) >= 1 + edges = result["model"]["edges"] + assert len(edges) >= 1 # Check first relationship structure - rel = list(relationships.values())[0] + rel = edges[0] assert "id" in rel assert "type" in rel assert "source" in rel assert "target" in rel - assert rel["name"] == "owns" + assert rel["data"]["name"] == "owns" def test_convert_spec_json_to_buml_handles_custom_title(): @@ -249,6 +247,29 @@ def test_convert_spec_json_to_buml_handles_custom_title(): assert result["title"] == "My_Custom_Diagram" + +def test_convert_spec_json_to_buml_output_converts_to_full_domain_model(): + """The converted JSON must be accepted by the class diagram processor + (regression: v3-shaped output produced an empty domain model).""" + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.class_diagram_processor import ( + process_class_diagram, + ) + domain_model = process_class_diagram(convert_spec_json_to_buml(_mock_system_spec())) + + assert sorted(c.name for c in domain_model.get_classes()) == ["Car", "Person"] + person = domain_model.get_class_by_name("Person") + assert sorted((a.name, a.type.name, a.visibility) for a in person.attributes) == [ + ("age", "int", "private"), ("name", "str", "private"), + ] + assert [(m.name, m.type.name) for m in person.methods] == [("getName", "str")] + + assert len(domain_model.associations) == 1 + owns = next(iter(domain_model.associations)) + assert owns.name == "owns" + ends = {e.type.name: e for e in owns.ends} + assert ends["Person"].multiplicity.max == 1 + assert ends["Car"].multiplicity.max == 9999 + # --- Tests for kg_to_plantuml --- @patch('builtins.open', new_callable=mock_open, read_data='mock kg data') @patch('requests.post') diff --git a/tests/utilities/test_secret_redaction_callers.py b/tests/utilities/test_secret_redaction_callers.py index ea3334d1d..f566e98fb 100644 --- a/tests/utilities/test_secret_redaction_callers.py +++ b/tests/utilities/test_secret_redaction_callers.py @@ -107,7 +107,7 @@ def test_the_agent_transform_endpoint_logs_its_config_redacted(caplog, monkeypat caplog.set_level(logging.DEBUG) with TestClient(app, raise_server_exceptions=False) as client: client.post("/besser_api/transform-agent-model-json", json={ - "title": "a", "model": {"type": "AgentDiagram", "elements": {}, "relationships": {}}, + "title": "a", "model": {"version": "4.0.0", "type": "AgentDiagram", "nodes": [], "edges": []}, "config": {"openai_api_key": KEY, "language": "en"}}) logged = [r.getMessage() for r in caplog.records if r.getMessage().startswith("[Agent transform] config")] diff --git a/tests/utilities/web_modeling_editor/backend/fixtures/template_bpmn_pizza_store.json b/tests/utilities/web_modeling_editor/backend/fixtures/template_bpmn_pizza_store.json index d7a58754f..6bd001d2f 100644 --- a/tests/utilities/web_modeling_editor/backend/fixtures/template_bpmn_pizza_store.json +++ b/tests/utilities/web_modeling_editor/backend/fixtures/template_bpmn_pizza_store.json @@ -1,988 +1,1022 @@ { - "version": "3.0.0", + "version": "4.0.0", + "id": "converted-diagram-1782994098534", + "title": "Pizza Store", "type": "BPMNDiagram", - "size": { - "width": 1300, - "height": 710 - }, - "interactive": { - "elements": {}, - "relationships": {} - }, - "elements": { - "c-pool": { + "nodes": [ + { "id": "c-pool", - "name": "Pizza Customer", - "type": "BPMNPool", - "owner": null, - "bounds": { + "type": "bpmnPool", + "position": { "x": 0, - "y": 0, + "y": 0 + }, + "width": 1300, + "height": 260, + "measured": { "width": 1300, "height": 260 + }, + "data": { + "name": "Pizza Customer" } }, - "c-start": { + { "id": "c-start", - "name": "Hungry for pizza", - "type": "BPMNStartEvent", - "owner": null, - "bounds": { + "type": "bpmnStartEvent", + "position": { "x": 60, - "y": 110, + "y": 110 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "eventType": "default" + "data": { + "name": "Hungry for pizza", + "eventType": "default" + }, + "parentId": "c-pool" }, - "c-select": { + { "id": "c-select", - "name": "Select a pizza", - "type": "BPMNTask", - "owner": null, - "bounds": { + "type": "bpmnTask", + "position": { "x": 150, - "y": 100, + "y": 100 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "user", - "marker": "none" + "data": { + "name": "Select a pizza", + "taskType": "user", + "marker": "none" + }, + "parentId": "c-pool" }, - "c-order": { + { "id": "c-order", - "name": "Order a pizza", - "type": "BPMNTask", - "owner": null, - "bounds": { + "type": "bpmnTask", + "position": { "x": 320, - "y": 100, + "y": 100 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "send", - "marker": "none" + "data": { + "name": "Order a pizza", + "taskType": "send", + "marker": "none" + }, + "parentId": "c-pool" }, - "c-gw": { + { "id": "c-gw", - "name": "", - "type": "BPMNGateway", - "owner": null, - "bounds": { + "type": "bpmnGateway", + "position": { "x": 480, - "y": 110, + "y": 110 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "gatewayType": "event-based" + "data": { + "name": "", + "gatewayType": "event-based" + }, + "parentId": "c-pool" }, - "c-timer": { + { "id": "c-timer", - "name": "60 min", - "type": "BPMNIntermediateEvent", - "owner": null, - "bounds": { + "type": "bpmnIntermediateEvent", + "position": { "x": 480, - "y": 190, + "y": 190 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "eventType": "timer-catch" + "data": { + "name": "60 min", + "eventType": "timer-catch" + }, + "parentId": "c-pool" }, - "c-ask": { + { "id": "c-ask", - "name": "Ask for pizza", - "type": "BPMNTask", - "owner": null, - "bounds": { + "type": "bpmnTask", + "position": { "x": 525, - "y": 180, + "y": 180 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "user", - "marker": "none" + "data": { + "name": "Ask for pizza", + "taskType": "user", + "marker": "none" + }, + "parentId": "c-pool" }, - "c-msg": { + { "id": "c-msg", - "name": "Pizza received", - "type": "BPMNIntermediateEvent", - "owner": null, - "bounds": { + "type": "bpmnIntermediateEvent", + "position": { "x": 795, - "y": 110, + "y": 110 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "eventType": "message-catch" + "data": { + "name": "Pizza received", + "eventType": "message-catch" + }, + "parentId": "c-pool" }, - "c-pay": { + { "id": "c-pay", - "name": "Pay for pizza", - "type": "BPMNTask", - "owner": null, - "bounds": { + "type": "bpmnTask", + "position": { "x": 900, - "y": 100, + "y": 100 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "user", - "marker": "none" + "data": { + "name": "Pay for pizza", + "taskType": "user", + "marker": "none" + }, + "parentId": "c-pool" }, - "c-eat": { + { "id": "c-eat", - "name": "Eat the pizza", - "type": "BPMNTask", - "owner": null, - "bounds": { + "type": "bpmnTask", + "position": { "x": 1070, - "y": 100, + "y": 100 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "user", - "marker": "none" + "data": { + "name": "Eat the pizza", + "taskType": "user", + "marker": "none" + }, + "parentId": "c-pool" }, - "c-end": { + { "id": "c-end", - "name": "Hunger satisfied", - "type": "BPMNEndEvent", - "owner": null, - "bounds": { + "type": "bpmnEndEvent", + "position": { "x": 1240, - "y": 110, + "y": 110 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "eventType": "default" + "data": { + "name": "Hunger satisfied", + "eventType": "default" + }, + "parentId": "c-pool" }, - "v-pool": { + { "id": "v-pool", - "name": "Pizza Vendor", - "type": "BPMNPool", - "owner": null, - "bounds": { + "type": "bpmnPool", + "position": { "x": 0, - "y": 300, + "y": 300 + }, + "width": 1300, + "height": 390, + "measured": { "width": 1300, "height": 390 + }, + "data": { + "name": "Pizza Vendor" } }, - "v-lane-clerk": { + { "id": "v-lane-clerk", - "name": "Clerk", - "type": "BPMNSwimlane", - "owner": "v-pool", - "bounds": { + "type": "bpmnSwimlane", + "position": { "x": 40, - "y": 300, + "y": 0 + }, + "width": 1260, + "height": 130, + "measured": { "width": 1260, "height": 130 - } + }, + "data": { + "name": "Clerk" + }, + "parentId": "v-pool" }, - "v-lane-chef": { + { "id": "v-lane-chef", - "name": "Pizza Chef", - "type": "BPMNSwimlane", - "owner": "v-pool", - "bounds": { + "type": "bpmnSwimlane", + "position": { "x": 40, - "y": 430, + "y": 130 + }, + "width": 1260, + "height": 130, + "measured": { "width": 1260, "height": 130 - } + }, + "data": { + "name": "Pizza Chef" + }, + "parentId": "v-pool" }, - "v-lane-delivery": { + { "id": "v-lane-delivery", - "name": "Delivery Boy", - "type": "BPMNSwimlane", - "owner": "v-pool", - "bounds": { + "type": "bpmnSwimlane", + "position": { "x": 40, - "y": 560, + "y": 260 + }, + "width": 1260, + "height": 130, + "measured": { "width": 1260, "height": 130 - } + }, + "data": { + "name": "Delivery Boy" + }, + "parentId": "v-pool" }, - "v-start": { + { "id": "v-start", - "name": "Order received", - "type": "BPMNStartEvent", - "owner": null, - "bounds": { - "x": 355, - "y": 350, + "type": "bpmnStartEvent", + "position": { + "x": 315, + "y": 50 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "eventType": "message" + "data": { + "name": "Order received", + "eventType": "message" + }, + "parentId": "v-lane-clerk" }, - "v-pgw": { + { "id": "v-pgw", - "name": "", - "type": "BPMNGateway", - "owner": null, - "bounds": { - "x": 450, - "y": 350, + "type": "bpmnGateway", + "position": { + "x": 410, + "y": 50 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "gatewayType": "parallel" + "data": { + "name": "", + "gatewayType": "parallel" + }, + "parentId": "v-lane-clerk" }, - "v-askmsg": { + { "id": "v-askmsg", - "name": "Where is my pizza?", - "type": "BPMNIntermediateEvent", - "owner": null, - "bounds": { - "x": 560, - "y": 350, + "type": "bpmnIntermediateEvent", + "position": { + "x": 520, + "y": 50 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "eventType": "message-catch" + "data": { + "name": "Where is my pizza?", + "eventType": "message-catch" + }, + "parentId": "v-lane-clerk" }, - "v-calm": { + { "id": "v-calm", - "name": "Calm customer", - "type": "BPMNTask", - "owner": null, - "bounds": { - "x": 650, - "y": 340, + "type": "bpmnTask", + "position": { + "x": 610, + "y": 40 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "user", - "marker": "none" + "data": { + "name": "Calm customer", + "taskType": "user", + "marker": "none" + }, + "parentId": "v-lane-clerk" }, - "v-bake": { + { "id": "v-bake", - "name": "Bake the pizza", - "type": "BPMNTask", - "owner": null, - "bounds": { - "x": 520, - "y": 465, + "type": "bpmnTask", + "position": { + "x": 480, + "y": 35 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "user", - "marker": "none" + "data": { + "name": "Bake the pizza", + "taskType": "user", + "marker": "none" + }, + "parentId": "v-lane-chef" }, - "v-deliver": { + { "id": "v-deliver", - "name": "Deliver the pizza", - "type": "BPMNTask", - "owner": null, - "bounds": { - "x": 760, - "y": 595, + "type": "bpmnTask", + "position": { + "x": 720, + "y": 35 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "user", - "marker": "none" + "data": { + "name": "Deliver the pizza", + "taskType": "user", + "marker": "none" + }, + "parentId": "v-lane-delivery" }, - "v-receive": { + { "id": "v-receive", - "name": "Receive payment", - "type": "BPMNTask", - "owner": null, - "bounds": { - "x": 900, - "y": 595, + "type": "bpmnTask", + "position": { + "x": 860, + "y": 35 + }, + "width": 110, + "height": 60, + "measured": { "width": 110, "height": 60 }, - "taskType": "user", - "marker": "none" + "data": { + "name": "Receive payment", + "taskType": "user", + "marker": "none" + }, + "parentId": "v-lane-delivery" }, - "v-end": { + { "id": "v-end", - "name": "Order complete", - "type": "BPMNEndEvent", - "owner": null, - "bounds": { - "x": 1060, - "y": 605, + "type": "bpmnEndEvent", + "position": { + "x": 1020, + "y": 45 + }, + "width": 40, + "height": 40, + "measured": { "width": 40, "height": 40 }, - "eventType": "default" + "data": { + "name": "Order complete", + "eventType": "default" + }, + "parentId": "v-lane-delivery" } - }, - "relationships": { - "f-c1": { + ], + "edges": [ + { "id": "f-c1", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 100, - "y": 130, - "width": 50, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 50, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "c-start" - }, - "target": { - "direction": "Left", - "element": "c-select" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-c2": { + "source": "c-start", + "target": "c-select", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 100, + "y": 130 + }, + { + "x": 150, + "y": 130 + } + ] + } + }, + { "id": "f-c2", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 260, - "y": 130, - "width": 60, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 60, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "c-select" - }, - "target": { - "direction": "Left", - "element": "c-order" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-c3": { + "source": "c-select", + "target": "c-order", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 260, + "y": 130 + }, + { + "x": 320, + "y": 130 + } + ] + } + }, + { "id": "f-c3", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 430, - "y": 130, - "width": 50, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 50, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "c-order" - }, - "target": { - "direction": "Left", - "element": "c-gw" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-c4": { + "source": "c-order", + "target": "c-gw", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 430, + "y": 130 + }, + { + "x": 480, + "y": 130 + } + ] + } + }, + { "id": "f-c4", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 500, - "y": 150, - "width": 1, - "height": 40 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 0, - "y": 40 - } - ], - "source": { - "direction": "Down", - "element": "c-gw" - }, - "target": { - "direction": "Up", - "element": "c-timer" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-c5": { + "source": "c-gw", + "target": "c-timer", + "type": "BPMNSequenceFlow", + "sourceHandle": "bottom", + "targetHandle": "top", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 500, + "y": 150 + }, + { + "x": 500, + "y": 190 + } + ] + } + }, + { "id": "f-c5", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 520, - "y": 130, - "width": 275, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 275, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "c-gw" - }, - "target": { - "direction": "Left", - "element": "c-msg" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-c6": { + "source": "c-gw", + "target": "c-msg", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 520, + "y": 130 + }, + { + "x": 795, + "y": 130 + } + ] + } + }, + { "id": "f-c6", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 520, - "y": 210, - "width": 5, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 5, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "c-timer" - }, - "target": { - "direction": "Left", - "element": "c-ask" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-c7": { + "source": "c-timer", + "target": "c-ask", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 520, + "y": 210 + }, + { + "x": 525, + "y": 210 + } + ] + } + }, + { "id": "f-c7", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 835, - "y": 130, - "width": 65, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 65, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "c-msg" - }, - "target": { - "direction": "Left", - "element": "c-pay" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-c8": { + "source": "c-msg", + "target": "c-pay", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 835, + "y": 130 + }, + { + "x": 900, + "y": 130 + } + ] + } + }, + { "id": "f-c8", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 1010, - "y": 130, - "width": 60, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 60, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "c-pay" - }, - "target": { - "direction": "Left", - "element": "c-eat" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-c9": { + "source": "c-pay", + "target": "c-eat", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 1010, + "y": 130 + }, + { + "x": 1070, + "y": 130 + } + ] + } + }, + { "id": "f-c9", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 1180, - "y": 130, - "width": 60, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 60, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "c-eat" - }, - "target": { - "direction": "Left", - "element": "c-end" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-v1": { + "source": "c-eat", + "target": "c-end", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 1180, + "y": 130 + }, + { + "x": 1240, + "y": 130 + } + ] + } + }, + { "id": "f-v1", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 395, - "y": 370, - "width": 55, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 55, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "v-start" - }, - "target": { - "direction": "Left", - "element": "v-pgw" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-v2": { + "source": "v-start", + "target": "v-pgw", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 395, + "y": 370 + }, + { + "x": 450, + "y": 370 + } + ] + } + }, + { "id": "f-v2", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 470, - "y": 390, - "width": 50, - "height": 105 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 0, - "y": 105 - }, - { - "x": 50, - "y": 105 - } - ], - "source": { - "direction": "Down", - "element": "v-pgw" - }, - "target": { - "direction": "Left", - "element": "v-bake" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-v3": { + "source": "v-pgw", + "target": "v-bake", + "type": "BPMNSequenceFlow", + "sourceHandle": "bottom", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 470, + "y": 390 + }, + { + "x": 470, + "y": 495 + }, + { + "x": 520, + "y": 495 + } + ] + } + }, + { "id": "f-v3", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 490, - "y": 370, - "width": 70, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 70, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "v-pgw" - }, - "target": { - "direction": "Left", - "element": "v-askmsg" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-v4": { + "source": "v-pgw", + "target": "v-askmsg", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 490, + "y": 370 + }, + { + "x": 560, + "y": 370 + } + ] + } + }, + { "id": "f-v4", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 600, - "y": 370, - "width": 50, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 50, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "v-askmsg" - }, - "target": { - "direction": "Left", - "element": "v-calm" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-v5": { + "source": "v-askmsg", + "target": "v-calm", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 600, + "y": 370 + }, + { + "x": 650, + "y": 370 + } + ] + } + }, + { "id": "f-v5", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 575, - "y": 525, - "width": 185, - "height": 100 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 0, - "y": 100 - }, - { - "x": 185, - "y": 100 - } - ], - "source": { - "direction": "Down", - "element": "v-bake" - }, - "target": { - "direction": "Left", - "element": "v-deliver" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-v6": { + "source": "v-bake", + "target": "v-deliver", + "type": "BPMNSequenceFlow", + "sourceHandle": "bottom", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 575, + "y": 525 + }, + { + "x": 575, + "y": 625 + }, + { + "x": 760, + "y": 625 + } + ] + } + }, + { "id": "f-v6", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 870, - "y": 625, - "width": 30, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 30, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "v-deliver" - }, - "target": { - "direction": "Left", - "element": "v-receive" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "f-v7": { + "source": "v-deliver", + "target": "v-receive", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 870, + "y": 625 + }, + { + "x": 900, + "y": 625 + } + ] + } + }, + { "id": "f-v7", - "name": "", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 1010, - "y": 625, - "width": 50, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 50, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "v-receive" - }, - "target": { - "direction": "Left", - "element": "v-end" - }, - "isManuallyLayouted": false, - "flowType": "sequence", - "isDefault": false - }, - "mf-1": { + "source": "v-receive", + "target": "v-end", + "type": "BPMNSequenceFlow", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "sequence", + "points": [ + { + "x": 1010, + "y": 625 + }, + { + "x": 1060, + "y": 625 + } + ] + } + }, + { "id": "mf-1", - "name": "Pizza order", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 375, - "y": 160, - "width": 1, - "height": 190 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 0, - "y": 190 - } - ], - "source": { - "direction": "Down", - "element": "c-order" - }, - "target": { - "direction": "Up", - "element": "v-start" - }, - "isManuallyLayouted": false, - "flowType": "message", - "isDefault": false - }, - "mf-2": { + "source": "c-order", + "target": "v-start", + "type": "BPMNMessageFlow", + "sourceHandle": "bottom", + "targetHandle": "top", + "data": { + "label": "Pizza order", + "name": "Pizza order", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "message", + "points": [ + { + "x": 375, + "y": 160 + }, + { + "x": 375, + "y": 350 + } + ] + } + }, + { "id": "mf-2", - "name": "Where is my pizza?", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 580, - "y": 240, - "width": 1, - "height": 110 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 0, - "y": 110 - } - ], - "source": { - "direction": "Down", - "element": "c-ask" - }, - "target": { - "direction": "Up", - "element": "v-askmsg" - }, - "isManuallyLayouted": false, - "flowType": "message", - "isDefault": false - }, - "mf-3": { + "source": "c-ask", + "target": "v-askmsg", + "type": "BPMNMessageFlow", + "sourceHandle": "bottom", + "targetHandle": "top", + "data": { + "label": "Where is my pizza?", + "name": "Where is my pizza?", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "message", + "points": [ + { + "x": 580, + "y": 240 + }, + { + "x": 580, + "y": 350 + } + ] + } + }, + { "id": "mf-3", - "name": "Pizza delivered", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 815, - "y": 150, - "width": 1, - "height": 445 - }, - "path": [ - { - "x": 0, - "y": 445 - }, - { - "x": 0, - "y": 0 - } - ], - "source": { - "direction": "Up", - "element": "v-deliver" - }, - "target": { - "direction": "Down", - "element": "c-msg" - }, - "isManuallyLayouted": false, - "flowType": "message", - "isDefault": false - }, - "mf-4": { + "source": "v-deliver", + "target": "c-msg", + "type": "BPMNMessageFlow", + "sourceHandle": "top", + "targetHandle": "bottom", + "data": { + "label": "Pizza delivered", + "name": "Pizza delivered", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "message", + "points": [ + { + "x": 815, + "y": 595 + }, + { + "x": 815, + "y": 150 + } + ] + } + }, + { "id": "mf-4", - "name": "Payment", - "type": "BPMNFlow", - "owner": null, - "bounds": { - "x": 955, - "y": 160, - "width": 1, - "height": 435 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 0, - "y": 435 - } - ], - "source": { - "direction": "Down", - "element": "c-pay" - }, - "target": { - "direction": "Up", - "element": "v-receive" - }, - "isManuallyLayouted": false, - "flowType": "message", - "isDefault": false + "source": "c-pay", + "target": "v-receive", + "type": "BPMNMessageFlow", + "sourceHandle": "bottom", + "targetHandle": "top", + "data": { + "label": "Payment", + "name": "Payment", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "flowType": "message", + "points": [ + { + "x": 955, + "y": 160 + }, + { + "x": 955, + "y": 595 + } + ] + } } - }, + ], "assessments": {} } diff --git a/tests/utilities/web_modeling_editor/backend/fixtures/template_nn_tutorial_example.json b/tests/utilities/web_modeling_editor/backend/fixtures/template_nn_tutorial_example.json index d2096b4d8..bf48eff5a 100644 --- a/tests/utilities/web_modeling_editor/backend/fixtures/template_nn_tutorial_example.json +++ b/tests/utilities/web_modeling_editor/backend/fixtures/template_nn_tutorial_example.json @@ -1,1624 +1,568 @@ { - "version": "3.0.0", + "version": "4.0.0", + "id": "converted-diagram-1778241725870", + "title": "", "type": "NNDiagram", - "size": { - "width": 1460, - "height": 880 - }, - "interactive": { - "elements": {}, - "relationships": {} - }, - "elements": { - "6feb868b-45bf-4c44-88ab-6af624191fa9": { + "nodes": [ + { "id": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "name": "Neural_Network", "type": "NNContainer", - "owner": null, - "bounds": { + "position": { "x": -710, - "y": -420, + "y": -420 + }, + "width": 1150, + "height": 250, + "measured": { "width": 1150, "height": 250 + }, + "data": { + "name": "Neural_Network" } }, - "dc98557d-a1e1-403d-afcb-01b318a221dd": { + { "id": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "name": "Conv2DLayer", "type": "Conv2DLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -680, - "y": -320, + "position": { + "x": 30, + "y": 100 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "bfae619a-284a-4f14-9e4e-a44b8f722b4f", - "b2718503-5aa2-474a-8570-b79ed1e91292", - "5643fecb-2424-45dd-a3a6-62796f49a1eb", - "02c27f2c-d012-4e73-a7cb-99f0277c436e", - "c1d9d722-8276-4ea8-93c2-719542051758" - ], - "methods": [] - }, - "bfae619a-284a-4f14-9e4e-a44b8f722b4f": { - "id": "bfae619a-284a-4f14-9e4e-a44b8f722b4f", - "name": "name = l1", - "type": "NameAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l1", - "isMandatory": true - }, - "b2718503-5aa2-474a-8570-b79ed1e91292": { - "id": "b2718503-5aa2-474a-8570-b79ed1e91292", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "5643fecb-2424-45dd-a3a6-62796f49a1eb": { - "id": "5643fecb-2424-45dd-a3a6-62796f49a1eb", - "name": "out_channels = 32", - "type": "OutChannelsAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "32", - "isMandatory": true - }, - "02c27f2c-d012-4e73-a7cb-99f0277c436e": { - "id": "02c27f2c-d012-4e73-a7cb-99f0277c436e", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "c1d9d722-8276-4ea8-93c2-719542051758": { - "id": "c1d9d722-8276-4ea8-93c2-719542051758", - "name": "in_channels = 3", - "type": "InChannelsAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 170, - "height": 20 + "data": { + "name": "l1", + "attributes": { + "name": "l1", + "kernel_dim": "[3, 3]", + "out_channels": "32", + "actv_func": "relu", + "in_channels": "3" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "3", - "isMandatory": false + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" }, - "a0594c44-830e-4693-a34a-fd97f81f6b85": { + { "id": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "name": "PoolingLayer", "type": "PoolingLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -540, - "y": -320, + "position": { + "x": 170, + "y": 100 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "4e47255c-80bd-4743-b205-0320b2fcaf12", - "b89dc1bc-4d9e-4fc8-835b-8aa7bdc43e62", - "6062815a-e7df-457a-be9e-f09e53d0ea55", - "4fffff4c-6527-4a5e-9b74-8c6d4d60e3a6" - ], - "methods": [] - }, - "4e47255c-80bd-4743-b205-0320b2fcaf12": { - "id": "4e47255c-80bd-4743-b205-0320b2fcaf12", - "name": "name = l2", - "type": "NameAttributePooling", - "owner": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "bounds": { - "x": -540, - "y": -320, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l2", - "isMandatory": true - }, - "b89dc1bc-4d9e-4fc8-835b-8aa7bdc43e62": { - "id": "b89dc1bc-4d9e-4fc8-835b-8aa7bdc43e62", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "bounds": { - "x": -540, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "6062815a-e7df-457a-be9e-f09e53d0ea55": { - "id": "6062815a-e7df-457a-be9e-f09e53d0ea55", - "name": "dimension = 2D", - "type": "DimensionAttributePooling", - "owner": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "bounds": { - "x": -540, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "dimension", - "value": "2D", - "isMandatory": true - }, - "4fffff4c-6527-4a5e-9b74-8c6d4d60e3a6": { - "id": "4fffff4c-6527-4a5e-9b74-8c6d4d60e3a6", - "name": "kernel_dim = [2, 2]", - "type": "KernelDimAttributePooling", - "owner": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "bounds": { - "x": -540, - "y": -320, - "width": 200, - "height": 20 + "data": { + "name": "l2", + "attributes": { + "name": "l2", + "pooling_type": "max", + "pooling.dimension": "2D", + "kernel_dim": "[2, 2]" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[2, 2]", - "isMandatory": false + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" }, - "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39": { + { "id": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "name": "Conv2DLayer", "type": "Conv2DLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -400, - "y": -320, + "position": { + "x": 310, + "y": 100 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "a8022ee0-fe59-48aa-a4c3-ca0c9d95e2f4", - "e032d54e-4e31-40fe-8905-88e98a3d6a75", - "20d2d231-1722-4347-8dfe-20eed1dc1139", - "9c88de03-7d12-4376-a565-6c72c356fda1", - "d4b2f43d-1161-483c-9736-61469a8a0df0" - ], - "methods": [] - }, - "a8022ee0-fe59-48aa-a4c3-ca0c9d95e2f4": { - "id": "a8022ee0-fe59-48aa-a4c3-ca0c9d95e2f4", - "name": "name = l3", - "type": "NameAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l3", - "isMandatory": true - }, - "e032d54e-4e31-40fe-8905-88e98a3d6a75": { - "id": "e032d54e-4e31-40fe-8905-88e98a3d6a75", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "20d2d231-1722-4347-8dfe-20eed1dc1139": { - "id": "20d2d231-1722-4347-8dfe-20eed1dc1139", - "name": "out_channels = 64", - "type": "OutChannelsAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "64", - "isMandatory": true - }, - "9c88de03-7d12-4376-a565-6c72c356fda1": { - "id": "9c88de03-7d12-4376-a565-6c72c356fda1", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "d4b2f43d-1161-483c-9736-61469a8a0df0": { - "id": "d4b2f43d-1161-483c-9736-61469a8a0df0", - "name": "in_channels = 32", - "type": "InChannelsAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 180, - "height": 20 + "data": { + "name": "l3", + "attributes": { + "name": "l3", + "kernel_dim": "[3, 3]", + "out_channels": "64", + "actv_func": "relu", + "in_channels": "32" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "32", - "isMandatory": false + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" }, - "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5": { + { "id": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "name": "PoolingLayer", "type": "PoolingLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -260, - "y": -320, + "position": { + "x": 450, + "y": 100 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "e32bea52-bd09-4eba-b9cb-1b143a008443", - "4fd73771-b971-44c5-a893-c827ba809ec6", - "ad125315-4a4f-4a7c-8f7f-469204499219", - "83990485-6499-4984-b8fe-4808e58e7bd8" - ], - "methods": [] - }, - "e32bea52-bd09-4eba-b9cb-1b143a008443": { - "id": "e32bea52-bd09-4eba-b9cb-1b143a008443", - "name": "name = l4", - "type": "NameAttributePooling", - "owner": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "bounds": { - "x": -260, - "y": -320, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l4", - "isMandatory": true - }, - "4fd73771-b971-44c5-a893-c827ba809ec6": { - "id": "4fd73771-b971-44c5-a893-c827ba809ec6", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "bounds": { - "x": -260, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "ad125315-4a4f-4a7c-8f7f-469204499219": { - "id": "ad125315-4a4f-4a7c-8f7f-469204499219", - "name": "dimension = 2D", - "type": "DimensionAttributePooling", - "owner": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "bounds": { - "x": -260, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "dimension", - "value": "2D", - "isMandatory": true - }, - "83990485-6499-4984-b8fe-4808e58e7bd8": { - "id": "83990485-6499-4984-b8fe-4808e58e7bd8", - "name": "kernel_dim = [2, 2]", - "type": "KernelDimAttributePooling", - "owner": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "bounds": { - "x": -260, - "y": -320, - "width": 200, - "height": 20 + "data": { + "name": "l4", + "attributes": { + "name": "l4", + "pooling_type": "max", + "pooling.dimension": "2D", + "kernel_dim": "[2, 2]" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[2, 2]", - "isMandatory": false + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" }, - "b4f15221-2f2b-4876-8b79-ab7655ea7fa3": { + { "id": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "name": "Conv2DLayer", "type": "Conv2DLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -120, - "y": -320, + "position": { + "x": 590, + "y": 100 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "e1e26deb-820f-4d06-8fdb-e0104dae41ec", - "49c136db-a712-4c5e-ae0c-0c7a31d09cb0", - "8632faf5-1855-46a1-aa55-915432734fe4", - "384057f0-1660-4182-b949-ec86530932c7", - "337d5cab-647f-4a0f-865e-789e925a7e0c" - ], - "methods": [] - }, - "e1e26deb-820f-4d06-8fdb-e0104dae41ec": { - "id": "e1e26deb-820f-4d06-8fdb-e0104dae41ec", - "name": "name = l5", - "type": "NameAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l5", - "isMandatory": true - }, - "49c136db-a712-4c5e-ae0c-0c7a31d09cb0": { - "id": "49c136db-a712-4c5e-ae0c-0c7a31d09cb0", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "8632faf5-1855-46a1-aa55-915432734fe4": { - "id": "8632faf5-1855-46a1-aa55-915432734fe4", - "name": "out_channels = 64", - "type": "OutChannelsAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "64", - "isMandatory": true - }, - "384057f0-1660-4182-b949-ec86530932c7": { - "id": "384057f0-1660-4182-b949-ec86530932c7", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "337d5cab-647f-4a0f-865e-789e925a7e0c": { - "id": "337d5cab-647f-4a0f-865e-789e925a7e0c", - "name": "in_channels = 64", - "type": "InChannelsAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 180, - "height": 20 + "data": { + "name": "l5", + "attributes": { + "name": "l5", + "kernel_dim": "[3, 3]", + "out_channels": "64", + "actv_func": "relu", + "in_channels": "64" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "64", - "isMandatory": false + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" }, - "c97bc5bd-dfff-4d74-8d6d-b9bee945913c": { + { "id": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", - "name": "FlattenLayer", "type": "FlattenLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": 20, - "y": -320, + "position": { + "x": 730, + "y": 100 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "6c62667a-893f-48bd-9cdb-9c4a21bf5fed" - ], - "methods": [] - }, - "6c62667a-893f-48bd-9cdb-9c4a21bf5fed": { - "id": "6c62667a-893f-48bd-9cdb-9c4a21bf5fed", - "name": "name = l6", - "type": "NameAttributeFlatten", - "owner": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", - "bounds": { - "x": 20, - "y": -320, - "width": 210, - "height": 20 + "data": { + "name": "l6", + "attributes": { + "name": "l6" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l6", - "isMandatory": true + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" }, - "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4": { + { "id": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": 160, - "y": -330, + "position": { + "x": 870, + "y": 90 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "9126a77d-afd8-40d1-b18b-b50e747624a0", - "bc911bfa-baa2-4c39-aeae-17d57747e317", - "797b5fcb-4688-4d0a-8536-2b32bfeb7c51", - "2bb380fd-1d08-41f4-87c4-741d167d8404" - ], - "methods": [] - }, - "9126a77d-afd8-40d1-b18b-b50e747624a0": { - "id": "9126a77d-afd8-40d1-b18b-b50e747624a0", - "name": "name = l7", - "type": "NameAttributeLinear", - "owner": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "bounds": { - "x": 160, - "y": -330, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l7", - "isMandatory": true - }, - "bc911bfa-baa2-4c39-aeae-17d57747e317": { - "id": "bc911bfa-baa2-4c39-aeae-17d57747e317", - "name": "out_features = 64", - "type": "OutFeaturesAttributeLinear", - "owner": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "bounds": { - "x": 160, - "y": -330, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_features", - "value": "64", - "isMandatory": true - }, - "797b5fcb-4688-4d0a-8536-2b32bfeb7c51": { - "id": "797b5fcb-4688-4d0a-8536-2b32bfeb7c51", - "name": "actv_func = relu", - "type": "ActvFuncAttributeLinear", - "owner": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "bounds": { - "x": 160, - "y": -330, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "2bb380fd-1d08-41f4-87c4-741d167d8404": { - "id": "2bb380fd-1d08-41f4-87c4-741d167d8404", - "name": "in_features = 1024", - "type": "InFeaturesAttributeLinear", - "owner": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "bounds": { - "x": 160, - "y": -330, - "width": 190, - "height": 20 + "data": { + "name": "l7", + "attributes": { + "name": "l7", + "out_features": "64", + "actv_func": "relu", + "in_features": "1024" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_features", - "value": "1024", - "isMandatory": false + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" }, - "448f4122-75ed-4acb-b54a-c00a052a04b5": { + { "id": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": 300, - "y": -330, + "position": { + "x": 1010, + "y": 90 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "030354fc-6f46-48e7-9f8e-f919af96a016", - "b6e82026-c047-442e-ae8c-4c96b66f1dfa", - "3ba40354-cfc2-4710-ba55-ca8e1879b78e" - ], - "methods": [] - }, - "030354fc-6f46-48e7-9f8e-f919af96a016": { - "id": "030354fc-6f46-48e7-9f8e-f919af96a016", - "name": "name = l8", - "type": "NameAttributeLinear", - "owner": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "bounds": { - "x": 300, - "y": -330, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l8", - "isMandatory": true - }, - "b6e82026-c047-442e-ae8c-4c96b66f1dfa": { - "id": "b6e82026-c047-442e-ae8c-4c96b66f1dfa", - "name": "out_features = 10", - "type": "OutFeaturesAttributeLinear", - "owner": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "bounds": { - "x": 300, - "y": -330, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_features", - "value": "10", - "isMandatory": true - }, - "3ba40354-cfc2-4710-ba55-ca8e1879b78e": { - "id": "3ba40354-cfc2-4710-ba55-ca8e1879b78e", - "name": "in_features = 64", - "type": "InFeaturesAttributeLinear", - "owner": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "bounds": { - "x": 300, - "y": -330, - "width": 180, - "height": 20 + "data": { + "name": "l8", + "attributes": { + "name": "l8", + "out_features": "10", + "in_features": "64" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_features", - "value": "64", - "isMandatory": false + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" }, - "399f908e-b3ec-4c17-ad60-f5327f1b6aa0": { + { "id": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "name": "Configuration", "type": "Configuration", - "owner": null, - "bounds": { + "position": { "x": -650, - "y": -70, + "y": -70 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "5cdfcd61-4afe-48f2-831e-433e8573bb6f", - "11db3162-21fb-47b5-9e13-07992157917f", - "a8ae0754-736e-46fd-8f8a-d3cefb0af682", - "f022489b-c72c-4c39-af28-4553c4caf858", - "fc2d0e02-dbce-47ee-a0f5-8a4cb6be264b", - "ee723efc-e7a9-4f34-b235-133792d1468f" - ], - "methods": [] - }, - "5cdfcd61-4afe-48f2-831e-433e8573bb6f": { - "id": "5cdfcd61-4afe-48f2-831e-433e8573bb6f", - "name": "batch_size = 32", - "type": "BatchSizeAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "batch_size", - "value": "32", - "isMandatory": true - }, - "11db3162-21fb-47b5-9e13-07992157917f": { - "id": "11db3162-21fb-47b5-9e13-07992157917f", - "name": "epochs = 10", - "type": "EpochsAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 160, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "epochs", - "value": "10", - "isMandatory": true - }, - "a8ae0754-736e-46fd-8f8a-d3cefb0af682": { - "id": "a8ae0754-736e-46fd-8f8a-d3cefb0af682", - "name": "learning_rate = 0.001", - "type": "LearningRateAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 230, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "learning_rate", - "value": "0.001", - "isMandatory": true - }, - "f022489b-c72c-4c39-af28-4553c4caf858": { - "id": "f022489b-c72c-4c39-af28-4553c4caf858", - "name": "optimizer = adam", - "type": "OptimizerAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "optimizer", - "value": "adam", - "isMandatory": true - }, - "fc2d0e02-dbce-47ee-a0f5-8a4cb6be264b": { - "id": "fc2d0e02-dbce-47ee-a0f5-8a4cb6be264b", - "name": "loss_function = crossentropy", - "type": "LossFunctionAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 260, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "loss_function", - "value": "crossentropy", - "isMandatory": true - }, - "ee723efc-e7a9-4f34-b235-133792d1468f": { - "id": "ee723efc-e7a9-4f34-b235-133792d1468f", - "name": "metrics = [f1-score]", - "type": "MetricsAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 280, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "metrics", - "value": "[f1-score]", - "isMandatory": true + "data": { + "name": "Configuration", + "attributes": { + "batch_size": "32", + "epochs": "10", + "learning_rate": "0.001", + "optimizer": "adam", + "loss_function": "crossentropy", + "metrics": "[f1-score]", + "name": "Configuration" + } + } }, - "19601d31-0821-4dde-a24b-c9059321657f": { + { "id": "19601d31-0821-4dde-a24b-c9059321657f", - "name": "TrainingDataset", "type": "TrainingDataset", - "owner": null, - "bounds": { + "position": { "x": -340, - "y": -50, + "y": -50 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "349b6bdd-c067-4865-a9a5-170f859a0311", - "a9e4a4af-c700-4b67-b51d-f1e5fca2e68a", - "e8a36a43-bde0-4a1b-b579-1f63ae18d4ed", - "5568a334-08bf-4dd5-9575-3ac26892670d", - "b9e824a0-3cd8-4c6a-9d84-ae7e311297c1", - "e813c402-0c8d-4f32-8cbb-af5eb0da0d48" - ], - "methods": [] - }, - "349b6bdd-c067-4865-a9a5-170f859a0311": { - "id": "349b6bdd-c067-4865-a9a5-170f859a0311", - "name": "name = train_data", - "type": "NameAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "train_data", - "isMandatory": true - }, - "a9e4a4af-c700-4b67-b51d-f1e5fca2e68a": { - "id": "a9e4a4af-c700-4b67-b51d-f1e5fca2e68a", - "name": "path_data = dataset/cifar10/train", - "type": "PathDataAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 290, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "path_data", - "value": "dataset/cifar10/train", - "isMandatory": true - }, - "e8a36a43-bde0-4a1b-b579-1f63ae18d4ed": { - "id": "e8a36a43-bde0-4a1b-b579-1f63ae18d4ed", - "name": "task_type = multi_class", - "type": "TaskTypeAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 230, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "task_type", - "value": "multi_class", - "isMandatory": false - }, - "5568a334-08bf-4dd5-9575-3ac26892670d": { - "id": "5568a334-08bf-4dd5-9575-3ac26892670d", - "name": "input_format = images", - "type": "InputFormatAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "input_format", - "value": "images", - "isMandatory": false - }, - "b9e824a0-3cd8-4c6a-9d84-ae7e311297c1": { - "id": "b9e824a0-3cd8-4c6a-9d84-ae7e311297c1", - "name": "shape = [32, 32, 3]", - "type": "ShapeAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "shape", - "value": "[32, 32, 3]", - "isMandatory": false - }, - "e813c402-0c8d-4f32-8cbb-af5eb0da0d48": { - "id": "e813c402-0c8d-4f32-8cbb-af5eb0da0d48", - "name": "normalize = false", - "type": "NormalizeAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "bool", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "normalize", - "value": "false", - "isMandatory": false + "data": { + "name": "train_data", + "attributes": { + "name": "train_data", + "path_data": "dataset/cifar10/train", + "task_type": "multi_class", + "input_format": "images", + "shape": "[32, 32, 3]", + "normalize": false + } + } }, - "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302": { + { "id": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", - "name": "TestDataset", "type": "TestDataset", - "owner": null, - "bounds": { + "position": { "x": -80, - "y": -60, + "y": -60 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "f192f9df-844a-4e5f-a3be-117cabad01e6", - "146be0fe-0f87-42d1-b2d0-ea5fb774b0a9" - ], - "methods": [] - }, - "f192f9df-844a-4e5f-a3be-117cabad01e6": { - "id": "f192f9df-844a-4e5f-a3be-117cabad01e6", - "name": "name = test_data", - "type": "NameAttributeDataset", - "owner": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", - "bounds": { - "x": -80, - "y": -60, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "test_data", - "isMandatory": true - }, - "146be0fe-0f87-42d1-b2d0-ea5fb774b0a9": { - "id": "146be0fe-0f87-42d1-b2d0-ea5fb774b0a9", - "name": "path_data = dataset/cifar10/test", - "type": "PathDataAttributeDataset", - "owner": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", - "bounds": { - "x": -80, - "y": -60, - "width": 290, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "path_data", - "value": "dataset/cifar10/test", - "isMandatory": true + "data": { + "name": "test_data", + "attributes": { + "name": "test_data", + "path_data": "dataset/cifar10/test" + } + } } - }, - "relationships": { - "13169dfb-19ec-41f6-9814-5c350a2845b9": { + ], + "edges": [ + { "id": "13169dfb-19ec-41f6-9814-5c350a2845b9", - "name": "next", + "source": "dc98557d-a1e1-403d-afcb-01b318a221dd", + "target": "a0594c44-830e-4693-a34a-fd97f81f6b85", "type": "NNNext", - "owner": null, - "bounds": { - "x": -570, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "next", + "name": "next", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -570, + "y": -265 + }, + { + "x": -540, + "y": -265 + } + ] + } }, - "bdafcfe1-e093-481a-a868-9741cea085fc": { + { "id": "bdafcfe1-e093-481a-a868-9741cea085fc", - "name": "next", + "source": "a0594c44-830e-4693-a34a-fd97f81f6b85", + "target": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", "type": "NNNext", - "owner": null, - "bounds": { - "x": -430, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "next", + "name": "next", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -430, + "y": -265 + }, + { + "x": -400, + "y": -265 + } + ] + } }, - "1fd2f4f5-b2a5-46b4-a3c4-968484c7eeaa": { + { "id": "1fd2f4f5-b2a5-46b4-a3c4-968484c7eeaa", - "name": "next", + "source": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", + "target": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", "type": "NNNext", - "owner": null, - "bounds": { - "x": -290, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "next", + "name": "next", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -290, + "y": -265 + }, + { + "x": -260, + "y": -265 + } + ] + } }, - "3d84e689-b33d-477b-8a88-0a6b2564f4dd": { + { "id": "3d84e689-b33d-477b-8a88-0a6b2564f4dd", - "name": "next", + "source": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", + "target": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", "type": "NNNext", - "owner": null, - "bounds": { - "x": -150, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "next", + "name": "next", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -150, + "y": -265 + }, + { + "x": -120, + "y": -265 + } + ] + } }, - "60b782ab-f63e-44fc-b1cc-ff016dcdb47d": { + { "id": "60b782ab-f63e-44fc-b1cc-ff016dcdb47d", - "name": "next", + "source": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", + "target": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", "type": "NNNext", - "owner": null, - "bounds": { - "x": -10, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "next", + "name": "next", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -10, + "y": -265 + }, + { + "x": 20, + "y": -265 + } + ] + } }, - "02882625-8756-4a2d-a288-77f88020cdff": { + { "id": "02882625-8756-4a2d-a288-77f88020cdff", - "name": "next", + "source": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", + "target": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", "type": "NNNext", - "owner": null, - "bounds": { - "x": 130, - "y": -280, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "next", + "name": "next", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": 130, + "y": -270 + }, + { + "x": 160, + "y": -270 + } + ] + } }, - "7443ee55-2a5e-44c5-a981-b401a53d2dd6": { + { "id": "7443ee55-2a5e-44c5-a981-b401a53d2dd6", - "name": "next", + "source": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", + "target": "448f4122-75ed-4acb-b54a-c00a052a04b5", "type": "NNNext", - "owner": null, - "bounds": { - "x": 270, - "y": -285, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "next", + "name": "next", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": 270, + "y": -275 + }, + { + "x": 300, + "y": -275 + } + ] + } }, - "1c81e414-f791-4bb2-bfe5-ada765894730": { + { "id": "1c81e414-f791-4bb2-bfe5-ada765894730", - "name": "", + "source": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", + "target": "6feb868b-45bf-4c44-88ab-6af624191fa9", "type": "NNComposition", - "owner": null, - "bounds": { - "x": -600, - "y": -170, - "width": 10, - "height": 100 - }, - "path": [ - { - "x": 5, - "y": 100 - }, - { - "x": 5, - "y": 0 - } - ], - "source": { - "direction": "Up", - "element": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Bottomleft", - "element": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "top", + "targetHandle": "bottom-left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -595, + "y": -70 + }, + { + "x": -595, + "y": -170 + } + ] + } }, - "4d85f21f-a198-4249-a510-aed3fcf10ba6": { + { "id": "4d85f21f-a198-4249-a510-aed3fcf10ba6", - "name": "", + "source": "19601d31-0821-4dde-a24b-c9059321657f", + "target": "6feb868b-45bf-4c44-88ab-6af624191fa9", "type": "NNAssociation", - "owner": null, - "bounds": { - "x": -290, - "y": -170, - "width": 10, - "height": 120 - }, - "path": [ - { - "x": 5, - "y": 120 - }, - { - "x": 5, - "y": 0 - } - ], - "source": { - "direction": "Up", - "element": "19601d31-0821-4dde-a24b-c9059321657f", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Down", - "element": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "top", + "targetHandle": "bottom", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -285, + "y": -50 + }, + { + "x": -285, + "y": -170 + } + ] + } }, - "f6329bdf-b5e3-4f39-b9bf-ecd1e6c132e8": { + { "id": "f6329bdf-b5e3-4f39-b9bf-ecd1e6c132e8", - "name": "", + "source": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", + "target": "6feb868b-45bf-4c44-88ab-6af624191fa9", "type": "NNAssociation", - "owner": null, - "bounds": { - "x": -30, - "y": -170, - "width": 10, - "height": 110 - }, - "path": [ - { - "x": 5, - "y": 110 - }, - { - "x": 5, - "y": 0 - } - ], - "source": { - "direction": "Up", - "element": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Down", - "element": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "top", + "targetHandle": "bottom", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -25, + "y": -60 + }, + { + "x": -25, + "y": -170 + } + ] + } } - }, + ], "assessments": {} -} \ No newline at end of file +} diff --git a/tests/utilities/web_modeling_editor/backend/fixtures/template_state_machine_traffic_light.json b/tests/utilities/web_modeling_editor/backend/fixtures/template_state_machine_traffic_light.json index 57ef43d53..4694de7b2 100644 --- a/tests/utilities/web_modeling_editor/backend/fixtures/template_state_machine_traffic_light.json +++ b/tests/utilities/web_modeling_editor/backend/fixtures/template_state_machine_traffic_light.json @@ -1,382 +1,308 @@ { - "version": "3.0.0", + "version": "4.0.0", + "id": "converted-diagram-1778241725886", + "title": "", "type": "StateMachineDiagram", - "size": { "width": 1080, "height": 400 }, - "interactive": { "elements": {}, "relationships": {} }, - "elements": { - "bb23ddd6-3870-4ec8-914e-6d1ab24aa834": { - "id": "bb23ddd6-3870-4ec8-914e-6d1ab24aa834", - "name": "", - "type": "StateInitialNode", - "owner": null, - "bounds": { - "x": -850, - "y": -280, - "width": 45, - "height": 45 - } - }, - "435d3409-1e4c-4a00-94b7-d70238304594": { - "id": "435d3409-1e4c-4a00-94b7-d70238304594", - "name": "Red", - "type": "State", - "owner": null, - "bounds": { - "x": -550, - "y": -300, - "width": 160, - "height": 100 - }, - "bodies": [ - "6ad4504f-9589-456e-96e4-65446b921ae9" - ], - "fallbackBodies": [ - "6bc3cb72-fc37-48c2-bdf9-a5a2a6e33db1" - ] - }, - "6ad4504f-9589-456e-96e4-65446b921ae9": { - "id": "6ad4504f-9589-456e-96e4-65446b921ae9", - "name": "light_body", - "type": "StateBody", - "owner": "435d3409-1e4c-4a00-94b7-d70238304594", - "bounds": { - "x": -549.5, - "y": -259.5, - "width": 159, - "height": 30 - } - }, - "6bc3cb72-fc37-48c2-bdf9-a5a2a6e33db1": { - "id": "6bc3cb72-fc37-48c2-bdf9-a5a2a6e33db1", - "name": "fallback_body", - "type": "StateFallbackBody", - "owner": "435d3409-1e4c-4a00-94b7-d70238304594", - "bounds": { - "x": -549.5, - "y": -229.5, - "width": 159, - "height": 30 - } - }, - "9a0496ca-26be-473e-bd98-f27a916ed8fd": { - "id": "9a0496ca-26be-473e-bd98-f27a916ed8fd", - "name": "Green", - "type": "State", - "owner": null, - "bounds": { - "x": -70, - "y": -150, - "width": 160, - "height": 100 - }, - "bodies": [ - "2cc41e70-e864-4cf8-9c93-f037ee2da9dd" - ], - "fallbackBodies": [ - "970541a6-dfef-4bd4-88a7-16cd3f17de9f" - ] - }, - "2cc41e70-e864-4cf8-9c93-f037ee2da9dd": { - "id": "2cc41e70-e864-4cf8-9c93-f037ee2da9dd", - "name": "light_body", - "type": "StateBody", - "owner": "9a0496ca-26be-473e-bd98-f27a916ed8fd", - "bounds": { - "x": -69.5, - "y": -109.5, - "width": 159, - "height": 30 - } - }, - "970541a6-dfef-4bd4-88a7-16cd3f17de9f": { - "id": "970541a6-dfef-4bd4-88a7-16cd3f17de9f", - "name": "fallback_body", - "type": "StateFallbackBody", - "owner": "9a0496ca-26be-473e-bd98-f27a916ed8fd", - "bounds": { - "x": -69.5, - "y": -79.5, - "width": 159, - "height": 30 - } - }, - "557a86bb-d3ef-46bb-b766-0d8f7e785613": { - "id": "557a86bb-d3ef-46bb-b766-0d8f7e785613", - "name": "Amber", - "type": "State", - "owner": null, - "bounds": { - "x": 430, - "y": -300, - "width": 160, - "height": 100 - }, - "bodies": [ - "cb38bcab-92d0-4051-afdd-408e422bd01d" - ], - "fallbackBodies": [ - "54829163-af16-487e-b383-2e5c3d6fbbd4" - ] - }, - "cb38bcab-92d0-4051-afdd-408e422bd01d": { - "id": "cb38bcab-92d0-4051-afdd-408e422bd01d", - "name": "light_body", - "type": "StateBody", - "owner": "557a86bb-d3ef-46bb-b766-0d8f7e785613", - "bounds": { - "x": 430.5, - "y": -259.5, - "width": 159, - "height": 30 - } - }, - "54829163-af16-487e-b383-2e5c3d6fbbd4": { - "id": "54829163-af16-487e-b383-2e5c3d6fbbd4", - "name": "fallback_body", - "type": "StateFallbackBody", - "owner": "557a86bb-d3ef-46bb-b766-0d8f7e785613", - "bounds": { - "x": 430.5, - "y": -229.5, - "width": 159, - "height": 30 - } - }, - "59edd02e-7c85-40f1-90c0-e6313d8aed1f": { - "id": "59edd02e-7c85-40f1-90c0-e6313d8aed1f", - "name": "chronometer_finished", - "type": "StateCodeBlock", - "owner": null, - "bounds": { - "x": -970, - "y": 80, - "width": 580, - "height": 200 - }, - "code": "def chronometer_finished(session: Session, event_params: dict):\n # Python code here\n # Return Boolean value\n # Session can be read/written\n seconds = event_params['seconds']\n last_light_change_timestamp = session.get('last_light_change_timestamp')\n current_timestamp = datetime.datetime.now()\n if current_timestamp > (last_light_change_timestamp + seconds):\n return True\n return False", - "language": "python" - }, - "45d50e34-4bad-4f3f-8b41-bb46e43152a0": { - "id": "45d50e34-4bad-4f3f-8b41-bb46e43152a0", - "name": "light_body", - "type": "StateCodeBlock", - "owner": null, - "bounds": { - "x": -360, - "y": 80, - "width": 580, - "height": 200 - }, - "code": "def light_body(session: Session):\n # Python code here\n session.set('last_light_change_timestamp', datetime.datetime.now())\n # Example actions with the session\n # session.set('x', 555)\n # x = session.get('x')\n # session.delete('x')\n # Write anything else...\n # The return is ignored", - "language": "python" - }, - "f9fcaea7-342a-4365-860c-37c412e1deec": { - "id": "f9fcaea7-342a-4365-860c-37c412e1deec", - "name": "fallback_body", - "type": "StateCodeBlock", - "owner": null, - "bounds": { - "x": 250, - "y": 80, - "width": 580, - "height": 200 - }, - "code": "def fallback_body(session: Session):\n # Python code here\n print('Something went wrong')\n # The return is ignored", - "language": "python" - } - }, - "relationships": { - "8c4bd931-7ce2-412d-9104-527c407ca2fb": { - "id": "8c4bd931-7ce2-412d-9104-527c407ca2fb", - "name": "", - "type": "StateTransition", - "owner": null, - "bounds": { - "x": -805, - "y": -257.5, - "width": 255, - "height": 1 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 255, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "bb23ddd6-3870-4ec8-914e-6d1ab24aa834", - "bounds": { - "x": -805, - "y": -257.5, - "width": 0, - "height": 0 - } - }, - "target": { - "direction": "Left", - "element": "435d3409-1e4c-4a00-94b7-d70238304594", - "bounds": { - "x": -550, - "y": -265, - "width": 0, - "height": 0 - } - }, - "isManuallyLayouted": false - }, - "93a19abe-c9da-4e5b-ba66-1f3a4bc788f5": { - "id": "93a19abe-c9da-4e5b-ba66-1f3a4bc788f5", - "name": "chronometer_finished", - "type": "StateTransition", - "owner": null, - "bounds": { - "x": -390, - "y": -250, - "width": 320, - "height": 150 - }, - "path": [ - { - "x": 0, - "y": 0 - }, - { - "x": 160, - "y": 0 - }, - { - "x": 160, - "y": 150 - }, - { - "x": 320, - "y": 150 - } - ], - "source": { - "direction": "Right", - "element": "435d3409-1e4c-4a00-94b7-d70238304594", - "bounds": { - "x": -390, - "y": -250, - "width": 0, - "height": 0 - } - }, - "target": { - "direction": "Left", - "element": "9a0496ca-26be-473e-bd98-f27a916ed8fd", - "bounds": { - "x": -60, - "y": -250, - "width": 0, - "height": 0 - } - }, - "isManuallyLayouted": false, - "params": "{60}" - }, - "ffdc4d9d-fb7e-4332-bb95-4249c423f5b7": { - "id": "ffdc4d9d-fb7e-4332-bb95-4249c423f5b7", - "name": "chronometer_finished", - "type": "StateTransition", - "owner": null, - "bounds": { - "x": 90, - "y": -250, - "width": 340, - "height": 150 - }, - "path": [ - { - "x": 0, - "y": 150 - }, - { - "x": 170, - "y": 150 - }, - { - "x": 170, - "y": 0 - }, - { - "x": 340, - "y": 0 - } - ], - "source": { - "direction": "Right", - "element": "9a0496ca-26be-473e-bd98-f27a916ed8fd", - "bounds": { - "x": 100, - "y": -250, - "width": 0, - "height": 0 - } - }, - "target": { - "direction": "Left", - "element": "557a86bb-d3ef-46bb-b766-0d8f7e785613", - "bounds": { - "x": 430, - "y": -250, - "width": 0, - "height": 0 - } - }, - "isManuallyLayouted": false, - "params": "{20}" - }, - "5a968a7c-6237-4786-9002-19c051498aba": { - "id": "5a968a7c-6237-4786-9002-19c051498aba", - "name": "chronometer_finished", - "type": "StateTransition", - "owner": null, - "bounds": { - "x": -390, - "y": -290, - "width": 820, - "height": 41 - }, - "path": [ - { - "x": 820, - "y": 40 - }, - { - "x": 0, - "y": 40 - } - ], - "source": { - "direction": "Left", - "element": "557a86bb-d3ef-46bb-b766-0d8f7e785613", - "bounds": { - "x": 430, - "y": -250, - "width": 0, - "height": 0 - } - }, - "target": { - "direction": "Right", - "element": "435d3409-1e4c-4a00-94b7-d70238304594", - "bounds": { - "x": -390, - "y": -250, - "width": 0, - "height": 0 - } - }, - "isManuallyLayouted": false, - "params": "{3}" - } - }, - "assessments": {} + "nodes": [ + { + "id": "bb23ddd6-3870-4ec8-914e-6d1ab24aa834", + "type": "StateInitialNode", + "position": { + "x": -850, + "y": -280 + }, + "width": 45, + "height": 45, + "measured": { + "width": 45, + "height": 45 + }, + "data": { + "name": "" + } + }, + { + "id": "435d3409-1e4c-4a00-94b7-d70238304594", + "type": "State", + "position": { + "x": -550, + "y": -300 + }, + "width": 160, + "height": 100, + "measured": { + "width": 160, + "height": 100 + }, + "data": { + "name": "Red", + "bodies": [ + { + "id": "6ad4504f-9589-456e-96e4-65446b921ae9", + "name": "light_body" + } + ], + "fallbackBodies": [ + { + "id": "6bc3cb72-fc37-48c2-bdf9-a5a2a6e33db1", + "name": "fallback_body" + } + ] + } + }, + { + "id": "9a0496ca-26be-473e-bd98-f27a916ed8fd", + "type": "State", + "position": { + "x": -70, + "y": -150 + }, + "width": 160, + "height": 100, + "measured": { + "width": 160, + "height": 100 + }, + "data": { + "name": "Green", + "bodies": [ + { + "id": "2cc41e70-e864-4cf8-9c93-f037ee2da9dd", + "name": "light_body" + } + ], + "fallbackBodies": [ + { + "id": "970541a6-dfef-4bd4-88a7-16cd3f17de9f", + "name": "fallback_body" + } + ] + } + }, + { + "id": "557a86bb-d3ef-46bb-b766-0d8f7e785613", + "type": "State", + "position": { + "x": 430, + "y": -300 + }, + "width": 160, + "height": 100, + "measured": { + "width": 160, + "height": 100 + }, + "data": { + "name": "Amber", + "bodies": [ + { + "id": "cb38bcab-92d0-4051-afdd-408e422bd01d", + "name": "light_body" + } + ], + "fallbackBodies": [ + { + "id": "54829163-af16-487e-b383-2e5c3d6fbbd4", + "name": "fallback_body" + } + ] + } + }, + { + "id": "59edd02e-7c85-40f1-90c0-e6313d8aed1f", + "type": "StateCodeBlock", + "position": { + "x": -970, + "y": 80 + }, + "width": 580, + "height": 200, + "measured": { + "width": 580, + "height": 200 + }, + "data": { + "name": "chronometer_finished", + "code": "def chronometer_finished(session: Session, event_params: dict):\n # Python code here\n # Return Boolean value\n # Session can be read/written\n seconds = event_params['seconds']\n last_light_change_timestamp = session.get('last_light_change_timestamp')\n current_timestamp = datetime.datetime.now()\n if current_timestamp > (last_light_change_timestamp + seconds):\n return True\n return False", + "language": "python" + } + }, + { + "id": "45d50e34-4bad-4f3f-8b41-bb46e43152a0", + "type": "StateCodeBlock", + "position": { + "x": -360, + "y": 80 + }, + "width": 580, + "height": 200, + "measured": { + "width": 580, + "height": 200 + }, + "data": { + "name": "light_body", + "code": "def light_body(session: Session):\n # Python code here\n session.set('last_light_change_timestamp', datetime.datetime.now())\n # Example actions with the session\n # session.set('x', 555)\n # x = session.get('x')\n # session.delete('x')\n # Write anything else...\n # The return is ignored", + "language": "python" + } + }, + { + "id": "f9fcaea7-342a-4365-860c-37c412e1deec", + "type": "StateCodeBlock", + "position": { + "x": 250, + "y": 80 + }, + "width": 580, + "height": 200, + "measured": { + "width": 580, + "height": 200 + }, + "data": { + "name": "fallback_body", + "code": "def fallback_body(session: Session):\n # Python code here\n print('Something went wrong')\n # The return is ignored", + "language": "python" + } + } + ], + "edges": [ + { + "id": "8c4bd931-7ce2-412d-9104-527c407ca2fb", + "source": "bb23ddd6-3870-4ec8-914e-6d1ab24aa834", + "target": "435d3409-1e4c-4a00-94b7-d70238304594", + "type": "StateTransition", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "points": [ + { + "x": -805, + "y": -257.5 + }, + { + "x": -550, + "y": -257.5 + } + ] + } + }, + { + "id": "93a19abe-c9da-4e5b-ba66-1f3a4bc788f5", + "source": "435d3409-1e4c-4a00-94b7-d70238304594", + "target": "9a0496ca-26be-473e-bd98-f27a916ed8fd", + "type": "StateTransition", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "chronometer_finished", + "name": "chronometer_finished", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "params": [ + "{60}" + ], + "points": [ + { + "x": -390, + "y": -250 + }, + { + "x": -230, + "y": -250 + }, + { + "x": -230, + "y": -100 + }, + { + "x": -70, + "y": -100 + } + ] + } + }, + { + "id": "ffdc4d9d-fb7e-4332-bb95-4249c423f5b7", + "source": "9a0496ca-26be-473e-bd98-f27a916ed8fd", + "target": "557a86bb-d3ef-46bb-b766-0d8f7e785613", + "type": "StateTransition", + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "label": "chronometer_finished", + "name": "chronometer_finished", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "params": [ + "{20}" + ], + "points": [ + { + "x": 90, + "y": -100 + }, + { + "x": 260, + "y": -100 + }, + { + "x": 260, + "y": -250 + }, + { + "x": 430, + "y": -250 + } + ] + } + }, + { + "id": "5a968a7c-6237-4786-9002-19c051498aba", + "source": "557a86bb-d3ef-46bb-b766-0d8f7e785613", + "target": "435d3409-1e4c-4a00-94b7-d70238304594", + "type": "StateTransition", + "sourceHandle": "left", + "targetHandle": "right", + "data": { + "label": "chronometer_finished", + "name": "chronometer_finished", + "sourceMultiplicity": "", + "targetMultiplicity": "", + "sourceRole": "", + "targetRole": "", + "isManuallyLayouted": false, + "messages": [], + "params": [ + "{3}" + ], + "points": [ + { + "x": 430, + "y": -250 + }, + { + "x": -390, + "y": -250 + } + ] + } + } + ], + "assessments": {} } diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/parsers/test_constraint_descriptions.py b/tests/utilities/web_modeling_editor/backend/services/converters/parsers/test_constraint_descriptions.py index e0a57246b..8d0c5bba8 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/parsers/test_constraint_descriptions.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/parsers/test_constraint_descriptions.py @@ -234,9 +234,16 @@ def test_description_appears_in_json_output(self, professor_domain_model): class_buml_to_json, ) + # Pick the Professor class deterministically — ``next(iter(types))`` + # is flaky because ``DomainModel.types`` is a set that includes + # PrimitiveDataType instances alongside the user's classes. + professor_class = next( + t for t in professor_domain_model.types + if isinstance(t, Class) and t.name == "Professor" + ) c = Constraint( name="c1", - context=next(iter(professor_domain_model.types)), + context=professor_class, expression="context Professor inv: self.age > 25", language="OCL", description="Realistic age", @@ -244,12 +251,18 @@ def test_description_appears_in_json_output(self, professor_domain_model): professor_domain_model.constraints = {c} json_output = class_buml_to_json(professor_domain_model) - elements = json_output.get("elements", {}) - constraint_elements = [ - e for e in elements.values() if e.get("type") == "ClassOCLConstraint" - ] - assert constraint_elements, "expected at least one ClassOCLConstraint element" - assert constraint_elements[0].get("description") == "Realistic age" + # In v4, constraints with a class context are inlined as rows in + # ``data.oclConstraints`` on the owning class node. Free-standing + # constraints surface as their own ``ClassOCLConstraint`` node. + nodes = json_output.get("nodes") or [] + ocl_rows: list = [] + for node in nodes: + data = node.get("data") or {} + ocl_rows.extend(data.get("oclConstraints") or []) + if node.get("type") == "ClassOCLConstraint": + ocl_rows.append(data) + assert ocl_rows, "expected at least one inlined OCL constraint row" + assert ocl_rows[0].get("description") == "Realistic age" # The inline ``-- description`` split used a regex that CodeQL flagged as diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/placeholder_diagram.py b/tests/utilities/web_modeling_editor/backend/services/converters/placeholder_diagram.py index 3c325bc24..e1b52c955 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/placeholder_diagram.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/placeholder_diagram.py @@ -1,49 +1,46 @@ -"""The editor JSON of a class diagram whose elements named "..." are hidden.""" +"""The editor JSON (v4) of a class diagram whose elements named "..." are hidden.""" from besser.BUML.metamodel.structural import PLACEHOLDER_NAME -def _bounds(x, y): - return {"x": x, "y": y, "width": 160, "height": 100} +def class_node(node_id, name, x=0, attributes=(), stereotype=None): + """A ``class`` node; ``attributes`` are ``(row id, name)`` pairs.""" + rows = [{"id": row_id, "name": row_name, "attributeType": "str", "visibility": "public"} + for row_id, row_name in attributes] + return {"id": node_id, "type": "class", "position": {"x": x, "y": 0}, "width": 160, "height": 100, + "data": {"name": name, "stereotype": stereotype, "attributes": rows, "methods": []}} + + +def edge(edge_id, edge_type, source, target, **data): + return {"id": edge_id, "type": edge_type, "source": source, "target": target, + "data": {"points": [{"x": 0, "y": 0}, {"x": 10, "y": 10}], **data}} + + +def association(edge_id, source, target, source_role, target_role): + return edge(edge_id, "ClassBidirectional", source, target, name="", sourceMultiplicity="1", + sourceRole=source_role, targetMultiplicity="0..*", targetRole=target_role) + + +def class_diagram(nodes, edges=()) -> dict: + return {"title": "Zoo", "model": {"version": "4.0.0", "type": "ClassDiagram", + "nodes": list(nodes), "edges": list(edges)}} def placeholder_diagram() -> dict: """Animal <- Dog <- "..." and Animal <- "...", Animal -- "...", Kind {RED, GREEN, "..."}.""" - def cls(name, x, attributes=()): - return {"type": "Class", "name": name, "attributes": list(attributes), "methods": [], "bounds": _bounds(x, 0)} - - def inheritance(rel_id, specific, general): - return {"id": rel_id, "type": "ClassInheritance", - "source": {"element": specific, "bounds": _bounds(0, 0)}, - "target": {"element": general, "bounds": _bounds(0, 0)}, - "path": [{"x": 0, "y": 0}, {"x": 10, "y": 10}]} - - return { - "title": "Zoo", - "model": { - "type": "ClassDiagram", - "elements": { - "animal": cls("Animal", 0, ["animal-name"]), - "animal-name": {"type": "ClassAttribute", "name": "name", "attributeType": "str", - "visibility": "public", "owner": "animal"}, - "dog": cls("Dog", 200), - "hidden-1": cls(PLACEHOLDER_NAME, 400), - "hidden-2": cls(PLACEHOLDER_NAME, 600), - "kind": {"type": "Enumeration", "name": "Kind", "attributes": ["red", "green", "hidden-lit"], - "methods": [], "bounds": _bounds(800, 0)}, - "red": {"type": "EnumerationLiteral", "name": "RED"}, - "green": {"type": "EnumerationLiteral", "name": "GREEN"}, - "hidden-lit": {"type": "EnumerationLiteral", "name": PLACEHOLDER_NAME}, - }, - "relationships": { - "dog-animal": inheritance("dog-animal", "dog", "animal"), - "hidden-1-dog": inheritance("hidden-1-dog", "hidden-1", "dog"), - "hidden-2-animal": inheritance("hidden-2-animal", "hidden-2", "animal"), - "animal-hidden-1": { - "id": "animal-hidden-1", "type": "ClassBidirectional", - "source": {"element": "animal", "multiplicity": "1", "role": "owner"}, - "target": {"element": "hidden-1", "multiplicity": "0..*", "role": "hidden"}, - }, - }, - }, - } + return class_diagram( + [ + class_node("animal", "Animal", 0, [("animal-name", "name")]), + class_node("dog", "Dog", 200), + class_node("hidden-1", PLACEHOLDER_NAME, 400), + class_node("hidden-2", PLACEHOLDER_NAME, 600), + class_node("kind", "Kind", 800, [("red", "RED"), ("green", "GREEN"), ("hidden-lit", PLACEHOLDER_NAME)], + stereotype="Enumeration"), + ], + [ + edge("dog-animal", "ClassInheritance", "dog", "animal"), + edge("hidden-1-dog", "ClassInheritance", "hidden-1", "dog"), + edge("hidden-2-animal", "ClassInheritance", "hidden-2", "animal"), + association("animal-hidden-1", "animal", "hidden-1", "owner", "hidden"), + ], + ) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_a2a_tags.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_a2a_tags.py index 03b15c543..819e9e101 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_a2a_tags.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_a2a_tags.py @@ -88,41 +88,48 @@ def __init__(self, name="A"): self.name = name +def _node(node_id, node_type, **data): + return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, + "width": 160, "height": 80, "data": data} + + +def _edge(edge_id, edge_type, source, target, **data): + data.setdefault("points", []) + return {"id": edge_id, "type": edge_type, "source": source, "target": target, + "sourceHandle": "right", "targetHandle": "left", "data": data} + + def _tagged_diagram_json(): - """A minimal AgentDiagram JSON shaped like the frozen wire contract: - an AgentState carrying two a2a:out lines on `description`, and a - when_intent_matched transition carrying a2a:in on its `name`.""" + """A minimal v4 AgentDiagram JSON shaped like the frozen wire contract: + an AgentState carrying two a2a:out lines on `data.description`, and a + when_intent_matched transition carrying a2a:in on its `data.name`.""" return { "id": "diagram-coder", "model": { - "elements": { - "s-init": {"type": "StateInitialNode", "name": ""}, - "s-greet": {"type": "AgentState", "name": "greeting"}, - "s-write": { - "type": "AgentState", - "name": "write_code", - "description": ( + "version": "4.0.0", + "type": "AgentDiagram", + "nodes": [ + _node("s-init", "StateInitialNode", name=""), + _node("s-greet", "AgentState", name="greeting"), + _node( + "s-write", "AgentState", + name="write_code", + description=( "a2a:out;peer=AgentReviewer;ref=rev-uuid;flow=flow-09;order=2;kind=supervises\n" "a2a:out;peer=AgentTester;ref=test-uuid;flow=flow-09;order=1;kind=delegates" ), - }, - }, - "relationships": { - "t-init": { - "type": "AgentStateTransitionInit", - "name": "", - "source": {"element": "s-init"}, - "target": {"element": "s-greet"}, - }, - "t-in": { - "type": "AgentStateTransition", - "name": "a2a:in;peer=AgentSupervisor;ref=sup-uuid;flow=flow-09;kind=delegates", - "source": {"element": "s-greet"}, - "target": {"element": "s-write"}, - "predefined": {"predefinedType": "when_intent_matched", - "intentName": "recv_AgentSupervisor_task"}, - }, - }, + ), + ], + "edges": [ + _edge("t-init", "AgentStateTransitionInit", "s-init", "s-greet", name=""), + _edge( + "t-in", "AgentStateTransition", "s-greet", "s-write", + name="a2a:in;peer=AgentSupervisor;ref=sup-uuid;flow=flow-09;kind=delegates", + transitionType="predefined", + predefined={"predefinedType": "when_intent_matched", + "intentName": "recv_AgentSupervisor_task"}, + ), + ], }, } @@ -150,14 +157,14 @@ def test_annotate_legacy_diagram_sets_no_attribute(): legacy = { "id": "d", "model": { - "elements": { - "s1": {"type": "AgentState", "name": "idle"}, - }, - "relationships": { - "t1": {"type": "AgentStateTransition", "name": "", - "source": {"element": "s1"}, "target": {"element": "s1"}, - "predefined": {"predefinedType": "auto", "conditionValue": ""}}, - }, + "version": "4.0.0", + "type": "AgentDiagram", + "nodes": [_node("s1", "AgentState", name="idle")], + "edges": [ + _edge("t1", "AgentStateTransition", "s1", "s1", name="", + transitionType="predefined", + predefined={"predefinedType": "auto", "conditionValue": ""}), + ], }, } agent = annotate_agent_with_a2a(_FakeAgent(), legacy) @@ -181,8 +188,9 @@ def test_annotate_over_real_converter_keeps_intent_and_states(): json_data = _tagged_diagram_json() # Build the intents the transition references, so the converter resolves them. - json_data["model"]["elements"]["i-recv"] = { - "type": "AgentIntent", "name": "recv_AgentSupervisor_task", "bodies": [], + json_data["model"]["components"] = { + "i-recv": {"id": "i-recv", "type": "AgentIntent", + "name": "recv_AgentSupervisor_task", "bodies": []}, } # Point the transition's intent at the real intent element name. agent = process_agent_diagram(json_data) @@ -194,3 +202,41 @@ def test_annotate_over_real_converter_keeps_intent_and_states(): assert {"greeting", "write_code"} <= state_names assert any(i.name == "recv_AgentSupervisor_task" for i in agent.intents) assert agent._a2a["inbound"][0]["intent"] == "recv_AgentSupervisor_task" + + +# --------------------------------------------------------------------------- +# project .py round trip — the tags are written to B-UML and read back +# --------------------------------------------------------------------------- + +def test_a2a_tags_survive_a_project_buml_round_trip(tmp_path, monkeypatch): + from besser.utilities.buml_code_builder.project_builder import project_to_code + from besser.utilities.web_modeling_editor.backend.models.project import ProjectInput + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.project_converter import ( + project_to_json, + ) + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.project_converter import ( + json_to_buml_project, + ) + monkeypatch.chdir(tmp_path) + json_data = _tagged_diagram_json() + json_data["model"]["components"] = { + "i-recv": {"id": "i-recv", "type": "AgentIntent", + "name": "recv_AgentSupervisor_task", "bodies": []}, + } + project = {"id": "p", "type": "Project", "name": "Swarm", "createdAt": "2026-01-01T00:00:00Z", + "diagrams": {"AgentDiagram": [{"id": "diagram-coder", "title": "AgentCoder", + "model": json_data["model"]}]}} + out = tmp_path / "project.py" + project_to_code(json_to_buml_project(ProjectInput(**project)), str(out)) + [entry] = project_to_json(out.read_text(encoding="utf-8"))["diagrams"]["AgentDiagram"] + + expected = annotate_agent_with_a2a(_FakeAgent(), json_data)._a2a + assert annotate_agent_with_a2a(_FakeAgent(), entry)._a2a == expected + # The editor reads the tags from the state description and the transition name. + states = {n["data"]["name"]: n["data"] for n in entry["model"]["nodes"] if n["type"] == "AgentState"} + assert states["write_code"]["description"].splitlines() == [ + "a2a:out;peer=AgentTester;ref=test-uuid;flow=flow-09;order=1;kind=delegates", + "a2a:out;peer=AgentReviewer;ref=rev-uuid;flow=flow-09;order=2;kind=supervises", + ] + [tagged] = [e for e in entry["model"]["edges"] if e["data"].get("name", "").startswith("a2a:")] + assert tagged["data"]["name"] == "a2a:in;peer=AgentSupervisor;ref=sup-uuid;flow=flow-09;kind=delegates" diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_converter_multi_llm.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_converter_multi_llm.py new file mode 100644 index 000000000..2154a87cf --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_converter_multi_llm.py @@ -0,0 +1,312 @@ +""" +Multi-LLM round-trip tests for the agent converters (Wave 2). + +Two directions are exercised: + +1. v4 JSON (``{nodes, edges}`` with ``AgentLLM`` data-only nodes plus a + ``config.default_llm_name`` envelope) -> ``process_agent_diagram`` + -> Agent metamodel (``agent.llms`` / ``default_llm_name`` / + per-element ``llm_name``). +2. Agent metamodel -> generated B-UML code (``agent_model_to_code``) + -> ``agent_buml_to_json`` -> v4 JSON, asserting the AgentLLM nodes, + the ``config.default_llm_name`` payload, and the per-element + ``llm_name`` passthrough all survive. +""" + +import os +import tempfile + +import pytest + +from besser.BUML.metamodel.state_machine.agent import Agent, ReasoningState +from besser.utilities.buml_code_builder.agent_model_builder import agent_model_to_code +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.agent_diagram_processor import ( + process_agent_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.agent_diagram_converter import ( + agent_buml_to_json, +) + + +def _node(node_id, type_, data, x=0, y=0, width=160, height=80): + return { + "id": node_id, + "type": type_, + "position": {"x": x, "y": y}, + "width": width, + "height": height, + "data": data, + } + + +def _multi_llm_payload(): + """A v4 agent diagram with two LLM definitions, an LLM-reply body and + a reasoning state each bound to one of them, a RAG element bound by + name, and ``config.default_llm_name`` pointing at the second LLM.""" + nodes = [ + _node("init-1", "StateInitialNode", {"name": ""}, width=45, height=45), + _node( + "llm-1", + "AgentLLM", + { + "name": "fast", + "provider": "openai", + "parameters": {"model": "gpt-4o-mini", "temperature": 0.2}, + "num_previous_messages": 3, + "global_context": "Be terse.", + }, + width=200, + height=90, + ), + _node( + "llm-2", + "AgentLLM", + { + "name": "big", + "provider": "openai", + "parameters": {"model": "gpt-4o"}, + "num_previous_messages": 1, + "global_context": "", + }, + width=200, + height=90, + ), + _node( + "rs-1", + "AgentReasoningState", + { + "name": "reason", + "llm_name": "fast", + "max_steps": 5, + "enable_task_planning": True, + "stream_steps": True, + "system_prompt": "Think.", + "fallback_message": "", + }, + width=200, + ), + _node( + "as-1", + "AgentState", + { + "name": "answer", + "bodies": [ + { + "id": "b-1", + "name": "AI response", + "replyType": "llm", + "llm_name": "big", + }, + ], + }, + ), + _node( + "rag-1", + "AgentRagElement", + {"name": "manuals", "llm_name": "big"}, + width=120, + height=110, + ), + ] + edges = [ + { + "id": "e-init", + "source": "init-1", + "target": "rs-1", + "type": "AgentStateTransitionInit", + "data": {"points": []}, + }, + { + "id": "e-1", + "source": "rs-1", + "target": "as-1", + "type": "AgentStateTransition", + "data": { + "transitionType": "predefined", + "predefined": {"predefinedType": "when_no_intent_matched"}, + }, + }, + ] + return { + "title": "multi_llm_demo", + "model": { + "version": "4.0.0", + "type": "AgentDiagram", + "nodes": nodes, + "edges": edges, + }, + "config": {"default_llm_name": "big"}, + } + + +@pytest.fixture +def multi_llm_agent(): + return process_agent_diagram(_multi_llm_payload()) + + +class TestProcessMultiLlm: + """v4 JSON -> Agent metamodel.""" + + def test_llms_registered(self, multi_llm_agent): + assert {llm.name for llm in multi_llm_agent.llms} == {"fast", "big"} + fast = next(llm for llm in multi_llm_agent.llms if llm.name == "fast") + assert fast.parameters == {"model": "gpt-4o-mini", "temperature": 0.2} + assert fast.num_previous_messages == 3 + assert fast.global_context == "Be terse." + + def test_default_llm_applied_from_config(self, multi_llm_agent): + assert multi_llm_agent.default_llm_name == "big" + + def test_default_falls_back_to_first_registered(self): + payload = _multi_llm_payload() + payload["config"] = {} + agent = process_agent_diagram(payload) + assert agent.default_llm_name == "fast" + + def test_unknown_default_llm_is_ignored(self): + payload = _multi_llm_payload() + payload["config"] = {"default_llm_name": "missing"} + agent = process_agent_diagram(payload) + # Auto-default (first registered) stays in place. + assert agent.default_llm_name == "fast" + + def test_duplicate_llm_names_are_skipped(self): + payload = _multi_llm_payload() + dupe = dict(next( + n for n in payload["model"]["nodes"] if n["type"] == "AgentLLM" + )) + dupe["id"] = "llm-dupe" + payload["model"]["nodes"].append(dupe) + agent = process_agent_diagram(payload) + assert len(agent.llms) == 2 + + def test_reasoning_state_bound_to_named_llm(self, multi_llm_agent): + rs = next( + s for s in multi_llm_agent.states if isinstance(s, ReasoningState) + ) + assert rs.llm == "fast" + assert rs.max_steps == 5 + + def test_rag_bound_to_named_llm(self, multi_llm_agent): + rags = list(multi_llm_agent.rags) + assert len(rags) == 1 + assert rags[0].llm_name == "big" + + def test_llm_reply_body_keeps_llm_name(self, multi_llm_agent): + answer = next(s for s in multi_llm_agent.states if s.name == "answer") + llm_replies = [ + a for a in answer.body.actions if type(a).__name__ == "LLMReply" + ] + assert len(llm_replies) == 1 + assert llm_replies[0].llm_name == "big" + + +class TestMultiLlmRoundTrip: + """Agent metamodel -> builder code -> v4 JSON.""" + + @pytest.fixture + def reemitted(self, multi_llm_agent): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "agent.py") + agent_model_to_code(multi_llm_agent, path) + with open(path, encoding="utf-8") as f: + code = f.read() + return agent_buml_to_json(code) + + def _nodes_by_type(self, payload, node_type): + return [n for n in payload.get("nodes", []) if n.get("type") == node_type] + + def _components_by_type(self, payload, component_type): + """Off-canvas components (``model.components``) of one type. They are + never emitted as canvas nodes.""" + assert not self._nodes_by_type(payload, component_type) + return [c for c in (payload.get("components") or {}).values() if c.get("type") == component_type] + + def _reasoning_nodes(self, payload): + """AgentState nodes folded into a reasoning state (``data.stateType + == "reasoning"``) — the canonical v4 emission shape.""" + return [ + n for n in self._nodes_by_type(payload, "AgentState") + if (n.get("data") or {}).get("stateType") == "reasoning" + ] + + def test_agent_llm_nodes_reemitted(self, reemitted): + llms = self._components_by_type(reemitted, "AgentLLM") + assert {c["name"] for c in llms} == {"fast", "big"} + fast = next(c for c in llms if c["name"] == "fast") + assert fast["provider"] == "openai" + assert fast["parameters"] == { + "model": "gpt-4o-mini", + "temperature": 0.2, + } + assert fast["num_previous_messages"] == 3 + assert fast["global_context"] == "Be terse." + + def test_default_llm_name_reemitted_in_config(self, reemitted): + assert reemitted.get("config", {}).get("default_llm_name") == "big" + + def test_reasoning_state_llm_name_reemitted(self, reemitted): + rs = self._reasoning_nodes(reemitted)[0] + assert rs["data"]["stateType"] == "reasoning" + assert rs["data"]["llm_name"] == "fast" + + def test_rag_llm_name_reemitted(self, reemitted): + rag = self._components_by_type(reemitted, "AgentRagElement")[0] + assert rag["name"] == "manuals" + assert rag["llm_name"] == "big" + + def test_llm_reply_body_llm_name_reemitted(self, reemitted): + answer = next( + n for n in self._nodes_by_type(reemitted, "AgentState") + if n["data"]["name"] == "answer" + ) + llm_rows = [ + row for row in answer["data"].get("bodies", []) + if row.get("replyType") == "llm" + ] + assert len(llm_rows) == 1 + assert llm_rows[0]["llm_name"] == "big" + + def test_full_circle_restores_llm_registry(self, reemitted): + restored = process_agent_diagram( + {"model": reemitted, "config": reemitted.get("config", {})} + ) + assert {llm.name for llm in restored.llms} == {"fast", "big"} + assert restored.default_llm_name == "big" + rs = next(s for s in restored.states if isinstance(s, ReasoningState)) + assert rs.llm == "fast" + + +def test_builder_roundtrip_from_metamodel(tmp_path): + """Port of the development backend's + ``test_agent_roundtrip_preserves_multi_llm_and_reasoning`` — Agent + built directly via the metamodel API survives builder -> JSON -> + processor with both LLMs and the designated default intact.""" + agent = Agent("RoundTripAgent") + agent.new_llm(name="fast", provider="openai", parameters={"model": "gpt-4o-mini"}) + agent.new_llm(name="big", provider="openai", parameters={"model": "gpt-4o"}) + agent.set_default_llm("big") + initial = agent.new_state("initial", initial=True) + reason = agent.new_reasoning_state( + name="reason", llm="fast", max_steps=5, system_prompt="Think." + ) + initial.go_to(reason) + + code_path = os.path.join(str(tmp_path), "agent.py") + agent_model_to_code(agent, code_path) + with open(code_path, encoding="utf-8") as handle: + content = handle.read() + + json_model = agent_buml_to_json(content) + restored = process_agent_diagram( + {"model": json_model, "config": json_model.get("config", {})} + ) + + assert {llm.name for llm in restored.llms} == {"fast", "big"} + assert restored.default_llm_name == "big" + reasoning_states = [ + s for s in restored.states if isinstance(s, ReasoningState) + ] + assert len(reasoning_states) == 1 + assert reasoning_states[0].llm == "fast" + assert reasoning_states[0].max_steps == 5 diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_converter_roundtrip.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_converter_roundtrip.py index 3d7e774a5..dd254cb2c 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_converter_roundtrip.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_converter_roundtrip.py @@ -83,15 +83,18 @@ def test_agent_roundtrip_preserves_multi_llm_and_reasoning(tmp_path): json_model = agent_buml_to_json(content) - # The reasoning state must be emitted in the canonical shape the editor can - # deserialize: an AgentState carrying stateType "reasoning". The legacy - # AgentReasoningState element type was removed from the editor registry, so - # emitting it would crash on import. - json_elements = list(json_model.get("elements", {}).values()) - reasoning_elements = [el for el in json_elements if el.get("stateType") == "reasoning"] - assert len(reasoning_elements) == 1 - assert reasoning_elements[0]["type"] == "AgentState" - assert all(el.get("type") != "AgentReasoningState" for el in json_elements) + # The reasoning state must be emitted in the canonical v4 shape the editor can + # load: an AgentState node carrying data.stateType "reasoning". The legacy + # AgentReasoningState type is no longer registered by the editor. + json_nodes = json_model["nodes"] + reasoning_nodes = [n for n in json_nodes if n["data"].get("stateType") == "reasoning"] + assert len(reasoning_nodes) == 1 + assert reasoning_nodes[0]["type"] == "AgentState" + assert all(n.get("type") != "AgentReasoningState" for n in json_nodes) + # Components never become canvas nodes. + component_types = {c["type"] for c in json_model["components"].values()} + assert {"AgentLLM", "AgentTool", "AgentSkill", "AgentWorkspace", "AgentRagElement"} <= component_types + assert not component_types & {n["type"] for n in json_nodes} # process_agent_diagram consumes the frontend envelope: the apollon model # under "model" and the diagram config surfaced at the top level. @@ -314,13 +317,19 @@ def test_agent_roundtrip_preserves_ollama_llm_and_embedding(tmp_path): def _action(action_id, action_type, **fields): - return {"id": action_id, "type": "AgentStateBody", "name": fields.pop("name", action_type), - "actionType": action_type, **fields} + """A v4 AgentState action row (inline in ``data.bodies`` / ``data.fallbackBodies``).""" + return {"id": action_id, "name": fields.pop("name", action_type), "actionType": action_type, **fields} -def _transition(rel_id, source, target, **fields): - return {"id": rel_id, "type": "AgentStateTransition", "source": {"element": source}, - "target": {"element": target}, **fields} +def _transition(edge_id, source, target, **data): + return {"id": edge_id, "type": "AgentStateTransition", "source": source, "target": target, + "sourceHandle": "Right", "targetHandle": "Left", "data": {"points": [], **data}} + + +def _state(node_id, name, actions, fallback=(), initial=False): + return {"id": node_id, "type": "AgentState", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": name, "initial": initial, "stateType": "standard", + "bodies": list(actions), "fallbackBodies": list(fallback)}} def _live_testing_components(): @@ -328,7 +337,7 @@ def _live_testing_components(): "llm-1": {"id": "llm-1", "type": "AgentLLM", "name": "fast", "provider": "openai", "parameters": {"model": "gpt-4o-mini"}}, "int-1": {"id": "int-1", "type": "AgentIntent", "name": "greet", "bodies": ["int-1-b"]}, - "int-1-b": {"id": "int-1-b", "type": "AgentIntentBody", "name": _TRICKY}, + "int-1-b": {"id": "int-1-b", "type": "AgentIntentBody", "name": _TRICKY, "owner": "int-1"}, "rag-1": {"id": "rag-1", "type": "AgentRagElement", "name": "docs", "llm_name": "fast"}, "tool-1": {"id": "tool-1", "type": "AgentTool", "name": "lookup", "description": "d", "code": "def lookup(x):\n return x"}, @@ -339,71 +348,95 @@ def _live_testing_components(): } -def _live_testing_elements(): - return { - "init": {"id": "init", "type": "StateInitialNode", "name": ""}, - "s-ask": {"id": "s-ask", "type": "AgentState", "name": "ask", - "actions": ["a-text", "a-gui", "a-md", "a-html", "a-speech"], "fallbackActions": ["a-fb"]}, - "s-think": {"id": "s-think", "type": "AgentState", "name": "think", - "actions": ["a-llm", "a-chat", "a-rag", "a-db", "a-crawl"]}, - "s-files": {"id": "s-files", "type": "AgentState", "name": "files", "actions": ["a-done"]}, - "a-text": _action("a-text", "TextReplyAction", name=_TRICKY, useSessionVars=True), - "a-gui": _action("a-gui", "GUIReplyAction", guiId="signup"), - "a-md": _action("a-md", "WebSocketReplyMarkdownAction", ws_message="**{name}**", useSessionVars=True), - "a-html": _action("a-html", "WebSocketReplyHTMLAction", ws_message="{name}", useSessionVars=True), - "a-speech": _action("a-speech", "WebSocketReplySpeechAction", ws_message="Hi {name}", - ws_audio_speed=1.5, useSessionVars=True), - "a-fb": _action("a-fb", "GUIReplyAction", guiId="signup"), - "a-llm": _action("a-llm", "LLMReplyAction", system_message=_TRICKY, llm_name="fast", - inputPromptMode="custom", customInputPrompt="Summarise {email}", - customInputPromptUseSessionVars=True, systemPromptUseSessionVars=True, - storeInSession="summary", sendReply=False), - "a-chat": _action("a-chat", "LLMChatAction", system_message="Chat about {summary}", llm_name="fast", - systemPromptUseSessionVars=True, storeInSession="chat", sendReply=False), - "a-rag": _action("a-rag", "RAGReplyAction", ragDatabaseName="docs", prompt="Cite {summary}", - inputPromptMode="custom", customInputPrompt="Find {email}", - customInputPromptUseSessionVars=True, promptUseSessionVars=True, - storeInSession="rag_answer", sendReply=False), - "a-db": _action("a-db", "DBAction", dbQueryMode="llm_query", llm_name="fast", - inputPromptMode="custom", customInputPrompt="Rows for {email}", - customInputPromptUseSessionVars=True, storeInSession="rows", sendReply=False), - "a-crawl": _action("a-crawl", "WebCrawlLLMAction", initial_url="https://example.org", - system_message_prefix="Site of {email}", systemMessagePrefixUseSessionVars=True, - llm_name="fast", storeInSession="crawl", sendReply=False), - "a-done": _action("a-done", "TextReplyAction", name="Files received"), - } - - -def _live_testing_relationships(): - return { - "r-init": {"id": "r-init", "type": "AgentStateTransitionInit", "source": {"element": "init"}, - "target": {"element": "s-ask"}}, - "r-form": _transition("r-form", "s-ask", "s-think", transitionType="predefined", - predefined={"predefinedType": "when_form_submitted", "formGuiId": "signup"}), - "r-event": _transition("r-event", "s-think", "s-files", transitionType="custom", - custom={"event": "GUIEvent", "condition": [], "guiEventGuiId": "signup"}), - "r-files": _transition("r-files", "s-files", "s-ask", transitionType="predefined", - predefined={"predefinedType": "when_file_received", "fileType": "pdf, csv, image/png"}), - "r-intent": _transition("r-intent", "s-ask", "s-files", transitionType="predefined", - predefined={"predefinedType": "when_intent_matched", "intentName": "greet"}), - } +def _live_testing_nodes(): + return [ + _state("s-ask", "ask", [ + _action("a-text", "TextReplyAction", name=_TRICKY, useSessionVars=True), + _action("a-gui", "GUIReplyAction", guiId="signup"), + _action("a-md", "WebSocketReplyMarkdownAction", ws_message="**{name}**", useSessionVars=True), + _action("a-html", "WebSocketReplyHTMLAction", ws_message="{name}", useSessionVars=True), + _action("a-speech", "WebSocketReplySpeechAction", ws_message="Hi {name}", + ws_audio_speed=1.5, useSessionVars=True), + ], fallback=[_action("a-fb", "GUIReplyAction", guiId="signup")], initial=True), + _state("s-think", "think", [ + _action("a-llm", "LLMReplyAction", system_message=_TRICKY, llm_name="fast", + inputPromptMode="custom", customInputPrompt="Summarise {email}", + customInputPromptUseSessionVars=True, systemPromptUseSessionVars=True, + storeInSession="summary", sendReply=False), + _action("a-chat", "LLMChatAction", system_message="Chat about {summary}", llm_name="fast", + systemPromptUseSessionVars=True, storeInSession="chat", sendReply=False), + _action("a-rag", "RAGReplyAction", ragDatabaseName="docs", prompt="Cite {summary}", + inputPromptMode="custom", customInputPrompt="Find {email}", + customInputPromptUseSessionVars=True, promptUseSessionVars=True, + storeInSession="rag_answer", sendReply=False), + _action("a-db", "DBAction", dbQueryMode="llm_query", llm_name="fast", + inputPromptMode="custom", customInputPrompt="Rows for {email}", + customInputPromptUseSessionVars=True, storeInSession="rows", sendReply=False), + _action("a-crawl", "WebCrawlLLMAction", initial_url="https://example.org", + system_message_prefix="Site of {email}", systemMessagePrefixUseSessionVars=True, + llm_name="fast", storeInSession="crawl", sendReply=False), + ]), + _state("s-files", "files", [_action("a-done", "TextReplyAction", name="Files received")]), + ] + + +def _live_testing_edges(): + return [ + _transition("r-form", "s-ask", "s-think", transitionType="predefined", + predefined={"predefinedType": "when_form_submitted", "formGuiId": "signup"}), + _transition("r-event", "s-think", "s-files", transitionType="custom", + custom={"event": "GUIEvent", "condition": [], "guiEventGuiId": "signup"}), + _transition("r-files", "s-files", "s-ask", transitionType="predefined", + predefined={"predefinedType": "when_file_received", "fileType": "pdf, csv, image/png"}), + _transition("r-intent", "s-ask", "s-files", transitionType="predefined", + predefined={"predefinedType": "when_intent_matched", "intentName": "greet"}), + ] + + +def _component_nodes(components): + """Legacy v4 layout: components rendered as canvas nodes (pre-Components-page models). + + Intents carry their training sentences inline on ``data.training_phrases``. + """ + nodes = [] + for component in components.values(): + if component["type"] == "AgentIntentBody": + continue + data = {k: v for k, v in component.items() if k not in ("id", "type", "owner")} + if component["type"] == "AgentIntent": + data["training_phrases"] = [ + {"id": body_id, "name": components[body_id]["name"]} for body_id in data.pop("bodies") + ] + nodes.append({"id": component["id"], "type": component["type"], "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, "data": data}) + return nodes def _live_testing_diagram(layout: str = "components"): - """The live-testing diagram in the current layout (``model.components``), the old - layout (components inside ``model.elements``) or the legacy top-level ``agentComponents``.""" - elements = _live_testing_elements() - model = {"elements": elements, "relationships": _live_testing_relationships()} + """The live-testing diagram in the current layout (``model.components``), the legacy v4 + layout (components as canvas ``nodes``) or the legacy top-level ``agentComponents``.""" + nodes = _live_testing_nodes() + model = {"version": "4.0.0", "type": "AgentDiagram", "nodes": nodes, "edges": _live_testing_edges()} diagram = {"title": "LiveAgent", "model": model} if layout == "components": model["components"] = _live_testing_components() - elif layout == "elements": - elements.update(_live_testing_components()) + elif layout == "nodes": + nodes.extend(_component_nodes(_live_testing_components())) else: diagram["agentComponents"] = _live_testing_components() return diagram +def _state_rows(diagram_model, state_name, key="bodies"): + state = next(n for n in diagram_model["nodes"] + if n["type"] == "AgentState" and n["data"]["name"] == state_name) + return state["data"][key] + + +def _edge(diagram, edge_id): + return next(e for e in diagram["model"]["edges"] if e["id"] == edge_id) + + def _to_code(agent, tmp_path, name="agent.py"): code_path = os.path.join(str(tmp_path), name) agent_model_to_code(agent, code_path) @@ -461,17 +494,16 @@ def _agent_signature(agent): def _elements_by_type(json_model, element_type): - pool = {**json_model["elements"], **json_model["components"]} - return [el for el in pool.values() if el.get("type") == element_type] + """Components of ``element_type``; asserts none leaked onto the canvas.""" + assert all(n["type"] != element_type for n in json_model["nodes"]) + return [c for c in json_model["components"].values() if c.get("type") == element_type] -def _state_actions(json_model, state_name, key="actions"): - state = next(el for el in json_model["elements"].values() - if el.get("type") == "AgentState" and el.get("name") == state_name) - return {json_model["elements"][aid]["actionType"]: json_model["elements"][aid] for aid in state[key]} +def _state_actions(json_model, state_name, key="bodies"): + return {row["actionType"]: row for row in _state_rows(json_model, state_name, key)} -@pytest.mark.parametrize("layout", ["components", "elements", "agentComponents"]) +@pytest.mark.parametrize("layout", ["components", "nodes", "agentComponents"]) def test_live_testing_diagram_loads_in_every_layout(layout): agent = process_agent_diagram(_live_testing_diagram(layout)) assert {llm.name for llm in agent.llms} == {"fast"} @@ -509,17 +541,15 @@ def test_live_testing_json_roundtrip_preserves_editor_fields(tmp_path): source = _live_testing_diagram() json_model = agent_buml_to_json(_to_code(process_agent_diagram(copy.deepcopy(source)), tmp_path)) - source_elements = source["model"]["elements"] - for state_name, source_state in (("ask", "s-ask"), ("think", "s-think")): + for state_name in ("ask", "think"): actions = _state_actions(json_model, state_name) - for action_id in source_elements[source_state]["actions"]: - expected = source_elements[action_id] + for expected in _state_rows(source["model"], state_name): produced = actions[expected["actionType"]] - ignored = {"id", "type"} if expected["actionType"] == "TextReplyAction" else {"id", "type", "name"} + ignored = {"id"} if expected["actionType"] == "TextReplyAction" else {"id", "name"} for key, value in expected.items(): if key not in ignored: assert produced[key] == value, (state_name, expected["actionType"], key) - fallback = _state_actions(json_model, "ask", key="fallbackActions") + fallback = _state_actions(json_model, "ask", key="fallbackBodies") assert fallback["GUIReplyAction"]["guiId"] == "signup" guis = _elements_by_type(json_model, "AgentGUI") @@ -532,12 +562,15 @@ def test_live_testing_json_roundtrip_preserves_editor_fields(tmp_path): sentences = _elements_by_type(json_model, "AgentIntentBody") assert [s["name"] for s in sentences] == [_TRICKY] - transitions = [r for r in json_model["relationships"].values() if r["type"] == "AgentStateTransition"] + transitions = [e["data"] for e in json_model["edges"] if e["type"] == "AgentStateTransition"] predefined = {r["predefined"]["predefinedType"]: r["predefined"] for r in transitions if r["transitionType"] == "predefined"} assert predefined["when_form_submitted"]["formGuiId"] == "signup" assert predefined["when_file_received"]["fileType"] == "pdf, csv, png" custom = [r["custom"] for r in transitions if r["transitionType"] == "custom"] + # The initial state is a data flag, not a StateInitialNode marker. + initial = [n["data"]["name"] for n in json_model["nodes"] if n["data"].get("initial")] + assert initial == ["ask"] assert custom == [{"event": "GUIEvent", "condition": [], "guiEventGuiId": "signup"}] @@ -578,17 +611,17 @@ def test_gui_reply_without_agent_gui_is_rejected(): def test_intent_matched_transition_without_intent_is_rejected(): diagram = _live_testing_diagram() - diagram["model"]["relationships"]["r-intent"]["predefined"]["intentName"] = "" + _edge(diagram, "r-intent")["data"]["predefined"]["intentName"] = "" with pytest.raises(ValueError, match="names no intent"): process_agent_diagram(diagram) def test_state_with_two_auto_transitions_is_rejected(): diagram = _live_testing_diagram() - diagram["model"]["relationships"]["r-auto2"] = _transition( - "r-auto2", "s-think", "s-ask", transitionType="predefined", predefined={"predefinedType": "auto"}) - diagram["model"]["relationships"]["r-auto3"] = _transition( - "r-auto3", "s-think", "s-files", transitionType="predefined", predefined={"predefinedType": "auto"}) + diagram["model"]["edges"].append(_transition( + "r-auto2", "s-think", "s-ask", transitionType="predefined", predefined={"predefinedType": "auto"})) + diagram["model"]["edges"].append(_transition( + "r-auto3", "s-think", "s-files", transitionType="predefined", predefined={"predefinedType": "auto"})) with pytest.raises(ValueError, match="has 2 'auto' transitions"): process_agent_diagram(diagram) @@ -597,8 +630,8 @@ def test_auto_transition_next_to_another_transition_is_rejected(): """The quiz mistake: 'wrong answer' modelled as auto next to the intent transition of the same state.""" diagram = _live_testing_diagram() # s-ask already has transitions to s-think (form) and s-files (intent); add an auto one - diagram["model"]["relationships"]["r-auto"] = _transition( - "r-auto", "s-ask", "s-files", transitionType="predefined", predefined={"predefinedType": "auto"}) + diagram["model"]["edges"].append(_transition( + "r-auto", "s-ask", "s-files", transitionType="predefined", predefined={"predefinedType": "auto"})) with pytest.raises(ValueError, match="next to .* other transition"): process_agent_diagram(diagram) @@ -611,7 +644,7 @@ def _transitions_of(agent, state_name): def test_an_export_drops_an_intent_transition_that_names_no_intent_with_a_warning(caplog): """One stale transition in a saved project blocked its export and web-app generation.""" diagram = _live_testing_diagram() - diagram["model"]["relationships"]["r-intent"]["predefined"]["intentName"] = "" + _edge(diagram, "r-intent")["data"]["predefined"]["intentName"] = "" warnings = [] with caplog.at_level("WARNING"): agent = process_agent_diagram(diagram, warnings=warnings) @@ -622,8 +655,8 @@ def test_an_export_drops_an_intent_transition_that_names_no_intent_with_a_warnin def test_an_export_keeps_an_auto_transition_beside_another_with_a_warning(): diagram = _live_testing_diagram() - diagram["model"]["relationships"]["r-auto"] = _transition( - "r-auto", "s-ask", "s-files", transitionType="predefined", predefined={"predefinedType": "auto"}) + diagram["model"]["edges"].append(_transition( + "r-auto", "s-ask", "s-files", transitionType="predefined", predefined={"predefinedType": "auto"})) warnings = [] agent = process_agent_diagram(diagram, warnings=warnings) assert _transitions_of(agent, "ask") == ["files", "files", "think"] @@ -647,7 +680,7 @@ def test_a_project_with_a_stale_agent_transition_exports_as_buml(): from besser.utilities.web_modeling_editor.backend.backend import app diagram = _live_testing_diagram() - diagram["model"]["relationships"]["r-intent"]["predefined"]["intentName"] = "" + _edge(diagram, "r-intent")["data"]["predefined"]["intentName"] = "" project = {"id": "p-1", "type": "Project", "name": "StaleAgent", "description": "", "createdAt": "2026-11-23T00:00:00Z", "currentDiagramType": "AgentDiagram", "currentDiagramIndices": {"AgentDiagram": 0}, @@ -669,7 +702,7 @@ def test_the_project_agents_of_a_web_app_tolerate_a_stale_transition(): ) diagram = _live_testing_diagram() - diagram["model"]["relationships"]["r-intent"]["predefined"]["intentName"] = "" + _edge(diagram, "r-intent")["data"]["predefined"]["intentName"] = "" agents, _, _ = collect_agents_from_diagrams([{"id": "agent-1", **diagram}], default_config={}) assert [a.name for a in agents] == ["LiveAgent"] @@ -681,7 +714,7 @@ def test_agent_generation_still_refuses_a_stale_transition(tmp_path): from besser.utilities.web_modeling_editor.backend.services.generation.agents import generate_agent_output diagram = _live_testing_diagram() - diagram["model"]["relationships"]["r-intent"]["predefined"]["intentName"] = "" + _edge(diagram, "r-intent")["data"]["predefined"]["intentName"] = "" with pytest.raises(ValueError, match="names no intent"): asyncio.run(generate_agent_output(diagram)) @@ -695,9 +728,9 @@ def test_custom_condition_code_is_wired_under_its_generated_name(tmp_path): diagram = _live_testing_diagram() for rel_id, dest, value in (("r-c1", "s-think", 1), ("r-c2", "s-ask", 2)): - diagram["model"]["relationships"][rel_id] = _transition( + diagram["model"]["edges"].append(_transition( rel_id, "s-files", dest, transitionType="custom", - custom={"event": "None", "condition": [f"def condition(session):\n return session.get('q') == {value}"]}) + custom={"event": "None", "condition": [f"def condition(session):\n return session.get('q') == {value}"]})) agent = process_agent_diagram(diagram) BAFGenerator(agent, output_dir=str(tmp_path), generation_mode=GenerationMode.CODE_ONLY).generate() code = (tmp_path / f"{agent.name}.py").read_text(encoding="utf-8") @@ -716,8 +749,8 @@ def test_a_helper_above_a_custom_condition_is_not_the_function_that_gets_renamed diagram = _live_testing_diagram() code = ("def _came_from_q1(session):\n return session.get('came_from') == 'q1'\n\n" "def condition(session):\n return _came_from_q1(session)") - diagram["model"]["relationships"]["r-c1"] = _transition( - "r-c1", "s-files", "s-think", transitionType="custom", custom={"event": "None", "condition": [code]}) + diagram["model"]["edges"].append(_transition( + "r-c1", "s-files", "s-think", transitionType="custom", custom={"event": "None", "condition": [code]})) agent = process_agent_diagram(diagram) BAFGenerator(agent, output_dir=str(tmp_path), generation_mode=GenerationMode.CODE_ONLY).generate() generated = (tmp_path / f"{agent.name}.py").read_text(encoding="utf-8") @@ -737,7 +770,7 @@ def test_undesigned_agent_gui_becomes_empty_gui_model(): def test_custom_input_mode_without_prompt_is_rejected(): diagram = _live_testing_diagram() - diagram["model"]["elements"]["a-llm"]["customInputPrompt"] = "" + next(row for row in _state_rows(diagram["model"], "think") if row["id"] == "a-llm")["customInputPrompt"] = "" with pytest.raises(ValueError, match="requires a non-empty custom_input_prompt"): process_agent_diagram(diagram) @@ -768,3 +801,33 @@ def test_project_export_import_keeps_agent_gui_inside_agent_diagram(tmp_path): assert [g["gui_id"] for g in guis] == ["signup"] restored = process_agent_diagram({"title": "LiveAgent", "model": agent_json}) assert _agent_signature(restored) == _agent_signature(agent) + + +def test_rag_embedding_and_hybrid_settings_roundtrip(tmp_path): + """RAG embedding (Ollama base_url/model) and hybrid retrieval settings are read from the + AgentRagElement component (and from a legacy RAG node's data) and emitted back on the + component by buml_to_json.""" + rag = {"id": "rag-1", "type": "AgentRagElement", "name": "local_docs", "llm_name": "", + "embedding_provider": "ollama", "embedding_base_url": "http://ollama:11434", + "embedding_model": "mxbai-embed-large", "use_hybrid_rag": True, "bm25_weight": 0.3, + "k": 5, "num_previous_messages": 2, "llm_prompt": "Use the docs."} + state = _state("s-1", "answer", [_action("a-rag", "RAGReplyAction", ragDatabaseName="local_docs")], + initial=True) + as_component = {"title": "RagAgent", "model": {"nodes": [state], "edges": [], "components": {"rag-1": rag}}} + as_legacy_node = {"title": "RagAgent", "model": {"nodes": [state] + _component_nodes({"rag-1": rag}), + "edges": []}} + for diagram in (as_component, as_legacy_node): + agent = process_agent_diagram(copy.deepcopy(diagram)) + (restored_rag,) = agent.rags + assert restored_rag.vector_store.embedding_provider == "ollama" + assert restored_rag.vector_store.embedding_parameters == { + "base_url": "http://ollama:11434", "model": "mxbai-embed-large"} + assert (restored_rag.use_hybrid_rag, restored_rag.bm25_weight) == (True, 0.3) + assert (restored_rag.k, restored_rag.num_previous_messages) == (5, 2) + + json_model = agent_buml_to_json(_to_code(process_agent_diagram(copy.deepcopy(as_component)), tmp_path)) + (emitted,) = _elements_by_type(json_model, "AgentRagElement") + assert "bounds" not in emitted and "position" not in emitted + for key in ("embedding_provider", "embedding_base_url", "embedding_model", "use_hybrid_rag", + "bm25_weight", "k", "num_previous_messages", "llm_prompt"): + assert emitted[key] == rag[key], key diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_mixed_body_roundtrip.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_mixed_body_roundtrip.py new file mode 100644 index 000000000..207d54db1 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_mixed_body_roundtrip.py @@ -0,0 +1,63 @@ +""" +A state body that mixes a code action with other replies survives the B-UML +round trip (v4 JSON -> Agent -> generated .py -> v4 JSON). + +The exporter used to write only the code action of such a body, so +re-importing the .py lost the other replies. +""" + +import os +import tempfile + +from besser.utilities.buml_code_builder.agent_model_builder import agent_model_to_code +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.agent_diagram_processor import ( + process_agent_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.agent_diagram_converter import ( + agent_buml_to_json, +) + +CODE = "def log_visit(session):\n session.set('visited', True)" + + +def _node(node_id, type_, data): + return {"id": node_id, "type": type_, "position": {"x": 0, "y": 0}, + "width": 160, "height": 80, "data": data} + + +def _roundtrip(bodies): + payload = {"title": "MixedBody", "model": { + "version": "4.0.0", "type": "AgentDiagram", + "nodes": [ + _node("init", "StateInitialNode", {"name": ""}), + _node("s", "AgentState", {"name": "greet", "replyType": "text", "bodies": bodies}), + ], + "edges": [{"id": "e", "type": "AgentStateTransitionInit", "source": "init", "target": "s", + "data": {"params": {}, "points": []}}], + }} + agent = process_agent_diagram(payload) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "agent.py") + agent_model_to_code(agent, path) + with open(path, encoding="utf-8") as f: + content = f.read() + model = agent_buml_to_json(content) + state = next(n for n in model["nodes"] if n["type"] == "AgentState") + return [(row.get("replyType"), row.get("code") or row.get("name")) for row in state["data"]["bodies"]] + + +def test_code_mixed_with_text_keeps_every_reply_in_order(): + rows = _roundtrip([ + {"id": "r1", "name": "Hello!", "replyType": "text"}, + {"id": "r2", "name": "log_visit", "code": CODE, "replyType": "code"}, + {"id": "r3", "name": "Bye!", "replyType": "text"}, + ]) + assert [kind for kind, _ in rows] == ["text", "code", "text"] + assert rows[0][1] == "Hello!" and rows[2][1] == "Bye!" + assert "def log_visit(session):" in rows[1][1] + + +def test_a_code_only_body_still_round_trips(): + rows = _roundtrip([{"id": "r1", "name": "log_visit", "code": CODE, "replyType": "code"}]) + assert [kind for kind, _ in rows] == ["code"] + assert "def log_visit(session):" in rows[0][1] diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_options_label.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_options_label.py index 438713c60..effc80484 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_options_label.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_options_label.py @@ -15,22 +15,17 @@ def _diagram(label): - elements = { - "init": {"id": "init", "type": "StateInitialNode", "name": ""}, - "s-ask": {"id": "s-ask", "type": "AgentState", "name": "ask", "actions": ["a-opt"]}, - "s-done": {"id": "s-done", "type": "AgentState", "name": "done", "actions": []}, - "a-opt": {"id": "a-opt", "type": "AgentStateBody", "name": "Reply Options", - "actionType": "WebSocketReplyOptionsAction", "ws_options": "Oui\nNon", - **({"ws_options_label": label} if label is not None else {})}, - } - relationships = { - "r-init": {"id": "r-init", "type": "AgentStateTransitionInit", "source": {"element": "init"}, - "target": {"element": "s-ask"}}, - "r-next": {"id": "r-next", "type": "AgentStateTransition", "source": {"element": "s-ask"}, - "target": {"element": "s-done"}, "transitionType": "predefined", - "predefined": {"predefinedType": "auto"}}, - } - return {"title": "Quiz", "model": {"elements": elements, "relationships": relationships}} + def state(node_id, name, actions, initial=False): + return {"id": node_id, "type": "AgentState", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": name, "initial": initial, "stateType": "standard", + "bodies": actions, "fallbackBodies": []}} + + options = {"id": "a-opt", "name": "Reply Options", "actionType": "WebSocketReplyOptionsAction", + "ws_options": "Oui\nNon", **({"ws_options_label": label} if label is not None else {})} + nodes = [state("s-ask", "ask", [options], initial=True), state("s-done", "done", [])] + edges = [{"id": "r-next", "type": "AgentStateTransition", "source": "s-ask", "target": "s-done", + "data": {"transitionType": "predefined", "predefined": {"predefinedType": "auto"}}}] + return {"title": "Quiz", "model": {"version": "4.0.0", "type": "AgentDiagram", "nodes": nodes, "edges": edges}} def _options_action(agent): @@ -50,7 +45,8 @@ def test_label_survives_code_and_json_roundtrip(tmp_path): with open(code_path, encoding="utf-8") as handle: json_model = agent_buml_to_json(handle.read()) - options = next(el for el in json_model["elements"].values() if el.get("actionType") == "WebSocketReplyOptionsAction") + rows = (row for node in json_model["nodes"] for row in node["data"].get("bodies", [])) + options = next(row for row in rows if row.get("actionType") == "WebSocketReplyOptionsAction") assert options["ws_options"] == "Oui\nNon" assert options["ws_options_label"] == "Choisissez" diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_reasoning_roundtrip.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_reasoning_roundtrip.py new file mode 100644 index 000000000..e77ee8613 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_reasoning_roundtrip.py @@ -0,0 +1,379 @@ +""" +Roundtrip tests for the agent reasoning primitives (Wave 2). + +v4 JSON (``{nodes, edges}``) -> ``process_agent_diagram`` -> Agent metamodel +-> ``agent_model_to_code`` -> ``agent_buml_to_json`` -> v4 JSON. + +Covers ``AgentTool``, ``AgentSkill``, ``AgentWorkspace`` and reasoning +states — the four reasoning primitives the React Flow frontend ships on +the AgentDiagram palette (Capabilities / Reasoning sections). Shapes +mirror the frontend's ``NodeProps`` definitions. + +A reasoning state is the canonical v4 folded shape: ``type: "AgentState"`` +with ``data.stateType == "reasoning"``. The legacy ``type: +"AgentReasoningState"`` node (pre-fold) is covered separately below as a +back-compat read case. +""" + +import os +import tempfile + +import pytest + +from besser.BUML.metamodel.state_machine.agent import ReasoningState +from besser.utilities.buml_code_builder.agent_model_builder import agent_model_to_code +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.agent_diagram_processor import ( + process_agent_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.agent_diagram_converter import ( + agent_buml_to_json, +) + + +TOOL_CODE = "def ping():\n return 'pong'\n" + + +def _node(node_id, type_, data, x=0, y=0, width=160, height=80): + return { + "id": node_id, + "type": type_, + "position": {"x": x, "y": y}, + "width": width, + "height": height, + "data": data, + } + + +def _reasoning_payload(): + """A v4 agent diagram with one of each reasoning primitive. + + The initial-node edge targets the reasoning state, exercising the + "reasoning state can be the initial state" path. + + ``llm_name`` is empty — the editor's "(use default)" choice. A + non-empty name must reference a registered LLM (``AgentLLM`` + definitions arrive with the multi-LLM wave); see + ``test_unknown_llm_name_fails_validation``. + """ + nodes = [ + _node("init-1", "StateInitialNode", {"name": ""}, width=45, height=45), + _node( + "rs-1", + "AgentState", + { + "name": "reason", + "stateType": "reasoning", + "llm_name": "", + "max_steps": 15, + "enable_task_planning": True, + "stream_steps": False, + "system_prompt": "Be concise.", + "fallback_message": "Sorry, something broke.", + }, + width=200, + ), + _node( + "as-1", + "AgentState", + { + "name": "farewell", + "bodies": [ + {"id": "b-1", "name": "Bye!", "replyType": "text"}, + ], + }, + ), + _node( + "tool-1", + "AgentTool", + {"name": "ping", "description": "Ping the server.", "code": TOOL_CODE}, + ), + _node( + "skill-1", + "AgentSkill", + { + "name": "GreetByName", + "content": "Always greet the user by name.", + "description": "Greeting playbook.", + }, + ), + _node( + "ws-1", + "AgentWorkspace", + { + "name": "cinema", + "path": "/tmp/cinema", + "description": "Cinema files.", + "writable": False, + "max_read_bytes": 50_000, + }, + ), + ] + edges = [ + { + "id": "e-init", + "source": "init-1", + "target": "rs-1", + "type": "AgentStateTransitionInit", + "data": {"points": []}, + }, + { + "id": "e-1", + "source": "rs-1", + "target": "as-1", + "type": "AgentStateTransition", + "data": { + "transitionType": "predefined", + "predefined": {"predefinedType": "when_no_intent_matched"}, + }, + }, + ] + return { + "title": "reasoning_demo", + "model": { + "version": "4.0.0", + "type": "AgentDiagram", + "nodes": nodes, + "edges": edges, + }, + } + + +@pytest.fixture +def reasoning_agent(): + return process_agent_diagram(_reasoning_payload()) + + +class TestProcessReasoningPrimitives: + """v4 JSON -> Agent metamodel.""" + + def test_tool_registered(self, reasoning_agent): + assert len(reasoning_agent.tools) == 1 + tool = reasoning_agent.tools[0] + assert tool.name == "ping" + assert tool.description == "Ping the server." + assert tool.code == TOOL_CODE + + def test_skill_registered(self, reasoning_agent): + assert len(reasoning_agent.skills) == 1 + skill = reasoning_agent.skills[0] + assert skill.name == "GreetByName" + assert skill.content == "Always greet the user by name." + assert skill.description == "Greeting playbook." + + def test_workspace_registered(self, reasoning_agent): + assert len(reasoning_agent.workspaces) == 1 + ws = reasoning_agent.workspaces[0] + assert ws.name == "cinema" + assert ws.path == "/tmp/cinema" + assert ws.description == "Cinema files." + assert ws.writable is False + assert ws.max_read_bytes == 50_000 + + def test_reasoning_state_is_initial_with_fields(self, reasoning_agent): + reasoning_states = [ + s for s in reasoning_agent.states if isinstance(s, ReasoningState) + ] + assert len(reasoning_states) == 1 + rs = reasoning_states[0] + assert rs.name == "reason" + assert rs.initial is True + # Empty llm_name maps to None — "resolve the agent default at + # codegen time". + assert rs.llm is None + assert rs.max_steps == 15 + assert rs.enable_task_planning is True + assert rs.stream_steps is False + assert rs.system_prompt == "Be concise." + assert rs.fallback_message == "Sorry, something broke." + + def test_unknown_llm_name_fails_validation(self): + """A free-entry llm_name that no registered LLM matches must fail + loudly (metamodel ``_validate_llm_references``) instead of silently + generating an agent that cannot resolve its LLM. ``AgentLLM`` + diagram definitions arrive with the multi-LLM wave.""" + payload = _reasoning_payload() + rs_node = next( + n for n in payload["model"]["nodes"] + if n["type"] == "AgentState" and n["data"].get("stateType") == "reasoning" + ) + rs_node["data"]["llm_name"] = "gpt-4o-mini" + with pytest.raises(ValueError, match="not.*registered|new_llm"): + process_agent_diagram(payload) + + def test_transition_from_reasoning_state(self, reasoning_agent): + rs = next(s for s in reasoning_agent.states if isinstance(s, ReasoningState)) + assert len(rs.transitions) == 1 + assert rs.transitions[0].dest.name == "farewell" + + def test_duplicate_primitives_are_skipped(self): + payload = _reasoning_payload() + # Duplicate every primitive node under fresh ids. + dupes = [] + for n in payload["model"]["nodes"]: + if n["type"] in ("AgentTool", "AgentSkill", "AgentWorkspace"): + dupe = dict(n) + dupe["id"] = n["id"] + "-dupe" + dupes.append(dupe) + payload["model"]["nodes"].extend(dupes) + agent = process_agent_diagram(payload) + assert len(agent.tools) == 1 + assert len(agent.skills) == 1 + assert len(agent.workspaces) == 1 + + +class TestLegacyReasoningStateBackCompat: + """Pre-fold diagrams used a dedicated ``AgentReasoningState`` node + type. The processor must keep reading that shape for back-compat even + though the converter no longer emits it — canonical v4 output folds + reasoning states into ``type: "AgentState"`` + ``data.stateType == + "reasoning"`` (see ``TestReasoningRoundTrip`` above).""" + + def _legacy_payload(self): + nodes = [ + _node("init-1", "StateInitialNode", {"name": ""}, width=45, height=45), + _node( + "rs-1", + "AgentReasoningState", + { + "name": "reason", + "llm_name": "", + "max_steps": 15, + "enable_task_planning": True, + "stream_steps": False, + "system_prompt": "Be concise.", + "fallback_message": "Sorry, something broke.", + }, + width=200, + ), + ] + edges = [ + { + "id": "e-init", + "source": "init-1", + "target": "rs-1", + "type": "AgentStateTransitionInit", + "data": {"points": []}, + }, + ] + return { + "title": "legacy_reasoning_demo", + "model": { + "version": "4.0.0", + "type": "AgentDiagram", + "nodes": nodes, + "edges": edges, + }, + } + + def test_legacy_agent_reasoning_state_type_still_imports(self): + agent = process_agent_diagram(self._legacy_payload()) + reasoning_states = [s for s in agent.states if isinstance(s, ReasoningState)] + assert len(reasoning_states) == 1 + rs = reasoning_states[0] + assert rs.name == "reason" + assert rs.initial is True + assert rs.llm is None + assert rs.max_steps == 15 + assert rs.enable_task_planning is True + assert rs.stream_steps is False + assert rs.system_prompt == "Be concise." + assert rs.fallback_message == "Sorry, something broke." + + +class TestReasoningRoundTrip: + """Agent metamodel -> builder code -> v4 JSON.""" + + @pytest.fixture + def reemitted(self, reasoning_agent): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "agent.py") + agent_model_to_code(reasoning_agent, path) + with open(path, encoding="utf-8") as f: + code = f.read() + return agent_buml_to_json(code) + + def _nodes_by_type(self, payload, node_type): + return [n for n in payload.get("nodes", []) if n.get("type") == node_type] + + def _components_by_type(self, payload, component_type): + """Off-canvas components (``model.components``) of one type. They are + never emitted as canvas nodes.""" + assert not self._nodes_by_type(payload, component_type) + return [c for c in (payload.get("components") or {}).values() if c.get("type") == component_type] + + def _reasoning_nodes(self, payload): + """AgentState nodes folded into a reasoning state (``data.stateType + == "reasoning"``) — the canonical v4 emission shape.""" + return [ + n for n in self._nodes_by_type(payload, "AgentState") + if (n.get("data") or {}).get("stateType") == "reasoning" + ] + + def test_tool_node_reemitted(self, reemitted): + tools = self._components_by_type(reemitted, "AgentTool") + assert len(tools) == 1 + data = tools[0] + assert data["name"] == "ping" + assert data["description"] == "Ping the server." + assert data["code"] == TOOL_CODE + + def test_skill_node_reemitted(self, reemitted): + skills = self._components_by_type(reemitted, "AgentSkill") + assert len(skills) == 1 + data = skills[0] + assert data["name"] == "GreetByName" + assert data["content"] == "Always greet the user by name." + assert data["description"] == "Greeting playbook." + + def test_workspace_node_reemitted(self, reemitted): + workspaces = self._components_by_type(reemitted, "AgentWorkspace") + assert len(workspaces) == 1 + data = workspaces[0] + assert data["name"] == "cinema" + assert data["path"] == "/tmp/cinema" + assert data["description"] == "Cinema files." + assert data["writable"] is False + assert data["max_read_bytes"] == 50_000 + + def test_reasoning_state_node_reemitted(self, reemitted): + rs_nodes = self._reasoning_nodes(reemitted) + assert len(rs_nodes) == 1 + data = rs_nodes[0]["data"] + assert data["stateType"] == "reasoning" + assert data["name"] == "reason" + assert data["llm_name"] == "" + assert data["max_steps"] == 15 + assert data["enable_task_planning"] is True + assert data["stream_steps"] is False + assert data["system_prompt"] == "Be concise." + assert data["fallback_message"] == "Sorry, something broke." + + def test_initial_flag_on_reasoning_state(self, reemitted): + # v4: the initial state is ``data.initial`` on the state itself — no + # StateInitialNode marker and no AgentStateTransitionInit edge. + rs_node = self._reasoning_nodes(reemitted)[0] + assert rs_node["data"]["initial"] is True + initial_states = [ + n for n in self._nodes_by_type(reemitted, "AgentState") if n["data"].get("initial") + ] + assert initial_states == [rs_node] + assert not self._nodes_by_type(reemitted, "StateInitialNode") + assert not [e for e in reemitted.get("edges", []) if e.get("type") == "AgentStateTransitionInit"] + + def test_transition_reemitted_between_states(self, reemitted): + rs_node = self._reasoning_nodes(reemitted)[0] + as_node = next( + n for n in self._nodes_by_type(reemitted, "AgentState") + if n["data"]["name"] == "farewell" + ) + transitions = [ + e for e in reemitted.get("edges", []) + if e.get("type") == "AgentStateTransition" + ] + assert len(transitions) == 1 + assert transitions[0]["source"] == rs_node["id"] + assert transitions[0]["target"] == as_node["id"] + assert ( + transitions[0]["data"]["predefined"]["predefinedType"] + == "when_no_intent_matched" + ) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_transition_fallbacks.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_transition_fallbacks.py new file mode 100644 index 000000000..35891eb77 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_agent_transition_fallbacks.py @@ -0,0 +1,66 @@ +"""Legacy transition data that development's agent processor read. + +``_normalise_agent_transitions`` collapses legacy ``AgentStateTransition`` +data to the canonical v4 block, in the order the editor's TS normaliser +(``liftAgentTransitionDataToV4``) uses. These shapes reach the backend from +callers that skip the editor (API clients, stored JSON). +""" + +import pytest + +from besser.BUML.metamodel.state_machine.agent import FileTypeMatcher, IntentMatcher +from besser.utilities.web_modeling_editor.backend.services.converters import process_agent_diagram + + +def _agent(transition_data: dict): + model = { + "version": "4.0.0", "type": "AgentDiagram", + "nodes": [ + {"id": "s1", "type": "AgentState", "position": {"x": 0, "y": 0}, + "data": {"name": "A", "initial": True, "bodies": [{"id": "r1", "name": "hi", "replyType": "text"}], + "fallbackBodies": []}}, + {"id": "s2", "type": "AgentState", "position": {"x": 300, "y": 0}, + "data": {"name": "B", "bodies": [], "fallbackBodies": []}}, + ], + "edges": [{"id": "e1", "type": "AgentStateTransition", "source": "s1", "target": "s2", + "data": transition_data}], + "components": {"i1": {"id": "i1", "type": "AgentIntent", "name": "Hello", "bodies": ["b1"]}, + "b1": {"id": "b1", "type": "AgentIntentBody", "name": "hi", "owner": "i1"}}, + } + agent = process_agent_diagram({"title": "T", "model": model}) + (transition,) = next(s for s in agent.states if s.name == "A").transitions + return transition + + +@pytest.mark.parametrize("data", [ + {"predefinedType": "when_intent_matched", "conditionValue": "Hello"}, + {"transitionType": "predefined", "predefined": {"predefinedType": "when_intent_matched"}, + "conditionValue": "Hello"}, + {"transitionType": "predefined", + "predefined": {"predefinedType": "when_intent_matched", "conditionValue": "Hello"}}, +]) +def test_an_intent_named_only_by_condition_value(data): + (condition,) = _agent(data).conditions + assert isinstance(condition, IntentMatcher) + assert condition.intent.name == "Hello" + + +def test_a_file_type_named_only_by_condition_value(): + (condition,) = _agent({"predefinedType": "when_file_received", "conditionValue": "pdf"}).conditions + assert isinstance(condition, FileTypeMatcher) + assert condition.allowed_types == "application/pdf" + + +@pytest.mark.parametrize("key", ["conditions", "condition"]) +def test_custom_conditions_on_the_edge_data(key): + transition = _agent({"transitionType": "custom", "event": "WildcardEvent", + key: ["def c(session):\n return True"]}) + assert len(transition.conditions) == 1 + + +def test_an_idle_custom_bag_does_not_turn_an_intent_transition_custom(): + """The editor leaves ``custom: {event: "None", condition: []}`` on a predefined transition.""" + (condition,) = _agent({"predefinedType": "when_intent_matched", "intentName": "Hello", + "custom": {"event": "None", "condition": []}}).conditions + assert isinstance(condition, IntentMatcher) + assert condition.intent.name == "Hello" diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_agentic_converters.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_agentic_converters.py index a99ca83d3..a3a2dc709 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_agentic_converters.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_agentic_converters.py @@ -40,54 +40,75 @@ # --------------------------------------------------------------------------- -# Fixture helpers (mirror test_bpmn_converters.py _envelope / _node / _flow) +# Fixture helpers: v4 wire shape (flat nodes / edges, containment via parentId, +# agentic fields in node.data). Fixtures are id-keyed dicts of v4 nodes / edges +# so tests can look entries up by id. # --------------------------------------------------------------------------- -def _envelope(elements, relationships, title="Test BPMN"): +def _envelope(nodes_by_id, edges_by_id, title="Test BPMN"): return { "title": title, "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "BPMNDiagram", "size": {"width": 1400, "height": 700}, - "elements": elements, - "relationships": relationships, + "nodes": list(nodes_by_id.values()), + "edges": list(edges_by_id.values()), "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, }, } -def _node(elem_id, type_, name, owner=None, **extra): - base = { - "id": elem_id, - "name": name, +def _node(node_id, type_, name, parent=None, **data): + node = { + "id": node_id, "type": type_, - "owner": owner, - "bounds": {"x": 100, "y": 100, "width": 110, "height": 60}, + "position": {"x": 100, "y": 100}, + "width": 110, + "height": 60, + "measured": {"width": 110, "height": 60}, + "data": {"name": name, **data}, } - base.update(extra) - return base + if parent is not None: + node["parentId"] = parent + return node -def _flow(rel_id, source_id, target_id, flow_type="sequence", name="", **extra): - base = { - "id": rel_id, - "name": name, - "type": "BPMNFlow", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 100, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], - "source": {"element": source_id, "direction": "Right", - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}}, - "target": {"element": target_id, "direction": "Left", - "bounds": {"x": 100, "y": 0, "width": 0, "height": 0}}, - "isManuallyLayouted": False, - "flowType": flow_type, - "isDefault": False, +_EDGE_TYPE_FOR_FLOW = { + "sequence": "BPMNSequenceFlow", + "message": "BPMNMessageFlow", + "association": "BPMNAssociationFlow", + "data association": "BPMNDataAssociationFlow", +} + + +def _flow(edge_id, source_id, target_id, flow_type="sequence", name="", **data): + """A v4 BPMN edge with the data fields the editor's BPMN edge serialises.""" + return { + "id": edge_id, + "source": source_id, + "target": target_id, + "type": _EDGE_TYPE_FOR_FLOW[flow_type], + "sourceHandle": "right", + "targetHandle": "left", + "data": { + "name": name, + "label": name, + "points": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], + "isManuallyLayouted": False, + **data, + }, } - base.update(extra) - return base + + +def _node_data(out, node_type=None): + """``data`` of every emitted node (of ``node_type`` when given), in emission order.""" + return [n["data"] for n in out["nodes"] if node_type is None or n["type"] == node_type] + + +def _node_data_by_id(out): + return {n["id"]: n["data"] for n in out["nodes"]} def _process_with_node(node): @@ -105,7 +126,7 @@ def test_I1_import_agentic_task(): """I-1: BPMNTask with isAgentic=true imports as AgenticTask.""" elements = { "t1": _node( - "t1", "BPMNTask", "Review", taskType="user", marker="none", + "t1", "bpmnTask", "Review", taskType="user", marker="none", isAgentic=True, reflectionMode="cross", trustScore=85, ), } @@ -121,7 +142,7 @@ def test_I2_import_non_agentic_task_discards_seaa_fields(): """I-2: isAgentic=false with SEAA fields set in JSON imports as base Task.""" elements = { "t1": _node( - "t1", "BPMNTask", "Plain", taskType="default", marker="none", + "t1", "bpmnTask", "Plain", taskType="default", marker="none", isAgentic=False, reflectionMode="self", trustScore=99, ), } @@ -135,7 +156,7 @@ def test_I3_import_agentic_task_clamps_trust_score_high(): """I-3: trustScore=150 clamps to 100 on import (WME-tolerant bridge).""" elements = { "t1": _node( - "t1", "BPMNTask", "Review", taskType="default", marker="none", + "t1", "bpmnTask", "Review", taskType="default", marker="none", isAgentic=True, reflectionMode="none", trustScore=150, ), } @@ -148,7 +169,7 @@ def test_I3b_import_agentic_task_clamps_trust_score_negative(): """trustScore=-5 clamps to 0 on import.""" elements = { "t1": _node( - "t1", "BPMNTask", "Review", taskType="default", marker="none", + "t1", "bpmnTask", "Review", taskType="default", marker="none", isAgentic=True, reflectionMode="none", trustScore=-5, ), } @@ -161,7 +182,7 @@ def test_I4_import_agentic_task_unknown_reflection_raises(): """I-4: Unknown reflectionMode raises ConversionError.""" elements = { "t1": _node( - "t1", "BPMNTask", "Review", taskType="default", marker="none", + "t1", "bpmnTask", "Review", taskType="default", marker="none", isAgentic=True, reflectionMode="bogus", trustScore=0, ), } @@ -174,7 +195,7 @@ def test_I5_import_agentic_task_collaboration_mode_silently_ignored(): task still imports as AgenticTask, no error raised.""" elements = { "t1": _node( - "t1", "BPMNTask", "Review", taskType="default", marker="none", + "t1", "bpmnTask", "Review", taskType="default", marker="none", isAgentic=True, reflectionMode="cross", trustScore=50, collaborationMode="competition", ), @@ -190,7 +211,7 @@ def test_I6_import_agentic_gateway_diverging(): """I-6: Diverging gateway imports correctly; collaborationMode+mergingStrategy silently ignored.""" elements = { "g1": _node( - "g1", "BPMNGateway", "Fork", gatewayType="parallel", + "g1", "bpmnGateway", "Fork", gatewayType="parallel", isAgentic=True, gatewayRole="diverging", collaborationMode="voting", mergingStrategy="majority", trustScore=85, ), @@ -206,7 +227,7 @@ def test_I7_import_agentic_gateway_merging(): """I-7: Full agentic-merging gateway; mergingStrategy silently ignored.""" elements = { "g1": _node( - "g1", "BPMNGateway", "Vote", gatewayType="parallel", + "g1", "bpmnGateway", "Vote", gatewayType="parallel", isAgentic=True, gatewayRole="merging", collaborationMode="voting", mergingStrategy="absolute-majority", trustScore=70, ), @@ -221,7 +242,7 @@ def test_I8_import_agentic_gateway_rejects_exclusive(): """I-8: isAgentic=true on gatewayType=exclusive raises ConversionError (paper §4.3).""" elements = { "g1": _node( - "g1", "BPMNGateway", "X", gatewayType="exclusive", + "g1", "bpmnGateway", "X", gatewayType="exclusive", isAgentic=True, gatewayRole="diverging", trustScore=0, ), } @@ -233,7 +254,7 @@ def test_I9_import_agentic_gateway_unknown_collaboration_mode_silently_ignored() """I-9: Unknown collaborationMode is silently ignored.""" elements = { "g1": _node( - "g1", "BPMNGateway", "Vote", gatewayType="parallel", + "g1", "bpmnGateway", "Vote", gatewayType="parallel", isAgentic=True, gatewayRole="merging", collaborationMode="bogus", mergingStrategy="majority", trustScore=0, ), @@ -249,7 +270,7 @@ def test_I10_import_agentic_gateway_illegal_strategy_silently_ignored(): """I-10: An illegal mergingStrategy is silently ignored.""" elements = { "g1": _node( - "g1", "BPMNGateway", "Vote", gatewayType="parallel", + "g1", "bpmnGateway", "Vote", gatewayType="parallel", isAgentic=True, gatewayRole="merging", collaborationMode="voting", mergingStrategy="fastest", trustScore=0, ), @@ -263,9 +284,9 @@ def test_I10_import_agentic_gateway_illegal_strategy_silently_ignored(): def test_I11_import_agentic_lane(): """I-11: BPMNSwimlane with isAgentic=true imports as AgenticLane.""" elements = { - "p1": _node("p1", "BPMNPool", "Pool"), + "p1": _node("p1", "bpmnPool", "Pool"), "l1": _node( - "l1", "BPMNSwimlane", "Reviewer", owner="p1", + "l1", "bpmnSwimlane", "Reviewer", parent="p1", isAgentic=True, role="supervision", trustScore=85, ), } @@ -280,9 +301,9 @@ def test_I11_import_agentic_lane(): def test_I12_import_non_agentic_lane(): """I-12: isAgentic=false on swimlane imports as base Lane.""" elements = { - "p1": _node("p1", "BPMNPool", "Pool"), + "p1": _node("p1", "bpmnPool", "Pool"), "l1": _node( - "l1", "BPMNSwimlane", "Reviewer", owner="p1", + "l1", "bpmnSwimlane", "Reviewer", parent="p1", isAgentic=False, role="worker", trustScore=0, ), } @@ -294,14 +315,14 @@ def test_I12_import_non_agentic_lane(): def test_I13_import_message_flow_agentic_downgraded_to_base(): - """I-13: BPMNFlow with isAgentic=true is silently downgraded to base MessageFlow + """I-13: A message flow with isAgentic=true is silently downgraded to base MessageFlow (AgenticMessageFlow was removed).""" elements = { - "p1": _node("p1", "BPMNPool", "P1"), - "p2": _node("p2", "BPMNPool", "P2"), - "t1": _node("t1", "BPMNTask", "T1", owner="p1", + "p1": _node("p1", "bpmnPool", "P1"), + "p2": _node("p2", "bpmnPool", "P2"), + "t1": _node("t1", "bpmnTask", "T1", parent="p1", taskType="default", marker="none"), - "t2": _node("t2", "BPMNTask", "T2", owner="p2", + "t2": _node("t2", "bpmnTask", "T2", parent="p2", taskType="default", marker="none"), } rels = { @@ -316,17 +337,18 @@ def test_I13_import_message_flow_agentic_downgraded_to_base(): def test_I15_roundtrip_pool_to_pool_message_flow(): - """R-R1: pool-to-pool message flow round-trips JSON -> BUML -> JSON (flowType=message).""" + """R-R1: pool-to-pool message flow round-trips JSON -> BUML -> JSON (BPMNMessageFlow).""" elements = { - "p1": _node("p1", "BPMNPool", "P1"), - "p2": _node("p2", "BPMNPool", "P2"), + "p1": _node("p1", "bpmnPool", "P1"), + "p2": _node("p2", "bpmnPool", "P2"), } rels = { "f1": _flow("f1", "p1", "p2", flow_type="message", isAgentic=False), } out = bpmn_object_to_json(process_bpmn_diagram(_envelope(elements, rels))) - [rel] = out["relationships"].values() - assert rel["flowType"] == "message" + [edge] = out["edges"] + assert edge["type"] == "BPMNMessageFlow" + assert (edge["source"], edge["target"]) == ("p1", "p2") # =========================================================================== @@ -338,7 +360,7 @@ def test_E1_export_agentic_task(): task = AgenticTask(name="Review", task_type=TaskType.USER, reflection_mode=ReflectionMode.CROSS, trust_score=85) out = _process_with_node(task) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert entry["isAgentic"] is True assert entry["reflectionMode"] == "cross" assert entry["trustScore"] == 85 @@ -351,7 +373,7 @@ def test_E2_export_non_agentic_task_emits_wme_defaults(): """E-2: Base Task exports with isAgentic=false + WME-default SEAA fields.""" task = Task(name="Plain", task_type=TaskType.DEFAULT) out = _process_with_node(task) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert entry["isAgentic"] is False assert entry["reflectionMode"] == "none" assert entry["trustScore"] == 0 @@ -367,7 +389,7 @@ def test_E3_export_agentic_gateway_merging(): trust_score=75, ) out = _process_with_node(gw) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert entry["isAgentic"] is True assert entry["gatewayRole"] == "merging" assert entry["trustScore"] == 75 @@ -384,7 +406,7 @@ def test_E4_export_agentic_gateway_diverging(): trust_score=85, ) out = _process_with_node(gw) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert entry["isAgentic"] is True assert entry["gatewayRole"] == "diverging" assert entry["trustScore"] == 85 @@ -397,7 +419,7 @@ def test_E5_export_non_agentic_gateway_emits_wme_defaults(): """E-5: Base Gateway exports with isAgentic=false + WME defaults.""" gw = Gateway(name="Plain", gateway_type=GatewayType.EXCLUSIVE) out = _process_with_node(gw) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert entry["isAgentic"] is False assert entry["gatewayRole"] == "diverging" assert entry["trustScore"] == 0 @@ -420,7 +442,7 @@ def _agentic_merging_gateway_elements(extra): tolerance (they are silently ignored on import). """ return { - "g1": _node("g1", "BPMNGateway", "Vote", gatewayType="parallel", + "g1": _node("g1", "bpmnGateway", "Vote", gatewayType="parallel", isAgentic=True, gatewayRole="merging", collaborationMode="role", mergingStrategy="leader-driven", trustScore=75, **extra), @@ -459,7 +481,7 @@ def test_Rb_c4_export_agentic_gateway_with_governance_emits_field(): gateway_role=GatewayRole.MERGING, governance_dsl=_GOV_DSL) out = _process_with_node(gw) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert entry["governanceDsl"] == _GOV_DSL @@ -468,14 +490,14 @@ def test_Rb_c5_export_agentic_gateway_without_governance_omits_field(): gw = AgenticGateway(name="Vote", gateway_type=GatewayType.PARALLEL, gateway_role=GatewayRole.MERGING) out = _process_with_node(gw) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert "governanceDsl" not in entry def test_Rb_c6_export_non_agentic_gateway_no_governance(): """a base Gateway never carries governanceDsl.""" out = _process_with_node(Gateway(name="Plain", gateway_type=GatewayType.EXCLUSIVE)) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert "governanceDsl" not in entry @@ -486,7 +508,7 @@ def test_Rb_c7_roundtrip_agentic_gateway_governance_preserved(): _envelope(_agentic_merging_gateway_elements({"governanceDsl": _GOV_DSL}), {}) ) ) - gw_entry = next(e for e in out["elements"].values() if e["type"] == "BPMNGateway") + gw_entry = _node_data(out, "bpmnGateway")[0] assert gw_entry["governanceDsl"] == _GOV_DSL @@ -505,8 +527,7 @@ def test_E6_export_agentic_lane(): """E-6: AgenticLane exports with isAgentic=true and SEAA fields.""" out = _wrap_lane(AgenticLane(name="Reviewer", role=AgentRole.SUPERVISION, trust_score=90)) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + lane_entry = _node_data(out, "bpmnSwimlane")[0] assert lane_entry["isAgentic"] is True assert lane_entry["role"] == "supervision" assert lane_entry["trustScore"] == 90 @@ -515,15 +536,14 @@ def test_E6_export_agentic_lane(): def test_E7_export_non_agentic_lane(): """E-7: Base Lane exports with isAgentic=false + WME defaults.""" out = _wrap_lane(Lane(name="Reviewer")) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + lane_entry = _node_data(out, "bpmnSwimlane")[0] assert lane_entry["isAgentic"] is False assert lane_entry["role"] == "solution" assert lane_entry["trustScore"] == 0 def test_E8_export_message_flow_carries_no_agentic_fields(): - """E-8: A flow exports only the fields the editor's BPMNFlow serialises.""" + """E-8: A flow exports only the fields the editor's BPMN edge serialises.""" t1 = Task(name="T1") t2 = Task(name="T2") p1 = Process(name="P1", flow_nodes={t1}) @@ -537,11 +557,11 @@ def test_E8_export_message_flow_carries_no_agentic_fields(): message_flows={mf}), ) out = bpmn_object_to_json(model) - [rel] = out["relationships"].values() - assert "isAgentic" not in rel - assert "trustScore" not in rel - assert "collaborationMode" not in rel - assert "mergingStrategy" not in rel + [edge] = out["edges"] + assert edge["type"] == "BPMNMessageFlow" + for key in ("isAgentic", "trustScore", "collaborationMode", "mergingStrategy"): + assert key not in edge + assert key not in edge["data"] # =========================================================================== @@ -552,13 +572,13 @@ def test_R1_roundtrip_agentic_task(): """R-1: Agentic task JSON -> BUML -> JSON preserves SEAA fields.""" elements = { "t1": _node( - "t1", "BPMNTask", "Review", taskType="user", marker="none", + "t1", "bpmnTask", "Review", taskType="user", marker="none", isAgentic=True, reflectionMode="cross", trustScore=85, ), } model = process_bpmn_diagram(_envelope(elements, {})) out = bpmn_object_to_json(model) - [entry] = (e for e in out["elements"].values() if e["type"] == "BPMNTask") + [entry] = _node_data(out, "bpmnTask") assert entry["isAgentic"] is True assert entry["reflectionMode"] == "cross" assert entry["trustScore"] == 85 @@ -569,7 +589,7 @@ def test_R2_roundtrip_agentic_gateway_merging(): """R-2: Full agentic merging gateway round-trips lossless.""" elements = { "g1": _node( - "g1", "BPMNGateway", "Vote", gatewayType="inclusive", + "g1", "bpmnGateway", "Vote", gatewayType="inclusive", isAgentic=True, gatewayRole="merging", collaborationMode="competition", mergingStrategy="most-complete", trustScore=60, @@ -577,7 +597,7 @@ def test_R2_roundtrip_agentic_gateway_merging(): } model = process_bpmn_diagram(_envelope(elements, {})) out = bpmn_object_to_json(model) - [entry] = (e for e in out["elements"].values() if e["type"] == "BPMNGateway") + [entry] = _node_data(out, "bpmnGateway") assert entry["isAgentic"] is True assert entry["gatewayType"] == "inclusive" assert entry["gatewayRole"] == "merging" @@ -591,14 +611,14 @@ def test_R3_roundtrip_agentic_gateway_diverging(): """R-3: Diverging gateway round-trips correctly.""" elements = { "g1": _node( - "g1", "BPMNGateway", "Fork", gatewayType="parallel", + "g1", "bpmnGateway", "Fork", gatewayType="parallel", isAgentic=True, gatewayRole="diverging", collaborationMode="role", mergingStrategy="majority", trustScore=50, ), } model = process_bpmn_diagram(_envelope(elements, {})) out = bpmn_object_to_json(model) - [entry] = (e for e in out["elements"].values() if e["type"] == "BPMNGateway") + [entry] = _node_data(out, "bpmnGateway") assert entry["gatewayRole"] == "diverging" assert entry["trustScore"] == 50 @@ -606,16 +626,15 @@ def test_R3_roundtrip_agentic_gateway_diverging(): def test_R4_roundtrip_agentic_lane(): """R-4: Agentic lane round-trips lossless (canonical value).""" elements = { - "p1": _node("p1", "BPMNPool", "Pool"), + "p1": _node("p1", "bpmnPool", "Pool"), "l1": _node( - "l1", "BPMNSwimlane", "Reviewer", owner="p1", + "l1", "bpmnSwimlane", "Reviewer", parent="p1", isAgentic=True, role="supervision", trustScore=95, ), } model = process_bpmn_diagram(_envelope(elements, {})) out = bpmn_object_to_json(model) - [lane_entry] = (e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + [lane_entry] = _node_data(out, "bpmnSwimlane") assert lane_entry["isAgentic"] is True assert lane_entry["role"] == "supervision" assert lane_entry["trustScore"] == 95 @@ -625,21 +644,21 @@ def test_R5_roundtrip_mixed_diagram(): """R-5: Mixed agentic + non-agentic elements round-trip correctly.""" elements = { "t1": _node( - "t1", "BPMNTask", "Plain", taskType="default", marker="none", + "t1", "bpmnTask", "Plain", taskType="default", marker="none", isAgentic=False, ), "t2": _node( - "t2", "BPMNTask", "Agent", taskType="user", marker="none", + "t2", "bpmnTask", "Agent", taskType="user", marker="none", isAgentic=True, reflectionMode="self", trustScore=50, ), "g1": _node( - "g1", "BPMNGateway", "PlainGw", gatewayType="exclusive", + "g1", "bpmnGateway", "PlainGw", gatewayType="exclusive", isAgentic=False, ), } model = process_bpmn_diagram(_envelope(elements, {})) out = bpmn_object_to_json(model) - by_name = {e["name"]: e for e in out["elements"].values()} + by_name = {d["name"]: d for d in _node_data(out)} assert by_name["Plain"]["isAgentic"] is False assert by_name["Agent"]["isAgentic"] is True assert by_name["Agent"]["reflectionMode"] == "self" @@ -657,8 +676,8 @@ def test_R5_roundtrip_mixed_diagram(): def _lane_elements(extra): """Pool + one agentic swimlane carrying the given extra fields.""" return { - "p1": _node("p1", "BPMNPool", "Pool"), - "l1": _node("l1", "BPMNSwimlane", "AgentReviewer", owner="p1", + "p1": _node("p1", "bpmnPool", "Pool"), + "l1": _node("l1", "bpmnSwimlane", "AgentReviewer", parent="p1", isAgentic=True, role="supervision", trustScore=90, **extra), } @@ -692,8 +711,7 @@ def test_S1_c4_export_agentic_lane_with_ref_emits_field(): """an AgenticLane with a ref emits agentDiagramRef in the JSON entry.""" out = _wrap_lane(AgenticLane(name="AgentReviewer", role=AgentRole.SUPERVISION, trust_score=90, agent_diagram_ref=_REF)) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + lane_entry = _node_data(out, "bpmnSwimlane")[0] assert lane_entry["agentDiagramRef"] == _REF @@ -701,30 +719,26 @@ def test_S1_c5_export_agentic_lane_without_ref_omits_field(): """an AgenticLane with no ref omits agentDiagramRef entirely.""" out = _wrap_lane(AgenticLane(name="AgentReviewer", role=AgentRole.SUPERVISION, trust_score=90)) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + lane_entry = _node_data(out, "bpmnSwimlane")[0] assert "agentDiagramRef" not in lane_entry def test_S1_c6_export_non_agentic_lane_no_ref(): """a base Lane never carries agentDiagramRef.""" out = _wrap_lane(Lane(name="Plain")) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + lane_entry = _node_data(out, "bpmnSwimlane")[0] assert "agentDiagramRef" not in lane_entry def test_S1_c7_roundtrip_agentic_lane_with_ref(): """JSON → BUML → JSON preserves agentDiagramRef; task does NOT pick it up.""" elements = _lane_elements({"agentDiagramRef": _REF}) - elements["t1"] = _node("t1", "BPMNTask", "Review", owner="l1", + elements["t1"] = _node("t1", "bpmnTask", "Review", parent="l1", taskType="user", marker="none", isAgentic=True, reflectionMode="cross", trustScore=80) out = bpmn_object_to_json(process_bpmn_diagram(_envelope(elements, {}))) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") - task_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNTask") + lane_entry = _node_data(out, "bpmnSwimlane")[0] + task_entry = _node_data(out, "bpmnTask")[0] assert lane_entry["agentDiagramRef"] == _REF assert "agentDiagramRef" not in task_entry @@ -740,8 +754,7 @@ def test_3c_roundtrip_agentic_lane_multiplicity(): [lane] = participant.process.lanes assert lane.swarm_size == 4 out = bpmn_object_to_json(model) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + lane_entry = _node_data(out, "bpmnSwimlane")[0] assert lane_entry["multiplicity"] == 4 @@ -762,10 +775,9 @@ def test_3c_import_agentic_lane_zero_multiplicity_clamps_to_one(): def test_3c_export_non_agentic_lane_carries_default_multiplicity(): - """a base Lane emits multiplicity=1 from _WME_LANE_DEFAULTS.""" + """a base Lane emits multiplicity=1 from _LANE_AGENTIC_DEFAULTS.""" out = _wrap_lane(Lane(name="Plain")) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + lane_entry = _node_data(out, "bpmnSwimlane")[0] assert lane_entry["multiplicity"] == 1 @@ -784,8 +796,8 @@ def test_3c_export_non_agentic_lane_carries_default_multiplicity(): def test_role_canonical_values_import(role_str, expected): """All four canonical role strings import to the correct AgentRole member.""" elements = { - "p1": _node("p1", "BPMNPool", "Pool"), - "l1": _node("l1", "BPMNSwimlane", "L", owner="p1", + "p1": _node("p1", "bpmnPool", "Pool"), + "l1": _node("l1", "bpmnSwimlane", "L", parent="p1", isAgentic=True, role=role_str, trustScore=0), } model = process_bpmn_diagram(_envelope(elements, {})) @@ -802,8 +814,7 @@ def test_role_canonical_values_import(role_str, expected): def test_role_canonical_values_export(role_str, expected): """All four canonical AgentRole members export to the correct string.""" out = _wrap_lane(AgenticLane(name="L", role=expected, trust_score=0)) - lane_entry = next(e for e in out["elements"].values() - if e["type"] == "BPMNSwimlane") + lane_entry = _node_data(out, "bpmnSwimlane")[0] assert lane_entry["role"] == role_str @@ -814,8 +825,8 @@ def test_role_canonical_values_export(role_str, expected): def test_role_legacy_alias_import(legacy, canonical): """Legacy role strings (worker/manager) are silently promoted to canonical values.""" elements = { - "p1": _node("p1", "BPMNPool", "Pool"), - "l1": _node("l1", "BPMNSwimlane", "L", owner="p1", + "p1": _node("p1", "bpmnPool", "Pool"), + "l1": _node("l1", "bpmnSwimlane", "L", parent="p1", isAgentic=True, role=legacy, trustScore=0), } model = process_bpmn_diagram(_envelope(elements, {})) @@ -827,8 +838,8 @@ def test_role_invalid_raises_conversion_error(): """An unrecognised role string raises ConversionError on import.""" from besser.utilities.web_modeling_editor.backend.services.exceptions import ConversionError elements = { - "p1": _node("p1", "BPMNPool", "Pool"), - "l1": _node("l1", "BPMNSwimlane", "L", owner="p1", + "p1": _node("p1", "bpmnPool", "Pool"), + "l1": _node("l1", "bpmnSwimlane", "L", parent="p1", isAgentic=True, role="coder", trustScore=0), } with pytest.raises(ConversionError, match="Unknown role 'coder'"): @@ -845,7 +856,7 @@ def _agentic_task_elements(extra): Legacy collaborationMode field included to verify tolerance (silently ignored). """ return { - "t1": _node("t1", "BPMNTask", "Review", taskType="user", marker="none", + "t1": _node("t1", "bpmnTask", "Review", taskType="user", marker="none", isAgentic=True, reflectionMode="cross", trustScore=80, collaborationMode="voting", **extra), } @@ -877,21 +888,21 @@ def test_Ra_c4_export_agentic_task_with_ref_emits_field(): """an AgenticTask with a ref emits agentDiagramRef in the JSON entry.""" out = _process_with_node(AgenticTask(name="Review", task_type=TaskType.USER, agent_diagram_ref=_REF)) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert entry["agentDiagramRef"] == _REF def test_Ra_c5_export_agentic_task_without_ref_omits_field(): """an AgenticTask with no ref omits agentDiagramRef entirely.""" out = _process_with_node(AgenticTask(name="Review", task_type=TaskType.USER)) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert "agentDiagramRef" not in entry def test_Ra_c6_export_non_agentic_task_no_ref(): """a base Task never carries agentDiagramRef.""" out = _process_with_node(Task(name="Plain", task_type=TaskType.DEFAULT)) - [entry] = out["elements"].values() + [entry] = _node_data(out) assert "agentDiagramRef" not in entry @@ -900,7 +911,7 @@ def test_Ra_c7_roundtrip_agentic_task_with_ref(): out = bpmn_object_to_json( process_bpmn_diagram(_envelope(_agentic_task_elements({"agentDiagramRef": _REF}), {})) ) - task_entry = next(e for e in out["elements"].values() if e["type"] == "BPMNTask") + task_entry = _node_data(out, "bpmnTask")[0] assert task_entry["agentDiagramRef"] == _REF @@ -911,7 +922,7 @@ def test_Ra_c7_roundtrip_agentic_task_with_ref(): def test_S2_collaboration_mode_silently_ignored(): """collaborationMode in the JSON is silently ignored — task imports OK.""" elements = { - "t1": _node("t1", "BPMNTask", "Review", taskType="user", marker="none", + "t1": _node("t1", "bpmnTask", "Review", taskType="user", marker="none", isAgentic=True, reflectionMode="cross", trustScore=80, collaborationMode="debate"), } @@ -930,23 +941,26 @@ def test_S2_collaboration_mode_silently_ignored(): def test_R5_agentic_process_round_trips_every_agentic_field(): """JSON -> BUML -> JSON keeps every agentic field and adds none to flows.""" elements = { - "pool": _node("pool", "BPMNPool", "Swarm"), - "lane-c": _node("lane-c", "BPMNSwimlane", "Coder", owner="pool", isAgentic=True, + "pool": _node("pool", "bpmnPool", "Swarm"), + "lane-c": _node("lane-c", "bpmnSwimlane", "Coder", parent="pool", isAgentic=True, role="solution", trustScore=60, multiplicity=2, agentDiagramRef="agent-c"), - "lane-r": _node("lane-r", "BPMNSwimlane", "Reviewer", owner="pool", isAgentic=True, + "lane-r": _node("lane-r", "bpmnSwimlane", "Reviewer", parent="pool", isAgentic=True, role="supervision", trustScore=90, multiplicity=1, agentDiagramRef="agent-r"), - "task": _node("task", "BPMNTask", "Draft", owner="lane-c", taskType="default", marker="none", + "task": _node("task", "bpmnTask", "Draft", parent="lane-c", taskType="default", marker="none", isAgentic=True, reflectionMode="cross", trustScore=70, agentDiagramRef="agent-c", reflectionReviewerLaneId="lane-r"), - "gw": _node("gw", "BPMNGateway", "Merge", owner="lane-r", gatewayType="parallel", + "gw": _node("gw", "bpmnGateway", "Merge", parent="lane-r", gatewayType="parallel", isAgentic=True, gatewayRole="merging", trustScore=50, governanceDsl="MajorityPolicy p { }"), } relationships = {"f1": _flow("f1", "task", "gw")} out = bpmn_object_to_json(process_bpmn_diagram(_envelope(elements, relationships))) + emitted_data = _node_data_by_id(out) for elem_id, original in elements.items(): - expected = {k: original[k] for k in _AGENTIC_FIELDS if k in original} - emitted = {k: out["elements"][elem_id][k] for k in _AGENTIC_FIELDS - if k in out["elements"][elem_id]} + expected = {k: original["data"][k] for k in _AGENTIC_FIELDS if k in original["data"]} + emitted = {k: emitted_data[elem_id][k] for k in _AGENTIC_FIELDS + if k in emitted_data[elem_id]} assert emitted == expected, elem_id - assert set(out["relationships"]["f1"]) == set(relationships["f1"]) + [edge] = out["edges"] + assert set(edge) == set(relationships["f1"]) + assert set(edge["data"]) == set(relationships["f1"]["data"]) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_buml_safe_loader.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_buml_safe_loader.py index c7e52e913..0c5a7da63 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_buml_safe_loader.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_buml_safe_loader.py @@ -89,15 +89,17 @@ def _rich_model() -> BPMNModel: def _elements(json_model): return sorted( - (e["type"], e["name"], e.get("taskType"), e.get("marker"), e.get("eventType"), e.get("gatewayType")) - for e in json_model["elements"].values() + (n["type"], n["data"].get("name"), n["data"].get("taskType"), n["data"].get("marker"), + n["data"].get("eventType"), n["data"].get("gatewayType")) + for n in json_model["nodes"] ) def _relationships(json_model): return sorted( - (r["type"], r["name"], r.get("flowType"), r.get("isDefault") if r.get("flowType") == "sequence" else None) - for r in json_model["relationships"].values() + (e["type"], e["data"].get("name"), + bool(e["data"].get("isDefault")) if e["type"] == "BPMNSequenceFlow" else None) + for e in json_model["edges"] ) @@ -110,7 +112,7 @@ def test_every_element_kind_round_trips_through_the_safe_loader(): direct = bpmn_object_to_json(model) assert _elements(out) == _elements(direct) assert _relationships(out) == _relationships(direct) - assert len(out["elements"]) >= 15 + assert len(out["nodes"]) >= 15 @pytest.mark.parametrize("payload", [ diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_converters.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_converters.py index a0839823c..45a21c02f 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_converters.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_bpmn_converters.py @@ -1,405 +1,471 @@ -"""Tests for the BPMN converters. +"""Tests for the v4 BPMN JSON <-> BUML converters. -Covers ``process_bpmn_diagram`` (JSON → BUML), ``bpmn_object_to_json`` (BUML → JSON), -their round-trip identity, the full WME ↔ metamodel event mapping, and error handling. +All fixtures use the v4 wire shape (flat ``{nodes, edges}`` lists, node ``type`` +in lowerCamelCase, containment via top-level ``parentId``, and one edge ``type`` +per BPMN flow kind). They are NOT ports of the v3 ``{elements, relationships}`` +fixtures. Helper idioms mirror +``tests/utilities/web_modeling_editor/backend/services/converters/test_converter_roundtrip.py``. """ +from collections import Counter + import pytest from besser.BUML.metamodel.bpmn import ( BPMNModel, - Collaboration, EndEvent, EventDefinitionType, EventDirection, - Gateway, - GatewayType, IntermediateEvent, - LoopCharacteristics, - MessageFlow, - Process, - SequenceFlow, StartEvent, - SubProcess, - Task, - TaskType, ) +from besser.utilities.buml_code_builder.bpmn_model_builder import bpmn_model_to_code from besser.utilities.web_modeling_editor.backend.services.converters.bpmn_event_mapping import ( parse_event_type, serialise_event_type, ) -from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.bpmn_diagram_converter import ( - bpmn_object_to_json, -) from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.bpmn_diagram_processor import ( process_bpmn_diagram, ) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.bpmn_diagram_converter import ( + bpmn_object_to_json, + bpmn_buml_to_json, +) from besser.utilities.web_modeling_editor.backend.services.exceptions import ConversionError # --------------------------------------------------------------------------- -# JSON envelope helpers — keep test fixtures readable +# v4 helpers (mirror test_converter_roundtrip.py) # --------------------------------------------------------------------------- -def _envelope(elements, relationships, title="Test BPMN"): - return { - "title": title, - "model": { - "version": "3.0.0", - "type": "BPMNDiagram", - "size": {"width": 1400, "height": 700}, - "elements": elements, - "relationships": relationships, - "interactive": {"elements": {}, "relationships": {}}, - "assessments": {}, - }, - } +def _model(payload): + if isinstance(payload, dict) and "nodes" in payload and "edges" in payload: + return payload + return (payload or {}).get("model") or {} -def _node(elem_id, type_, name, owner=None, **extra): - base = { - "id": elem_id, - "name": name, - "type": type_, - "owner": owner, - "bounds": {"x": 100, "y": 100, "width": 110, "height": 60}, - } - base.update(extra) - return base - - -def _flow(rel_id, source_id, target_id, flow_type="sequence", name="", **extra): - base = { - "id": rel_id, - "name": name, - "type": "BPMNFlow", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 100, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], - "source": {"element": source_id, "direction": "Right", - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}}, - "target": {"element": target_id, "direction": "Left", - "bounds": {"x": 100, "y": 0, "width": 0, "height": 0}}, - "isManuallyLayouted": False, - "flowType": flow_type, - "isDefault": False, - } - base.update(extra) - return base +def _nodes(payload): + return _model(payload).get("nodes") or [] + + +def _edges(payload): + return _model(payload).get("edges") or [] + + +def _nodes_by_type(payload, node_type): + return [n for n in _nodes(payload) if n.get("type") == node_type] + + +def _edges_by_type(payload, edge_type): + return [e for e in _edges(payload) if e.get("type") == edge_type] + + +def _data(node): + return node.get("data") or {} + + +def _node_by_id(payload, node_id): + for n in _nodes(payload): + if n.get("id") == node_id: + return n + return None + + +def _node_by_name(payload, name): + for n in _nodes(payload): + if (_data(n).get("name") or "") == name: + return n + return None + + +def _type_name_pairs(payload): + """Multiset of ``(type, data.name)`` over every node — a shape fingerprint.""" + return Counter((n.get("type"), _data(n).get("name") or "") for n in _nodes(payload)) + + +def _reprocess(emitted): + """Wrap a ``bpmn_object_to_json`` payload back into the ``{title, model}`` + envelope that ``process_bpmn_diagram`` consumes (same contract as + ``process_class_diagram``).""" + return process_bpmn_diagram({"title": emitted.get("title"), "model": emitted}) + + +def _containment_by_name(payload): + """Map each node's ``data.name`` -> its parent node's ``data.name`` (or None).""" + id_to_name = {n.get("id"): _data(n).get("name") or "" for n in _nodes(payload)} + out = {} + for n in _nodes(payload): + parent_id = n.get("parentId") + out[_data(n).get("name") or ""] = id_to_name.get(parent_id) if parent_id else None + return out # --------------------------------------------------------------------------- -# Hand-written JSON fixtures +# v4 fixtures — plain dicts, {nodes, edges} # --------------------------------------------------------------------------- -@pytest.fixture -def poolless_start_task_end_json(): - """Pool-less: StartEvent -> Task -> EndEvent.""" - elements = { - "s1": _node("s1", "BPMNStartEvent", "go", eventType="default"), - "t1": _node("t1", "BPMNTask", "Do work", taskType="user", marker="none"), - "e1": _node("e1", "BPMNEndEvent", "done", eventType="default"), - } - relationships = { - "f1": _flow("f1", "s1", "t1"), - "f2": _flow("f2", "t1", "e1"), +def _node(node_id, node_type, name, *, parent_id=None, **data): + payload = {"name": name} + payload.update(data) + node = { + "id": node_id, + "type": node_type, + "position": {"x": 0, "y": 0}, + "width": 100, + "height": 60, + "data": payload, } - return _envelope(elements, relationships, title="Poolless") + if parent_id: + node["parentId"] = parent_id + return node -@pytest.fixture -def two_pool_collaboration_json(): - """Two pools, each with one task; one MessageFlow between them.""" - elements = { - "p1": _node("p1", "BPMNPool", "Buyer"), - "p2": _node("p2", "BPMNPool", "Seller"), - "t1": _node("t1", "BPMNTask", "Place order", owner="p1", - taskType="default", marker="none"), - "t2": _node("t2", "BPMNTask", "Ship", owner="p2", - taskType="default", marker="none"), - } - relationships = { - "m1": _flow("m1", "t1", "t2", flow_type="message", name="order"), +def _edge(edge_id, edge_type, source, target, name="", **data): + edge_data = {"name": name} + edge_data.update(data) + return { + "id": edge_id, + "type": edge_type, + "source": source, + "target": target, + "sourceHandle": "Right", + "targetHandle": "Left", + "data": edge_data, } - return _envelope(elements, relationships, title="Buyer-Seller") - - -@pytest.fixture -def gateway_with_default_json(): - """ExclusiveGateway with two outgoing sequence flows, one marked default.""" - elements = { - "s1": _node("s1", "BPMNStartEvent", "", eventType="default"), - "g1": _node("g1", "BPMNGateway", "?", gatewayType="exclusive"), - "t1": _node("t1", "BPMNTask", "A", taskType="default", marker="none"), - "t2": _node("t2", "BPMNTask", "B", taskType="default", marker="none"), - "e1": _node("e1", "BPMNEndEvent", "", eventType="default"), - "e2": _node("e2", "BPMNEndEvent", "", eventType="default"), + + +def simple_process_fixture(): + """start(default) -> task(user) -> gateway(exclusive) -> end(terminate). + No pools; everything lands in one synthetic process. The gateway->end flow + is the default flow.""" + return { + "title": "Order Handling", + "model": { + "type": "BPMN", + "nodes": [ + _node("start1", "bpmnStartEvent", "Start", eventType="default"), + _node("task1", "bpmnTask", "Review", taskType="user", marker="none"), + _node("gw1", "bpmnGateway", "Approved?", gatewayType="exclusive"), + _node("end1", "bpmnEndEvent", "Done", eventType="terminate"), + ], + "edges": [ + _edge("f1", "BPMNSequenceFlow", "start1", "task1"), + _edge("f2", "BPMNSequenceFlow", "task1", "gw1"), + _edge("f3", "BPMNSequenceFlow", "gw1", "end1", name="yes", isDefault=True), + ], + }, } - relationships = { - "f0": _flow("f0", "s1", "g1"), - "f1": _flow("f1", "g1", "t1", name="happy"), - "f2": _flow("f2", "g1", "t2", name="default", isDefault=True), - "fa": _flow("fa", "t1", "e1"), - "fb": _flow("fb", "t2", "e2"), + + +def pool_lane_fixture(): + """A pool containing one lane, which contains a Task. Exercises the + forward-compat ``bpmnSwimlane`` -> Lane mapping and lane containment.""" + return { + "title": "Sales", + "model": { + "type": "BPMNDiagram", # canonical spelling (other fixtures use the legacy "BPMN") + "nodes": [ + _node("pool1", "bpmnPool", "Customer"), + _node("lane1", "bpmnSwimlane", "Agent", parent_id="pool1"), + _node("t1", "bpmnTask", "Call", parent_id="lane1", taskType="default", marker="none"), + _node("e1", "bpmnEndEvent", "Hang up", parent_id="lane1", eventType="default"), + ], + "edges": [ + _edge("sf1", "BPMNSequenceFlow", "t1", "e1"), + ], + }, } - return _envelope(elements, relationships, title="Gateway") - - -@pytest.fixture -def subprocess_json(): - """Subprocess containing two flow nodes and one sequence flow inside it.""" - elements = { - "s1": _node("s1", "BPMNStartEvent", "", eventType="default"), - "sp": _node("sp", "BPMNSubprocess", "Sub", marker="none"), - "e1": _node("e1", "BPMNEndEvent", "", eventType="default"), - "ti": _node("ti", "BPMNTask", "inner", owner="sp", - taskType="default", marker="none"), - "ei": _node("ei", "BPMNEndEvent", "inner end", owner="sp", - eventType="default"), + + +def subprocess_fixture(): + """A top-level SubProcess with a child Task (via parentId) and an internal + sequence flow between two children.""" + return { + "title": "Nested", + "model": { + "type": "BPMN", + "nodes": [ + _node("sub1", "bpmnSubprocess", "Fulfil", marker="none"), + _node("cs", "bpmnStartEvent", "SubStart", parent_id="sub1", eventType="default"), + _node("ct", "bpmnTask", "Pack", parent_id="sub1", taskType="default", marker="none"), + ], + "edges": [ + _edge("csf", "BPMNSequenceFlow", "cs", "ct"), + ], + }, } - relationships = { - "f1": _flow("f1", "s1", "sp"), - "f2": _flow("f2", "sp", "e1"), - "fi": _flow("fi", "ti", "ei"), # inside subprocess + + +def artifact_fixture(): + """A Task, a TextAnnotation, and a BPMNAssociationFlow between them.""" + return { + "title": "Annotated", + "model": { + "type": "BPMN", + "nodes": [ + _node("task1", "bpmnTask", "Do it", taskType="default", marker="none"), + _node("note1", "bpmnAnnotation", "please hurry"), + ], + "edges": [ + _edge("a1", "BPMNAssociationFlow", "task1", "note1"), + ], + }, } - return _envelope(elements, relationships, title="Subprocess") -@pytest.fixture -def data_elements_json(): +def data_elements_fixture(): """Start -> Task -> End, with a data object read by the task (data input) and a data store written by it (data output) -- the shape of issue #627's request.""" - elements = { - "s1": _node("s1", "BPMNStartEvent", "Cell production started", eventType="default"), - "t1": _node("t1", "BPMNTask", "Stack electrodes", taskType="default", marker="none"), - "e1": _node("e1", "BPMNEndEvent", "Cell ready", eventType="default"), - "d1": _node("d1", "BPMNDataObject", "Electrode sheets"), - "ds1": _node("ds1", "BPMNDataStore", "MES"), - } - relationships = { - "f1": _flow("f1", "s1", "t1"), - "f2": _flow("f2", "t1", "e1"), - "a1": _flow("a1", "d1", "t1", flow_type="data association"), - "a2": _flow("a2", "t1", "ds1", flow_type="data association"), + return { + "title": "Data elements", + "model": { + "type": "BPMNDiagram", + "nodes": [ + _node("s1", "bpmnStartEvent", "Cell production started", eventType="default"), + _node("t1", "bpmnTask", "Stack electrodes", taskType="default", marker="none"), + _node("e1", "bpmnEndEvent", "Cell ready", eventType="default"), + _node("d1", "bpmnDataObject", "Electrode sheets"), + _node("ds1", "bpmnDataStore", "MES"), + ], + "edges": [ + _edge("f1", "BPMNSequenceFlow", "s1", "t1"), + _edge("f2", "BPMNSequenceFlow", "t1", "e1"), + _edge("a1", "BPMNDataAssociationFlow", "d1", "t1"), + _edge("a2", "BPMNDataAssociationFlow", "t1", "ds1"), + ], + }, } - return _envelope(elements, relationships, title="Data elements") # --------------------------------------------------------------------------- -# 1. process_bpmn_diagram — JSON → BUML +# TestProcessBpmnDiagram (json -> buml) # --------------------------------------------------------------------------- class TestProcessBpmnDiagram: - def test_poolless_builds_one_process_with_three_nodes(self, poolless_start_task_end_json): - model = process_bpmn_diagram(poolless_start_task_end_json) + def test_simple_process_builds_all_nodes_and_flows(self): + model = process_bpmn_diagram(simple_process_fixture()) assert isinstance(model, BPMNModel) - assert model.collaboration is None + assert model.name == "Order Handling" assert len(model.processes) == 1 process = next(iter(model.processes)) - assert len(process.flow_nodes) == 3 - assert len(process.sequence_flows) == 2 - - def test_poolless_node_classes_and_subtype_attrs(self, poolless_start_task_end_json): - model = process_bpmn_diagram(poolless_start_task_end_json) - nodes = {type(n).__name__ for n in model.all_flow_nodes()} - assert nodes == {"StartEvent", "Task", "EndEvent"} - task = next(n for n in model.all_flow_nodes() if isinstance(n, Task)) - assert task.task_type is TaskType.USER - assert task.loop_characteristics is LoopCharacteristics.NONE - - def test_poolless_layout_round_trip_data_stashed(self, poolless_start_task_end_json): - model = process_bpmn_diagram(poolless_start_task_end_json) - ids = {(n.layout or {}).get("id") for n in model.all_flow_nodes()} - assert ids == {"s1", "t1", "e1"} + names = {n.name for n in process.flow_nodes} + assert names == {"Start", "Review", "Approved?", "Done"} + assert len(process.sequence_flows) == 3 - def test_poolless_validate_succeeds(self, poolless_start_task_end_json): - model = process_bpmn_diagram(poolless_start_task_end_json) - result = model.validate(raise_exception=False) - assert result["success"] is True, result["errors"] - - def test_two_pool_builds_collaboration(self, two_pool_collaboration_json): - model = process_bpmn_diagram(two_pool_collaboration_json) - assert isinstance(model.collaboration, Collaboration) - assert len(model.collaboration.participants) == 2 - # Each pool has its own Process; collaboration has 1 message flow. - assert len(model.processes) == 2 - assert len(model.collaboration.message_flows) == 1 - msg = next(iter(model.collaboration.message_flows)) - assert isinstance(msg, MessageFlow) - assert msg.name == "order" + def test_task_type_and_gateway_type_parsed(self): + model = process_bpmn_diagram(simple_process_fixture()) + process = next(iter(model.processes)) + task = next(n for n in process.flow_nodes if n.name == "Review") + gateway = next(n for n in process.flow_nodes if n.name == "Approved?") + assert task.task_type.value == "user" + assert gateway.gateway_type.value == "exclusive" - def test_gateway_default_flow_is_marked(self, gateway_with_default_json): - model = process_bpmn_diagram(gateway_with_default_json) - gateway = next(n for n in model.all_flow_nodes() if isinstance(n, Gateway)) - assert gateway.gateway_type is GatewayType.EXCLUSIVE - defaults = [f for f in gateway.outgoing() if f.is_default] + def test_event_direction_and_definition_parsed(self): + model = process_bpmn_diagram(simple_process_fixture()) + process = next(iter(model.processes)) + start = next(n for n in process.flow_nodes if n.name == "Start") + end = next(n for n in process.flow_nodes if n.name == "Done") + assert isinstance(start, StartEvent) + assert start.direction is EventDirection.CATCH + assert start.event_definition is EventDefinitionType.NONE + assert isinstance(end, EndEvent) + assert end.direction is EventDirection.THROW + assert end.event_definition is EventDefinitionType.TERMINATE + + def test_default_sequence_flow_marked(self): + model = process_bpmn_diagram(simple_process_fixture()) + process = next(iter(model.processes)) + defaults = [f for f in process.sequence_flows if f.is_default] assert len(defaults) == 1 - assert defaults[0].name == "default" - assert gateway.default_flow is defaults[0] - - def test_subprocess_contains_inner_nodes(self, subprocess_json): - model = process_bpmn_diagram(subprocess_json) - sub = next(n for n in model.all_flow_nodes() if isinstance(n, SubProcess)) - # The subprocess holds its inner nodes; outer process holds it + start + end. - assert len(sub.flow_nodes) == 2 + assert defaults[0].name == "yes" + + def test_pool_and_lane_containment(self): + model = process_bpmn_diagram(pool_lane_fixture()) + assert model.collaboration is not None + assert len(model.collaboration.participants) == 1 + participant = next(iter(model.collaboration.participants)) + assert participant.name == "Customer" + assert participant.process is not None + assert len(participant.process.lanes) == 1 + lane = next(iter(participant.process.lanes)) + assert lane.name == "Agent" + # The Task and EndEvent are members of the lane. + lane_member_names = {n.name for n in lane.flow_nodes} + assert lane_member_names == {"Call", "Hang up"} + + def test_subprocess_containment(self): + model = process_bpmn_diagram(subprocess_fixture()) + process = next(iter(model.processes)) + subs = [n for n in process.flow_nodes if n.name == "Fulfil"] + assert len(subs) == 1 + sub = subs[0] + child_names = {n.name for n in sub.flow_nodes} + assert child_names == {"SubStart", "Pack"} assert len(sub.sequence_flows) == 1 - outer = next(iter(model.processes)) - assert sub in outer.flow_nodes - # The inner sequence flow is in the subprocess, not in the outer process. - assert all(f.source.container is sub for f in sub.sequence_flows) - def test_data_elements_and_associations(self, data_elements_json): - model = process_bpmn_diagram(data_elements_json) + def test_data_elements_and_associations(self): + model = process_bpmn_diagram(data_elements_fixture()) (process,) = model.processes assert {d.name for d in process.data_objects} == {"Electrode sheets"} assert {d.name for d in model.data_stores} == {"MES"} links = sorted((da.source.name, da.target.name) for da in process.data_associations) assert links == [("Electrode sheets", "Stack electrodes"), ("Stack electrodes", "MES")] - def test_dangling_endpoint_logs_and_skips(self, caplog): - elements = {"t1": _node("t1", "BPMNTask", "A", taskType="default", marker="none")} - relationships = { - "f1": _flow("f1", "t1", "missing"), # target doesn't exist - } - json_data = _envelope(elements, relationships) - with caplog.at_level("WARNING"): - model = process_bpmn_diagram(json_data) - assert len(next(iter(model.processes)).sequence_flows) == 0 - assert any("dangling endpoint" in rec.message for rec in caplog.records) + def test_dangling_flow_is_skipped(self): + fixture = simple_process_fixture() + fixture["model"]["edges"].append( + _edge("bad", "BPMNSequenceFlow", "start1", "does-not-exist") + ) + model = process_bpmn_diagram(fixture) + process = next(iter(model.processes)) + # The dangling flow is dropped; the 3 valid flows remain. + assert len(process.sequence_flows) == 3 - def test_illegal_is_default_logs_and_downgrades(self, caplog): - # A Task -> Task sequence flow with isDefault=True. The first task is the - # source — Activity sources CAN carry default, so use a parallel gateway - # source instead (parallel cannot carry defaults per BPMN §8.3.13). - elements = { - "g1": _node("g1", "BPMNGateway", "", gatewayType="parallel"), - "t1": _node("t1", "BPMNTask", "A", taskType="default", marker="none"), - "t2": _node("t2", "BPMNTask", "B", taskType="default", marker="none"), - } - relationships = { - "fa": _flow("fa", "g1", "t1"), - "fb": _flow("fb", "g1", "t2", isDefault=True), - } - json_data = _envelope(elements, relationships) - with caplog.at_level("WARNING"): - model = process_bpmn_diagram(json_data) - flows = next(iter(model.processes)).sequence_flows - assert all(not f.is_default for f in flows) - assert any("downgrading to is_default=False" in rec.message for rec in caplog.records) + def test_unknown_node_type_is_skipped(self): + fixture = simple_process_fixture() + fixture["model"]["nodes"].append(_node("weird", "bpmnUnicorn", "Sparkle")) + model = process_bpmn_diagram(fixture) + process = next(iter(model.processes)) + assert "Sparkle" not in {n.name for n in process.flow_nodes} + + def test_non_bpmn_edge_type_is_ignored(self): + fixture = simple_process_fixture() + fixture["model"]["edges"].append( + _edge("cl", "CommentLink", "start1", "task1") + ) + # Should not raise; the CommentLink is simply not a BPMN flow. + model = process_bpmn_diagram(fixture) + process = next(iter(model.processes)) + assert len(process.sequence_flows) == 3 # --------------------------------------------------------------------------- -# 2. bpmn_object_to_json — BUML → JSON +# TestBpmnObjectToJson (buml -> json) # --------------------------------------------------------------------------- class TestBpmnObjectToJson: - def test_envelope_keys_present(self, poolless_start_task_end_json): - model = process_bpmn_diagram(poolless_start_task_end_json) - out = bpmn_object_to_json(model) - assert out["version"] == "3.0.0" - assert out["type"] == "BPMNDiagram" - assert set(out.keys()) >= { - "version", "type", "size", "interactive", "elements", "relationships", - "assessments", - } - - def test_emits_three_nodes_two_flows(self, poolless_start_task_end_json): - model = process_bpmn_diagram(poolless_start_task_end_json) - out = bpmn_object_to_json(model) - assert len(out["elements"]) == 3 - assert len(out["relationships"]) == 2 - types = {e["type"] for e in out["elements"].values()} - assert types == {"BPMNStartEvent", "BPMNTask", "BPMNEndEvent"} - - def test_pool_owner_pointer(self, two_pool_collaboration_json): - model = process_bpmn_diagram(two_pool_collaboration_json) - out = bpmn_object_to_json(model) - pool_ids = {eid for eid, e in out["elements"].items() if e["type"] == "BPMNPool"} - # Each task's owner is one of the pools. - task_owners = {e["owner"] for e in out["elements"].values() if e["type"] == "BPMNTask"} - assert task_owners.issubset(pool_ids) - - def test_message_flow_emitted(self, two_pool_collaboration_json): - model = process_bpmn_diagram(two_pool_collaboration_json) - out = bpmn_object_to_json(model) - flow_types = {r["flowType"] for r in out["relationships"].values()} - assert flow_types == {"message"} - - def test_gateway_default_flag_round_trips(self, gateway_with_default_json): - model = process_bpmn_diagram(gateway_with_default_json) - out = bpmn_object_to_json(model) - defaults = [r for r in out["relationships"].values() - if r.get("flowType") == "sequence" and r.get("isDefault")] - assert len(defaults) == 1 - assert defaults[0]["name"] == "default" - - def test_subprocess_owner_pointer(self, subprocess_json): - model = process_bpmn_diagram(subprocess_json) - out = bpmn_object_to_json(model) - sub_id = next( - eid for eid, e in out["elements"].items() if e["type"] == "BPMNSubprocess" - ) - # The two inner nodes have the subprocess as owner. - inner = [e for e in out["elements"].values() if e["owner"] == sub_id] - assert {e["type"] for e in inner} == {"BPMNTask", "BPMNEndEvent"} - - def test_ids_are_reused_from_layout(self, poolless_start_task_end_json): - model = process_bpmn_diagram(poolless_start_task_end_json) - out = bpmn_object_to_json(model) - # Since process_ stashed the original ids in layout, the converter reuses them. - assert set(out["elements"].keys()) == {"s1", "t1", "e1"} - assert set(out["relationships"].keys()) == {"f1", "f2"} + def test_node_type_strings(self): + model = process_bpmn_diagram(simple_process_fixture()) + payload = bpmn_object_to_json(model) + assert payload["type"] == "BPMNDiagram" + assert payload["version"] == "4.0.0" + types = {n.get("type") for n in _nodes(payload)} + assert types == {"bpmnStartEvent", "bpmnTask", "bpmnGateway", "bpmnEndEvent"} + + def test_edge_type_strings(self): + model = process_bpmn_diagram(simple_process_fixture()) + payload = bpmn_object_to_json(model) + assert len(_edges_by_type(payload, "BPMNSequenceFlow")) == 3 + + def test_data_carries_task_gateway_event_fields(self): + model = process_bpmn_diagram(simple_process_fixture()) + payload = bpmn_object_to_json(model) + task = _node_by_name(payload, "Review") + gateway = _node_by_name(payload, "Approved?") + end = _node_by_name(payload, "Done") + assert _data(task)["taskType"] == "user" + assert _data(task)["marker"] == "none" + assert _data(gateway)["gatewayType"] == "exclusive" + assert _data(end)["eventType"] == "terminate" + + def test_parent_id_propagation_pool_lane(self): + model = process_bpmn_diagram(pool_lane_fixture()) + payload = bpmn_object_to_json(model) + pool = _node_by_name(payload, "Customer") + lane = _node_by_name(payload, "Agent") + task = _node_by_name(payload, "Call") + assert pool.get("parentId") is None + assert lane.get("parentId") == pool.get("id") + assert task.get("parentId") == lane.get("id") + + def test_subprocess_child_parent_id(self): + model = process_bpmn_diagram(subprocess_fixture()) + payload = bpmn_object_to_json(model) + sub = _node_by_name(payload, "Fulfil") + child = _node_by_name(payload, "Pack") + assert child.get("parentId") == sub.get("id") + + def test_default_flow_emits_is_default(self): + model = process_bpmn_diagram(simple_process_fixture()) + payload = bpmn_object_to_json(model) + default_edges = [e for e in _edges(payload) if _data(e).get("isDefault")] + assert len(default_edges) == 1 + + def test_sequence_flow_edge_data_has_both_name_and_label(self): + """Regression guard: BPMNDiagramEdge.tsx reads ``data.label`` while every + other v4 edge type reads ``data.name`` — the converter must emit both.""" + model = process_bpmn_diagram(simple_process_fixture()) + payload = bpmn_object_to_json(model) + named = next(e for e in _edges(payload) if _data(e).get("name") == "yes") + assert _data(named)["name"] == "yes" + assert _data(named)["label"] == "yes" + + def test_association_edge_type(self): + model = process_bpmn_diagram(artifact_fixture()) + payload = bpmn_object_to_json(model) + assert len(_edges_by_type(payload, "BPMNAssociationFlow")) == 1 + assert _node_by_name(payload, "please hurry")["type"] == "bpmnAnnotation" # --------------------------------------------------------------------------- -# 3. Round-trip identity (JSON → BUML → JSON) +# TestRoundTripIdentity # --------------------------------------------------------------------------- -def _signature(elements, relationships): - """Compact comparable summary of the load-bearing fields. ``isDefault`` is only - meaningful for sequence flows — the converter omits it on other flow types.""" - el_sig = sorted( - (eid, e["type"], e["name"], e.get("owner"), - e.get("taskType"), e.get("marker"), - e.get("eventType"), e.get("gatewayType")) - for eid, e in elements.items() - ) - rel_sig = sorted( - (rid, r["type"], r["name"], r.get("flowType"), - r.get("isDefault") if r.get("flowType") == "sequence" else None, - (r.get("source") or {}).get("element"), - (r.get("target") or {}).get("element")) - for rid, r in relationships.items() +class TestRoundTripIdentity: + @pytest.mark.parametrize( + "fixture_fn", + [simple_process_fixture, pool_lane_fixture, subprocess_fixture, artifact_fixture, + data_elements_fixture], ) - return el_sig, rel_sig + def test_process_emit_process_is_stable(self, fixture_fn): + json1 = bpmn_object_to_json(process_bpmn_diagram(fixture_fn())) + json2 = bpmn_object_to_json(_reprocess(json1)) + assert _type_name_pairs(json1) == _type_name_pairs(json2) + assert _containment_by_name(json1) == _containment_by_name(json2) + assert Counter(e.get("type") for e in _edges(json1)) == \ + Counter(e.get("type") for e in _edges(json2)) + + def test_ids_are_preserved_across_round_trip(self): + json1 = bpmn_object_to_json(process_bpmn_diagram(simple_process_fixture())) + json2 = bpmn_object_to_json(_reprocess(json1)) + assert {n["id"] for n in _nodes(json1)} == {n["id"] for n in _nodes(json2)} -class TestRoundTripIdentity: @pytest.mark.parametrize( - "fixture_name", - ["poolless_start_task_end_json", "two_pool_collaboration_json", - "gateway_with_default_json", "subprocess_json", "data_elements_json"], + "fixture_fn", + [simple_process_fixture, pool_lane_fixture, subprocess_fixture, artifact_fixture, + data_elements_fixture, lambda: two_pool_collaboration_fixture()], ) - def test_load_bearing_fields_preserved(self, request, fixture_name): - json_in = request.getfixturevalue(fixture_name) - model = process_bpmn_diagram(json_in) - json_out = bpmn_object_to_json(model) - - in_el, in_rel = _signature( - json_in["model"]["elements"], json_in["model"]["relationships"], - ) - out_el, out_rel = _signature(json_out["elements"], json_out["relationships"]) - assert in_el == out_el - assert in_rel == out_rel + def test_load_bearing_fields_preserved(self, fixture_fn): + json_in = fixture_fn() + json_out = bpmn_object_to_json(process_bpmn_diagram(json_in)) + assert _signature(json_in) == _signature(json_out) + + +def _signature(payload): + """The load-bearing fields of every node and edge. ``isDefault`` only means + something on a sequence flow; the converter omits it when false.""" + nodes = sorted( + (n["id"], n["type"], _data(n).get("name"), n.get("parentId"), + _data(n).get("taskType"), _data(n).get("marker"), + _data(n).get("eventType"), _data(n).get("gatewayType")) + for n in _nodes(payload) + ) + edges = sorted( + (e["id"], e["type"], (e.get("data") or {}).get("name") or "", + bool((e.get("data") or {}).get("isDefault")) if e["type"] == "BPMNSequenceFlow" else None, + e["source"], e["target"]) + for e in _edges(payload) + ) + return nodes, edges # --------------------------------------------------------------------------- -# 4. Event mapping — every row of Appendix A, both directions +# Event mapping -- every row of Appendix A, both directions # --------------------------------------------------------------------------- -# (event_class, wme_event_type, expected_direction, expected_definition) +# (event_class, wire eventType, expected_direction, expected_definition) _APPENDIX_A_ROWS = [ - # StartEvent (StartEvent, "default", EventDirection.CATCH, EventDefinitionType.NONE), (StartEvent, "message", EventDirection.CATCH, EventDefinitionType.MESSAGE), (StartEvent, "timer", EventDirection.CATCH, EventDefinitionType.TIMER), @@ -409,7 +475,6 @@ def test_load_bearing_fields_preserved(self, request, fixture_name): (StartEvent, "error", EventDirection.CATCH, EventDefinitionType.ERROR), (StartEvent, "compensation", EventDirection.CATCH, EventDefinitionType.COMPENSATION), (StartEvent, "link", EventDirection.CATCH, EventDefinitionType.LINK), - # EndEvent (EndEvent, "default", EventDirection.THROW, EventDefinitionType.NONE), (EndEvent, "message", EventDirection.THROW, EventDefinitionType.MESSAGE), (EndEvent, "escalation", EventDirection.THROW, EventDefinitionType.ESCALATION), @@ -417,7 +482,6 @@ def test_load_bearing_fields_preserved(self, request, fixture_name): (EndEvent, "compensation", EventDirection.THROW, EventDefinitionType.COMPENSATION), (EndEvent, "signal", EventDirection.THROW, EventDefinitionType.SIGNAL), (EndEvent, "terminate", EventDirection.THROW, EventDefinitionType.TERMINATE), - # IntermediateEvent (IntermediateEvent, "default", EventDirection.CATCH, EventDefinitionType.NONE), (IntermediateEvent, "message-catch", EventDirection.CATCH, EventDefinitionType.MESSAGE), (IntermediateEvent, "message-throw", EventDirection.THROW, EventDefinitionType.MESSAGE), @@ -433,62 +497,241 @@ def test_load_bearing_fields_preserved(self, request, fixture_name): ] -@pytest.mark.parametrize("event_class,event_type,direction,definition", _APPENDIX_A_ROWS) -def test_parse_event_type_table(event_class, event_type, direction, definition): - got_dir, got_def = parse_event_type(event_class, event_type) - assert got_dir is direction - assert got_def is definition +@pytest.mark.parametrize("event_cls, wire, direction, definition", _APPENDIX_A_ROWS) +def test_parse_event_type_table(event_cls, wire, direction, definition): + assert parse_event_type(event_cls, wire) == (direction, definition) -@pytest.mark.parametrize("event_class,event_type,direction,definition", _APPENDIX_A_ROWS) -def test_serialise_event_type_round_trip(event_class, event_type, direction, definition): - event = event_class(direction=direction, event_definition=definition) - assert serialise_event_type(event) == event_type +@pytest.mark.parametrize("event_cls, wire, direction, definition", _APPENDIX_A_ROWS) +def test_serialise_event_type_round_trip(event_cls, wire, direction, definition): + event = event_cls(name="e", direction=direction, event_definition=definition) + assert serialise_event_type(event) == wire # --------------------------------------------------------------------------- -# 5. Error handling +# TestErrorHandling # --------------------------------------------------------------------------- class TestErrorHandling: + def _with_node(self, node): + return {"title": "Bad", "model": {"type": "BPMN", "nodes": [node], "edges": []}} + + def test_bad_task_type_raises(self): + with pytest.raises(ConversionError): + process_bpmn_diagram(self._with_node( + _node("t", "bpmnTask", "X", taskType="bogus", marker="none") + )) + + def test_bad_gateway_type_raises(self): + with pytest.raises(ConversionError): + process_bpmn_diagram(self._with_node( + _node("g", "bpmnGateway", "X", gatewayType="bogus") + )) + + def test_bad_event_type_raises(self): + with pytest.raises(ConversionError): + process_bpmn_diagram(self._with_node( + _node("s", "bpmnStartEvent", "X", eventType="bogus") + )) + + def test_bad_loop_marker_raises(self): + with pytest.raises(ConversionError): + process_bpmn_diagram(self._with_node( + _node("t", "bpmnTask", "X", taskType="default", marker="bogus") + )) + + def test_unknown_bpmn_edge_type_raises_end_to_end(self): + # An unrecognised BPMN flow type used to be dropped silently, losing + # the flow; development raised for an unknown flowType. + fixture = simple_process_fixture() + fixture["model"]["edges"].append(_edge("bogus", "BPMNBogusFlow", "start1", "task1")) + with pytest.raises(ConversionError, match="BPMNBogusFlow"): + process_bpmn_diagram(fixture) + + def test_bad_edge_type_raises(self): + # A BPMN-flavoured but unrecognised edge ``type`` that reaches + # ``_build_flow`` raises ConversionError. (A wholly foreign type like + # ``CommentLink`` is skipped earlier by process_bpmn_diagram; this + # exercises _build_flow's guard directly.) + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.bpmn_diagram_processor import ( + _build_flow, + ) + with pytest.raises(ConversionError): + _build_flow({"type": "BPMNBogusFlow", "data": {}}, object(), object()) + + +# --------------------------------------------------------------------------- +# TestBpmnToJsonWrapper (bpmn_buml_to_json from generated .py source) +# --------------------------------------------------------------------------- + +class TestBpmnToJsonWrapper: + def test_buml_source_round_trips_to_json(self, tmp_path): + model = process_bpmn_diagram(simple_process_fixture()) + py_path = tmp_path / "bpmn_model.py" + bpmn_model_to_code(model=model, file_path=str(py_path)) + source = py_path.read_text(encoding="utf-8") + + payload = bpmn_buml_to_json(source) + assert payload["type"] == "BPMNDiagram" + types = Counter(n.get("type") for n in _nodes(payload)) + assert types["bpmnStartEvent"] == 1 + assert types["bpmnTask"] == 1 + assert types["bpmnGateway"] == 1 + assert types["bpmnEndEvent"] == 1 + assert len(_edges_by_type(payload, "BPMNSequenceFlow")) == 3 + + def test_missing_model_raises_conversion_error(self): + with pytest.raises(ConversionError): + bpmn_buml_to_json("x = 1\n") + + +# --------------------------------------------------------------------------- +# Ported from feature/smart-generator's (v3) suite — same assertions, v4 shape +# --------------------------------------------------------------------------- + +from besser.BUML.metamodel.bpmn import ( # noqa: E402 + Collaboration, + Gateway, + GatewayType, + MessageFlow, + Process, + SequenceFlow, + SubProcess, + Task, + TaskType, +) + + +def two_pool_collaboration_fixture(): + """Two pools, each with one task; one MessageFlow between them.""" + return { + "title": "Buyer-Seller", + "model": { + "type": "BPMNDiagram", + "nodes": [ + _node("p1", "bpmnPool", "Buyer"), + _node("p2", "bpmnPool", "Seller"), + _node("t1", "bpmnTask", "Place order", parent_id="p1", taskType="default", marker="none"), + _node("t2", "bpmnTask", "Ship", parent_id="p2", taskType="default", marker="none"), + ], + "edges": [ + _edge("m1", "BPMNMessageFlow", "t1", "t2", name="order"), + ], + }, + } + + +class TestPortedProcessBehaviour: + def test_layout_ids_stashed(self): + model = process_bpmn_diagram(simple_process_fixture()) + ids = {(n.layout or {}).get("id") for n in model.all_flow_nodes()} + assert ids == {"start1", "task1", "gw1", "end1"} + + def test_simple_process_validates(self): + model = process_bpmn_diagram(simple_process_fixture()) + result = model.validate(raise_exception=False) + assert result["success"] is True, result["errors"] + + def test_two_pool_builds_collaboration(self): + model = process_bpmn_diagram(two_pool_collaboration_fixture()) + assert isinstance(model.collaboration, Collaboration) + assert len(model.collaboration.participants) == 2 + assert len(model.processes) == 2 + assert len(model.collaboration.message_flows) == 1 + msg = next(iter(model.collaboration.message_flows)) + assert isinstance(msg, MessageFlow) + assert msg.name == "order" + + def test_gateway_default_flow_is_the_gateway_default(self): + model = process_bpmn_diagram(simple_process_fixture()) + gateway = next(n for n in model.all_flow_nodes() if isinstance(n, Gateway)) + assert gateway.gateway_type is GatewayType.EXCLUSIVE + defaults = [f for f in gateway.outgoing() if f.is_default] + assert len(defaults) == 1 + assert gateway.default_flow is defaults[0] + + def test_inner_sequence_flow_lives_in_the_subprocess(self): + model = process_bpmn_diagram(subprocess_fixture()) + sub = next(n for n in model.all_flow_nodes() if isinstance(n, SubProcess)) + outer = next(iter(model.processes)) + assert sub in outer.flow_nodes + assert all(f.source.container is sub for f in sub.sequence_flows) + + def test_dangling_endpoint_logs(self, caplog): + fixture = simple_process_fixture() + fixture["model"]["edges"].append(_edge("bad", "BPMNSequenceFlow", "start1", "missing")) + with caplog.at_level("WARNING"): + process_bpmn_diagram(fixture) + assert any("dangling endpoint" in rec.message for rec in caplog.records) + + def test_illegal_is_default_logs_and_downgrades(self, caplog): + # A parallel gateway cannot carry a default flow (BPMN 8.3.13). + fixture = { + "title": "Parallel", + "model": { + "type": "BPMNDiagram", + "nodes": [ + _node("g1", "bpmnGateway", "", gatewayType="parallel"), + _node("t1", "bpmnTask", "A", taskType="default", marker="none"), + _node("t2", "bpmnTask", "B", taskType="default", marker="none"), + ], + "edges": [ + _edge("fa", "BPMNSequenceFlow", "g1", "t1"), + _edge("fb", "BPMNSequenceFlow", "g1", "t2", isDefault=True), + ], + }, + } + with caplog.at_level("WARNING"): + model = process_bpmn_diagram(fixture) + flows = next(iter(model.processes)).sequence_flows + assert all(not f.is_default for f in flows) + assert any("downgrading to is_default=False" in rec.message for rec in caplog.records) + + def test_unknown_node_type_logs(self, caplog): + fixture = simple_process_fixture() + fixture["model"]["nodes"].append(_node("u1", "bpmnNonsense", "?")) + with caplog.at_level("WARNING"): + process_bpmn_diagram(fixture) + assert any("unknown type 'bpmnNonsense'" in rec.message for rec in caplog.records) + def test_missing_model_key_raises(self): with pytest.raises(ConversionError, match="missing the 'model' key"): process_bpmn_diagram({"title": "x"}) - def test_unknown_element_type_logs_skip(self, caplog): - elements = { - "u1": _node("u1", "BPMNNonsense", "?"), - "t1": _node("t1", "BPMNTask", "A", taskType="default", marker="none"), - } - json_data = _envelope(elements, {}) - with caplog.at_level("WARNING"): - model = process_bpmn_diagram(json_data) - assert {type(n).__name__ for n in model.all_flow_nodes()} == {"Task"} - assert any("unknown type 'BPMNNonsense'" in rec.message for rec in caplog.records) + def test_highlight_style_round_trips(self): + fixture = simple_process_fixture() + fixture["model"]["nodes"][1]["data"]["highlight"] = "#ff0" + payload = bpmn_object_to_json(process_bpmn_diagram(fixture)) + assert _data(_node_by_name(payload, "Review"))["highlight"] == "#ff0" - def test_unknown_task_type_raises_conversion_error(self): - elements = { - "t1": _node("t1", "BPMNTask", "A", taskType="bogus", marker="none"), - } - with pytest.raises(ConversionError, match="Unknown BPMN task type"): - process_bpmn_diagram(_envelope(elements, {})) - def test_unknown_flow_type_raises_conversion_error(self): - elements = { - "t1": _node("t1", "BPMNTask", "A", taskType="default", marker="none"), - "t2": _node("t2", "BPMNTask", "B", taskType="default", marker="none"), +class TestPortedObjectToJson: + def test_envelope_keys_present(self): + out = bpmn_object_to_json(process_bpmn_diagram(simple_process_fixture())) + assert out["version"] == "4.0.0" + assert out["type"] == "BPMNDiagram" + assert set(out.keys()) >= { + "version", "type", "title", "size", "interactive", "nodes", "edges", "assessments", } - relationships = {"f1": _flow("f1", "t1", "t2", flow_type="bogus")} - with pytest.raises(ConversionError, match="Unknown BPMN flowType"): - process_bpmn_diagram(_envelope(elements, relationships)) + def test_pool_parent_pointer(self): + out = bpmn_object_to_json(process_bpmn_diagram(two_pool_collaboration_fixture())) + pool_ids = {n["id"] for n in _nodes_by_type(out, "bpmnPool")} + task_parents = {n.get("parentId") for n in _nodes_by_type(out, "bpmnTask")} + assert task_parents.issubset(pool_ids) + + def test_message_flow_emitted(self): + out = bpmn_object_to_json(process_bpmn_diagram(two_pool_collaboration_fixture())) + assert {e["type"] for e in _edges(out)} == {"BPMNMessageFlow"} + + def test_ids_are_reused_from_layout(self): + out = bpmn_object_to_json(process_bpmn_diagram(simple_process_fixture())) + assert {n["id"] for n in _nodes(out)} == {"start1", "task1", "gw1", "end1"} + assert {e["id"] for e in _edges(out)} == {"f1", "f2", "f3"} -# --------------------------------------------------------------------------- -# 6. Direct BUML → JSON tests (no JSON input — exercises the layout fallback) -# --------------------------------------------------------------------------- def _simple_buml_model(): - """Build a minimal BPMNModel programmatically (no `layout` anywhere).""" + """A minimal BPMNModel built programmatically (no ``layout`` anywhere).""" s = StartEvent(name="start") t = Task(name="work", task_type=TaskType.SERVICE) e = EndEvent(name="end") @@ -497,80 +740,54 @@ def _simple_buml_model(): return BPMNModel(name="Programmatic", processes={p}) -def test_layout_fallback_emits_bounds_for_every_node(): - model = _simple_buml_model() - out = bpmn_object_to_json(model) - for entry in out["elements"].values(): - bounds = entry["bounds"] - assert {"x", "y", "width", "height"} <= set(bounds.keys()) - assert bounds["width"] > 0 and bounds["height"] > 0 +def test_layout_fallback_emits_geometry_for_every_node(): + out = bpmn_object_to_json(_simple_buml_model()) + assert len(_nodes(out)) == 3 + for node in _nodes(out): + assert {"x", "y"} <= set(node["position"].keys()) + assert node["width"] > 0 and node["height"] > 0 + assert len(_edges(out)) == 2 def test_layout_fallback_envelope_size_min_800x600(): - model = _simple_buml_model() - out = bpmn_object_to_json(model) + out = bpmn_object_to_json(_simple_buml_model()) assert out["size"]["width"] >= 800 assert out["size"]["height"] >= 600 -# --------------------------------------------------------------------------- -# 7. bpmn_buml_to_json wrapper (exec-based, added in 04-) -# --------------------------------------------------------------------------- - -from besser.utilities.buml_code_builder.bpmn_model_builder import bpmn_model_to_code # noqa: E402 -from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.bpmn_diagram_converter import ( # noqa: E402 - bpmn_buml_to_json, -) - - -class TestBpmnToJsonWrapper: +class TestPortedBumlWrapper: @pytest.mark.parametrize( - "fixture_name", - ["poolless_start_task_end_json", "two_pool_collaboration_json", - "gateway_with_default_json", "subprocess_json", "data_elements_json"], + "fixture_fn", + [simple_process_fixture, pool_lane_fixture, subprocess_fixture, artifact_fixture, + two_pool_collaboration_fixture, data_elements_fixture], ) - def test_full_round_trip_via_builder(self, request, fixture_name): - # JSON → BUML model → emitted .py → exec → BPMNModel → JSON. - # The result must agree with calling bpmn_object_to_json directly on the model - # for the load-bearing fields (subtype attrs, containment, flowType, isDefault). - json_in = request.getfixturevalue(fixture_name) - model = process_bpmn_diagram(json_in) - source = bpmn_model_to_code(model) - json_out = bpmn_buml_to_json(source) - + def test_full_round_trip_via_builder(self, fixture_fn): + # JSON -> BUML model -> emitted .py -> safe loader -> BPMNModel -> JSON must agree + # with bpmn_object_to_json on the model for the load-bearing fields. + model = process_bpmn_diagram(fixture_fn()) + json_out = bpmn_buml_to_json(bpmn_model_to_code(model)) direct = bpmn_object_to_json(model) - # Compare structural signatures (ids change because the layout passthrough - # only carries ids on nodes, not on flows). - in_el, _ = _signature(direct["elements"], direct["relationships"]) - out_el, _ = _signature(json_out["elements"], json_out["relationships"]) - # Element-wise: same set of (type, name, owner-style, subtype attrs). - in_el_no_id = sorted(t[1:] for t in in_el) - out_el_no_id = sorted(t[1:] for t in out_el) - assert in_el_no_id == out_el_no_id - - def test_data_elements_survive_code_round_trip(self, data_elements_json): + assert _type_name_pairs(json_out) == _type_name_pairs(direct) + assert _containment_by_name(json_out) == _containment_by_name(direct) + assert Counter(e["type"] for e in _edges(json_out)) == Counter(e["type"] for e in _edges(direct)) + + def test_data_elements_survive_code_round_trip(self): # Regression: the builder emitted model-level data stores AFTER the # processes, so a data association targeting a data store raised # NameError when the generated code was executed. - model = process_bpmn_diagram(data_elements_json) + model = process_bpmn_diagram(data_elements_fixture()) json_out = bpmn_buml_to_json(bpmn_model_to_code(model)) - - names_by_type = sorted((e["type"], e["name"]) for e in json_out["elements"].values()) - assert ("BPMNDataObject", "Electrode sheets") in names_by_type - assert ("BPMNDataStore", "MES") in names_by_type - name_of = {eid: e["name"] for eid, e in json_out["elements"].items()} + assert _type_name_pairs(json_out)[("bpmnDataObject", "Electrode sheets")] == 1 + assert _type_name_pairs(json_out)[("bpmnDataStore", "MES")] == 1 + name_of = {n["id"]: _data(n).get("name") for n in _nodes(json_out)} data_links = sorted( - (name_of[r["source"]["element"]], name_of[r["target"]["element"]]) - for r in json_out["relationships"].values() - if r["flowType"] == "data association" + (name_of[e["source"]], name_of[e["target"]]) + for e in _edges_by_type(json_out, "BPMNDataAssociationFlow") ) assert data_links == [("Electrode sheets", "Stack electrodes"), ("Stack electrodes", "MES")] def test_exec_failure_raises_conversion_error(self): - # A NameError is one of the documented failure modes the wrapper catches - # (the wrapper deliberately does NOT catch arbitrary RuntimeError so genuinely - # unexpected errors stay visible). with pytest.raises(ConversionError, match="failed to execute"): bpmn_buml_to_json("undefined_symbol\n") @@ -579,7 +796,6 @@ def test_no_bpmn_model_raises_conversion_error(self): bpmn_buml_to_json("x = 1\n") def test_finds_model_under_any_variable_name(self): - # The wrapper should find the model even if it's not the conventional name. source = ( "from besser.BUML.metamodel.bpmn import BPMNModel, Process, Task\n" "task_x = Task(name='x')\n" @@ -588,8 +804,79 @@ def test_finds_model_under_any_variable_name(self): ) out = bpmn_buml_to_json(source) assert out["type"] == "BPMNDiagram" - assert len(out["elements"]) == 1 + assert len(_nodes(out)) == 1 def test_syntax_error_raises_conversion_error(self): with pytest.raises(ConversionError, match="failed to execute"): bpmn_buml_to_json("def broken(:\n pass\n") + + +# --------------------------------------------------------------------------- +# Diagram interchange: the .bpmn export must carry the editor's geometry the +# way development's v3 converter did (regression: BPMNEdge DI was dropped and +# shapes inside a pool were placed parent-relative). +# --------------------------------------------------------------------------- + +def _positioned_pool_fixture(): + def at(node, x, y): + node["position"] = {"x": x, "y": y} + return node + + return { + "title": "Positioned", + "model": { + "type": "BPMNDiagram", + "nodes": [ + at(_node("pool1", "bpmnPool", "Customer"), 100, 50), + at(_node("lane1", "bpmnSwimlane", "Agent", parent_id="pool1"), 30, 0), + at(_node("t1", "bpmnTask", "Call", parent_id="lane1", taskType="default", marker="none"), 40, 20), + at(_node("e1", "bpmnEndEvent", "Hang up", parent_id="lane1", eventType="default"), 200, 20), + ], + "edges": [ + _edge("sf1", "BPMNSequenceFlow", "t1", "e1", + points=[{"x": 270, "y": 100}, {"x": 300, "y": 100}, {"x": 300, "y": 80}, + {"x": 330, "y": 80}]), + ], + }, + } + + +def _generated_bpmn_root(tmp_path): + import xml.etree.ElementTree as ET + from besser.generators.bpmn.bpmn_generator import BPMNGenerator + + BPMNGenerator(process_bpmn_diagram(_positioned_pool_fixture()), output_dir=str(tmp_path)).generate() + (bpmn_file,) = tmp_path.glob("*.bpmn") + return ET.parse(bpmn_file).getroot() + + +_DI = "{http://www.omg.org/spec/BPMN/20100524/DI}" +_DC = "{http://www.omg.org/spec/DD/20100524/DC}" +_DD_DI = "{http://www.omg.org/spec/DD/20100524/DI}" + + +class TestDiagramInterchange: + def test_generated_bpmn_keeps_edge_waypoints(self, tmp_path): + root = _generated_bpmn_root(tmp_path) + (edge,) = root.iter(f"{_DI}BPMNEdge") + waypoints = [(float(w.get("x")), float(w.get("y"))) for w in edge.iter(f"{_DD_DI}waypoint")] + # The user-routed absolute points start on the task and end on the + # event, so the generator keeps them instead of re-routing the edge. + assert waypoints == [(270, 100), (300, 100), (300, 80), (330, 80)] + + def test_generated_bpmn_shape_bounds_are_absolute(self, tmp_path): + root = _generated_bpmn_root(tmp_path) + bounds = {} + for shape in root.iter(f"{_DI}BPMNShape"): + b = shape.find(f"{_DC}Bounds") + bounds[shape.get("bpmnElement")] = (float(b.get("x")), float(b.get("y"))) + assert bounds["pool1"] == (100, 50) + assert bounds["lane1"] == (130, 50) + assert bounds["t1"] == (170, 70) + + def test_round_trip_keeps_relative_positions_and_points(self): + fixture = _positioned_pool_fixture() + out = bpmn_object_to_json(process_bpmn_diagram(fixture)) + expected = {n["id"]: (n["position"], n.get("parentId")) for n in _nodes(fixture)} + assert {n["id"]: (n["position"], n.get("parentId")) for n in _nodes(out)} == expected + assert _edges(out)[0]["data"]["points"] == _edges(fixture)[0]["data"]["points"] diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_buml_to_json_football.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_buml_to_json_football.py index 29faadc99..59312f903 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_buml_to_json_football.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_buml_to_json_football.py @@ -215,11 +215,8 @@ def test_inherited_attributes_keep_their_class_attribute(object, model, tmp_path object_model_to_code(object, str(code_file)) result = object_buml_to_json(code_file.read_text(), class_buml_to_json(model)) - names = object_names(result) - keeper = { - e["name"]: e for e in result["elements"].values() - if e["type"] == "ObjectAttribute" and names[e["owner"]] == "keeper" - } + [keeper_node] = [n for n in result["nodes"] if n["data"].get("name") == "keeper"] + keeper = {f"{row['name']} = {row['value']}": row for row in keeper_node["data"]["attributes"]} assert keeper["age = 30"]["attributeId"] is not None assert keeper["age = 30"]["attributeType"] == "int" assert keeper["name = Keeper"]["attributeId"] is not None diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_buml_to_json_library.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_buml_to_json_library.py index f25c2dfb2..bd47a834c 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_buml_to_json_library.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_buml_to_json_library.py @@ -125,16 +125,16 @@ def test_links_get_their_own_association_whatever_the_order(object, model, tmp_p code_file = tmp_path / "library_objects.py" object_model_to_code(object, str(code_file)) domain_json = class_buml_to_json(model) - rels = list(domain_json["relationships"].items()) - domain_json["relationships"] = dict(reversed(rels) if reverse else rels) + if reverse: + domain_json["edges"] = list(reversed(domain_json["edges"])) result = object_buml_to_json(code_file.read_text(), domain_json) names = object_names(result) - assoc_name = {rid: r.get("name") for rid, r in domain_json["relationships"].items()} + assoc_name = {edge["id"]: edge["data"].get("name") for edge in domain_json["edges"]} by_link = { - f"{names[r['source']['element']]} -{r['name']}-> {names[r['target']['element']]}": - assoc_name.get(r["associationId"]) - for r in result["relationships"].values() if r["type"] == "ObjectLink" + f"{names[e['source']]} -{e['data']['name']}-> {names[e['target']]}": + assoc_name.get(e["data"]["associationId"]) + for e in result["edges"] if e["type"] == "ObjectLink" } assert by_link["central -books-> ficciones"] == "books" assert by_link["antologia -authors-> casares"] == "books_1" diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_class_buml_to_json_safety.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_class_buml_to_json_safety.py index ae371e608..e65b58e60 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_class_buml_to_json_safety.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_class_buml_to_json_safety.py @@ -20,6 +20,15 @@ ) +def _attribute_rows(diagram_json): + """Every attribute row on every v4 ``class`` node.""" + return [ + row + for node in diagram_json["nodes"] if node.get("type") == "class" + for row in (node.get("data") or {}).get("attributes") or [] + ] + + def test_enum_literal_default_value_is_json_serialisable(): """An EnumerationLiteral default must be coerced to its name, not stored raw.""" low = EnumerationLiteral(name="LOW") @@ -32,9 +41,9 @@ def test_enum_literal_default_value_is_json_serialisable(): diagram_json = class_buml_to_json(model) default_value = next( - e["defaultValue"] - for e in diagram_json["elements"].values() - if e.get("name") == "level" and "defaultValue" in e + row["defaultValue"] + for row in _attribute_rows(diagram_json) + if row.get("name") == "level" and "defaultValue" in row ) assert default_value == "LOW" # The whole payload (as POSTed to the render service) must serialise. @@ -49,9 +58,9 @@ def test_primitive_default_value_is_preserved(): diagram_json = class_buml_to_json(model) default_value = next( - e["defaultValue"] - for e in diagram_json["elements"].values() - if e.get("name") == "name" and "defaultValue" in e + row["defaultValue"] + for row in _attribute_rows(diagram_json) + if row.get("name") == "name" and "defaultValue" in row ) assert default_value == "anon" diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_component_converters.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_component_converters.py index b952e1d5c..1fdefc545 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_component_converters.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_component_converters.py @@ -1,9 +1,9 @@ -"""Tests for the Component diagram converters. +"""Tests for the Component diagram converters (v4 ``{nodes, edges}`` wire shape). Covers: * JSON -> ``ComponentModel`` (``process_component_diagram``). * ``ComponentModel`` -> JSON (``component_object_to_json``). - * Round-trip identity for the load-bearing fields (ids, types, ownership, + * Round-trip identity for the load-bearing fields (ids, types, parents, stereotypes-after-token-resolution, agentic-edge dispatch). * Stereotype helpers: empty-stereotype guard, consumed-default tokens, typed-slot resolution, agentic dependency stereotypes. @@ -58,157 +58,131 @@ # --------------------------------------------------------------------------- -# Fixtures (mirror the editor's real Component-diagram export and a -# hand-built agentic diagram) +# v4 fixture builders # --------------------------------------------------------------------------- -@pytest.fixture -def real_component_diagram(): - """A base-Apollon Component diagram (real-export style: compact field - omission, no `stereotype` key on bare Component).""" +def _node(node_id, node_type, x, y, width, height, data, parent=None): + node = { + "id": node_id, "type": node_type, + "position": {"x": x, "y": y}, + "width": width, "height": height, + "measured": {"width": width, "height": height}, + "data": data, + } + if parent is not None: + node["parentId"] = parent + return node + + +def _edge(edge_id, edge_type, source, target, points, stereotype=None, + source_handle="right", target_handle="left"): + data = {"name": "", "label": "", "points": points, "isManuallyLayouted": False} + if stereotype is not None: + data["stereotype"] = stereotype + return { + "id": edge_id, "source": source, "target": target, "type": edge_type, + "sourceHandle": source_handle, "targetHandle": target_handle, "data": data, + } + + +def _diagram(title, nodes, edges): return { - "title": "Component Diagram", + "title": title, "model": { - "version": "3.0.0", - "type": "ComponentDiagram", - "size": {"width": 920, "height": 560}, - "elements": { - "c1": { - "id": "c1", "name": "Frontend", "type": "Component", - "owner": None, - "bounds": {"x": -440, "y": -240, "width": 160, "height": 100}, - "displayStereotype": True, - }, - "c2": { - "id": "c2", "name": "Backend", "type": "Component", - "owner": None, - "bounds": {"x": 90, "y": -260, "width": 160, "height": 100}, - "displayStereotype": True, - }, - "s1": { - "id": "s1", "name": "ServiceLayer", "type": "Subsystem", - "owner": None, - "bounds": {"x": -350, "y": -40, "width": 160, "height": 100}, - "stereotype": "subsystem", "displayStereotype": True, - }, - "i1": { - "id": "i1", "name": "Api", "type": "ComponentInterface", - "owner": None, - "bounds": {"x": 0, "y": -50, "width": 20, "height": 20}, - }, - }, - "relationships": { - "r1": { - "id": "r1", "name": "", "type": "ComponentDependency", - "owner": None, - "bounds": {"x": -280, "y": -200, "width": 370, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 370, "y": 0}], - "source": {"direction": "Right", "element": "c1"}, - "target": {"direction": "Left", "element": "c2"}, - "isManuallyLayouted": False, - }, - "r2": { - "id": "r2", "name": "", "type": "ComponentInterfaceProvided", - "owner": None, - "bounds": {"x": 15, "y": -160, "width": 155, "height": 170}, - "path": [{"x": 155, "y": 0}, {"x": 0, "y": 130}], - "source": {"direction": "Down", "element": "c2"}, - "target": {"direction": "Bottomright", "element": "i1"}, - "isManuallyLayouted": False, - }, - }, + "version": "4.0.0", "type": "ComponentDiagram", "title": title, + "nodes": nodes, "edges": edges, "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, }, } +def _nodes_by_id(payload): + return {n["id"]: n for n in payload["nodes"]} + + +def _edges_by_id(payload): + return {e["id"]: e for e in payload["edges"]} + + +def _data_of(payload, item_id): + """The ``data`` of the node or edge ``item_id`` of a v4 payload.""" + return {**_nodes_by_id(payload), **_edges_by_id(payload)}[item_id]["data"] + + +# --------------------------------------------------------------------------- +# Fixtures (mirror the editor's real Component-diagram export and a +# hand-built agentic diagram) +# --------------------------------------------------------------------------- + +@pytest.fixture +def real_component_diagram(): + """A plain UML Component diagram (bare Components carry an empty stereotype).""" + return _diagram( + "Component Diagram", + [ + _node("c1", "component", -440, -240, 160, 100, + {"name": "Frontend", "stereotype": "", "isComponentHeaderShown": True}), + _node("c2", "component", 90, -260, 160, 100, + {"name": "Backend", "stereotype": "", "isComponentHeaderShown": True}), + _node("s1", "componentSubsystem", -350, -40, 160, 100, + {"name": "ServiceLayer", "stereotype": "subsystem", + "isComponentSubsystemHeaderShown": True}), + _node("i1", "componentInterface", 0, -50, 20, 20, {"name": "Api"}), + ], + [ + _edge("r1", "ComponentDependency", "c1", "c2", + [{"x": -280, "y": -200}, {"x": 90, "y": -200}]), + _edge("r2", "ComponentProvidedInterface", "c2", "i1", + [{"x": 170, "y": -160}, {"x": 15, "y": -30}], + source_handle="bottom", target_handle="right-bottom"), + ], + ) + + @pytest.fixture def agentic_component_diagram(): """Hand-built style: Subsystem holding two Components with a solution agent submitting to its supervision agent.""" - return { - "title": "Component Diagram", - "model": { - "version": "3.0.0", - "type": "ComponentDiagram", - "size": {"width": 1400, "height": 740}, - "elements": { - "elem-consensus-group": { - "id": "elem-consensus-group", - "name": "ConsensusGroup", "type": "Subsystem", - "owner": None, - "bounds": {"x": 100, "y": 100, "width": 520, "height": 280}, - "stereotype": "subsystem", "displayStereotype": True, - }, - "elem-orchestrator-agent": { - "id": "elem-orchestrator-agent", - "name": "OrchestratorAgent", "type": "Component", - "owner": "elem-consensus-group", - "bounds": {"x": 140, "y": 180, "width": 160, "height": 80}, - "stereotype": "solution", "displayStereotype": True, - }, - "elem-worker-agent": { - "id": "elem-worker-agent", - "name": "WorkerAgent", "type": "Component", - "owner": "elem-consensus-group", - "bounds": {"x": 420, "y": 180, "width": 160, "height": 80}, - "stereotype": "supervision", "displayStereotype": True, - }, - }, - "relationships": { - "rel-submits": { - "id": "rel-submits", - "name": "", "type": "ComponentDependency", - "owner": None, - "bounds": {"x": 300, "y": 220, "width": 120, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 120, "y": 0}], - "source": { - "element": "elem-orchestrator-agent", "direction": "Right", - }, - "target": { - "element": "elem-worker-agent", "direction": "Left", - }, - "isManuallyLayouted": False, - "stereotype": "submits", - }, - }, - "interactive": {"elements": {}, "relationships": {}}, - "assessments": {}, - }, - } + return _diagram( + "Component Diagram", + [ + _node("elem-consensus-group", "componentSubsystem", 100, 100, 520, 280, + {"name": "ConsensusGroup", "stereotype": "subsystem", + "isComponentSubsystemHeaderShown": True}), + _node("elem-orchestrator-agent", "component", 40, 80, 160, 80, + {"name": "OrchestratorAgent", "stereotype": "solution", + "isComponentHeaderShown": True}, + parent="elem-consensus-group"), + _node("elem-worker-agent", "component", 320, 80, 160, 80, + {"name": "WorkerAgent", "stereotype": "supervision", + "isComponentHeaderShown": True}, + parent="elem-consensus-group"), + ], + [ + _edge("rel-submits", "ComponentDependency", + "elem-orchestrator-agent", "elem-worker-agent", + [{"x": 300, "y": 220}, {"x": 420, "y": 220}], + stereotype="submits"), + ], + ) @pytest.fixture def skill_component_diagram(): """Component with `stereotype: "skill"` should promote to Skill subclass.""" - return { - "title": "Skill Diagram", - "model": { - "version": "3.0.0", - "type": "ComponentDiagram", - "size": {"width": 800, "height": 600}, - "elements": { - "c-skill": { - "id": "c-skill", "name": "WebSearch", "type": "Component", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 80}, - "stereotype": "skill external", - "displayStereotype": True, - }, - "c-tool": { - "id": "c-tool", "name": "Calculator", "type": "Component", - "owner": None, - "bounds": {"x": 200, "y": 0, "width": 160, "height": 80}, - "stereotype": "tool", - "displayStereotype": True, - }, - }, - "relationships": {}, - "interactive": {"elements": {}, "relationships": {}}, - "assessments": {}, - }, - } + return _diagram( + "Skill Diagram", + [ + _node("c-skill", "component", 0, 0, 160, 80, + {"name": "WebSearch", "stereotype": "skill external", + "isComponentHeaderShown": True}), + _node("c-tool", "component", 200, 0, 160, 80, + {"name": "Calculator", "stereotype": "tool", + "isComponentHeaderShown": True}), + ], + [], + ) # --------------------------------------------------------------------------- @@ -220,7 +194,7 @@ def test_base_apollon_round_trip(self, real_component_diagram): model = process_component_diagram(real_component_diagram) assert isinstance(model, ComponentModel) assert model.name == "Component Diagram" - # 4 elements: 3 components (Frontend, Backend, ServiceLayer-subsystem) + 1 interface + # 4 nodes: 3 components (Frontend, Backend, ServiceLayer-subsystem) + 1 interface assert len(model.components) == 3 assert len(model.interfaces) == 1 # Subsystem is in components since Subsystem extends Component @@ -237,6 +211,13 @@ def test_layout_preserved(self, real_component_diagram): assert "id" in component.layout assert "bounds" in component.layout + def test_layout_bounds_are_absolute(self, agentic_component_diagram): + """A child's parent-relative v4 position is stashed as absolute bounds.""" + model = process_component_diagram(agentic_component_diagram) + orchestrator = next(c for c in model.components if c.name == "OrchestratorAgent") + assert orchestrator.layout["parentId"] == "elem-consensus-group" + assert orchestrator.layout["bounds"] == {"x": 140, "y": 180, "width": 160, "height": 80} + def test_agentic_edge_role_and_kind(self, agentic_component_diagram): model = process_component_diagram(agentic_component_diagram) # An agentic diagram yields an AgenticComponentModel. @@ -286,10 +267,11 @@ def test_envelope_shape(self): model = ComponentModel(name="Empty") out = component_object_to_json(model) assert out["type"] == "ComponentDiagram" - assert out["version"] == "3.0.0" + assert out["version"] == "4.0.0" + assert out["title"] == "Empty" assert "size" in out - assert out["elements"] == {} - assert out["relationships"] == {} + assert out["nodes"] == [] + assert out["edges"] == [] assert out["interactive"] == {"elements": {}, "relationships": {}} assert out["assessments"] == {} @@ -301,11 +283,10 @@ def test_emits_component_with_typed_stereotype(self): ) model = AgenticComponentModel(name="m", components={component}) out = component_object_to_json(model) - # Find the emitted Component entry. - entries = [e for e in out["elements"].values() - if e["type"] == "Component"] + # Find the emitted component node. + entries = [n for n in out["nodes"] if n["type"] == "component"] assert len(entries) == 1 - stereotype = entries[0].get("stereotype", "") + stereotype = entries[0]["data"].get("stereotype", "") # "solution external" — agent_category first, locality second. assert "solution" in stereotype.split() assert "external" in stereotype.split() @@ -315,10 +296,44 @@ def test_collaboration_emits_one_dependency_with_its_stereotypes(self): b = AgenticComponent("B") edge = AgenticEdge(a, b, AgenticEdgeKind.COLLABORATES, stereotypes=["review"]) model = AgenticComponentModel("m", components={a, b}, relationships={edge}) - entry, = component_object_to_json(model)["relationships"].values() + entry, = component_object_to_json(model)["edges"] assert entry["type"] == "ComponentDependency" - assert entry["stereotype"] == "collaborates review" - assert "interfaceBinding" not in entry + assert entry["data"]["stereotype"] == "collaborates review" + assert "interfaceBinding" not in entry["data"] + + def test_model_without_layout_gets_non_overlapping_positions(self): + """A model built in Python has no editor layout: children are placed + inside their Subsystem and no two siblings overlap.""" + child_a = Component(name="A") + child_b = Component(name="B") + group = Subsystem(name="Group") + group.add_child(child_a) + group.add_child(child_b) + loose = Component(name="Loose") + model = ComponentModel(name="m", components={group, child_a, child_b, loose}) + out = component_object_to_json(model) + nodes = {n["data"]["name"]: n for n in out["nodes"]} + group_node = nodes["Group"] + + # Parents precede their children (React Flow requirement). + order = [n["data"]["name"] for n in out["nodes"]] + assert order.index("Group") < order.index("A") + assert order.index("Group") < order.index("B") + + for name in ("A", "B"): + child = nodes[name] + assert child["parentId"] == group_node["id"] + # Parent-relative position fully inside the parent. + assert child["position"]["x"] >= 0 and child["position"]["y"] >= 0 + assert child["position"]["x"] + child["width"] <= group_node["width"] + assert child["position"]["y"] + child["height"] <= group_node["height"] + + def overlaps(n1, n2): + (x1, y1), (x2, y2) = (n1["position"]["x"], n1["position"]["y"]), (n2["position"]["x"], n2["position"]["y"]) + return x1 < x2 + n2["width"] and x2 < x1 + n1["width"] and y1 < y2 + n2["height"] and y2 < y1 + n1["height"] + + assert not overlaps(nodes["A"], nodes["B"]) + assert not overlaps(group_node, nodes["Loose"]) # --------------------------------------------------------------------------- @@ -343,10 +358,10 @@ def test_explicit_binding_survives_json_and_python_round_trip(self, kind, provid ) wire = component_object_to_json(model) - interfaces = {element["name"]: element_id for element_id, element in wire["elements"].items()} - dependency, = (rel for rel in wire["relationships"].values() if rel["type"] == "ComponentDependency") - assert dependency["stereotype"] == kind.value - assert dependency["interfaceBinding"] == { + interfaces = {node["data"]["name"]: node["id"] for node in wire["nodes"]} + dependency, = (edge for edge in wire["edges"] if edge["type"] == "ComponentDependency") + assert dependency["data"]["stereotype"] == kind.value + assert dependency["data"]["interfaceBinding"] == { "required": interfaces["Required"], "provided": interfaces["Provided"], } @@ -368,7 +383,7 @@ def test_second_same_named_interface_keeps_original_binding_through_export(self) model.add_provided_interface(provider, new) wire = component_buml_to_json(component_model_to_code(model)) - assert wire["relationships"]["uses-service"]["interfaceBinding"] == {"required": "old", "provided": "old"} + assert _data_of(wire, "uses-service")["interfaceBinding"] == {"required": "old", "provided": "old"} rebuilt = process_component_diagram({"model": wire}) assert rebuilt.validate()["success"] binding, = rebuilt.agentic_edges() @@ -403,31 +418,30 @@ def test_dangling_agentic_endpoint_cannot_be_exported(self, model_type): component_model_to_code(model) def test_dangling_typed_json_dependency_reports_its_id(self, agentic_component_diagram): - rel = agentic_component_diagram["model"]["relationships"]["rel-submits"] - rel["target"]["element"] = "missing-agent" + edge = _edges_by_id(agentic_component_diagram["model"])["rel-submits"] + edge["target"] = "missing-agent" with pytest.raises(ConversionError, match="rel-submits.*missing-agent"): process_component_diagram(agentic_component_diagram) - rel["stereotype"] = "import" + edge["data"]["stereotype"] = "import" assert not process_component_diagram(agentic_component_diagram).relationships def test_missing_provision_cannot_turn_a_dependency_into_shorthand(self, real_component_diagram): wire = real_component_diagram["model"] - wire["elements"]["c1"]["stereotype"] = "solution" - wire["relationships"]["r1"]["stereotype"] = "uses" - wire["relationships"]["incomplete"] = { - "type": "ComponentInterfaceProvided", "source": {"element": "c2"}, "target": {"element": "missing"}, - } + _data_of(wire, "c1")["stereotype"] = "solution" + _data_of(wire, "r1")["stereotype"] = "uses" + incomplete = _edge("incomplete", "ComponentProvidedInterface", "c2", "missing", []) + wire["edges"].append(incomplete) with pytest.raises(ConversionError, match="incomplete.*missing"): process_component_diagram(real_component_diagram) - wire["relationships"]["incomplete"]["source"]["element"] = "s1" + incomplete["source"] = "s1" assert process_component_diagram(real_component_diagram).validate()["success"] def test_plain_dependency_preserves_free_form_stereotype(self, real_component_diagram): - rel = real_component_diagram["model"]["relationships"]["r1"] - rel["stereotype"] = "import {permission: public}" + data = _data_of(real_component_diagram["model"], "r1") + data["stereotype"] = "import {permission: public}" model = process_component_diagram(real_component_diagram) - assert component_object_to_json(model)["relationships"]["r1"]["stereotype"] == rel["stereotype"] + assert _data_of(component_object_to_json(model), "r1")["stereotype"] == data["stereotype"] def test_plain_dependency_exports_its_uses_stereotype(self): agent = AgenticComponent("Client", agent_category=AgentCategory.SOLUTION) @@ -436,19 +450,19 @@ def test_plain_dependency_exports_its_uses_stereotype(self): model = ComponentModel("m", components={agent, tool}, relationships={dependency}) wire = component_object_to_json(model) - relationship, = wire["relationships"].values() - assert relationship["stereotype"] == "«USES»" + edge, = wire["edges"] + assert edge["data"]["stereotype"] == "«USES»" rebuilt = process_component_diagram({"model": wire}) - edge, = rebuilt.agentic_edges() - assert edge.kind is AgenticEdgeKind.USES + agentic, = rebuilt.agentic_edges() + assert agentic.kind is AgenticEdgeKind.USES assert rebuilt.validate()["success"] def test_skill_round_trips_with_an_extra_role_stereotype(self, skill_component_diagram): - skill_component_diagram["model"]["elements"]["c-skill"]["stereotype"] = "skill solution" + _data_of(skill_component_diagram["model"], "c-skill")["stereotype"] = "skill solution" model = process_component_diagram(skill_component_diagram) skill, = (component for component in model.components if isinstance(component, Skill)) assert skill.stereotypes == ["solution"] - assert component_object_to_json(model)["elements"]["c-skill"]["stereotype"] == "skill solution" + assert _data_of(component_object_to_json(model), "c-skill")["stereotype"] == "skill solution" def test_json_rejects_conflicting_agent_roles(self, agentic_component_diagram): model = process_component_diagram(agentic_component_diagram) @@ -456,8 +470,7 @@ def test_json_rejects_conflicting_agent_roles(self, agentic_component_diagram): agent.stereotypes.append("none") with pytest.raises(ConversionError, match="OrchestratorAgent.*agent role"): component_object_to_json(model) - elem = agentic_component_diagram["model"]["elements"]["elem-orchestrator-agent"] - elem["stereotype"] = "none solution" + _data_of(agentic_component_diagram["model"], "elem-orchestrator-agent")["stereotype"] = "none solution" with pytest.raises(ConversionError, match="elem-orchestrator-agent.*agent role"): process_component_diagram(agentic_component_diagram) @@ -481,15 +494,13 @@ def test_ambiguous_or_retired_agentic_edge_stereotypes(self, agentic_component_d component_model_to_code(model) def test_json_rejects_an_ambiguous_agentic_edge_stereotype(self, agentic_component_diagram): - rel = agentic_component_diagram["model"]["relationships"]["rel-submits"] - rel["stereotype"] = "submits «SUPERVISES»,audited" + _data_of(agentic_component_diagram["model"], "rel-submits")["stereotype"] = "submits «SUPERVISES»,audited" with pytest.raises(ConversionError, match="rel-submits.*kind"): process_component_diagram(agentic_component_diagram) @pytest.mark.parametrize("kind", ["has", "delegates", "revises", "granted", "implements"]) def test_retired_token_has_no_agentic_semantics(self, real_component_diagram, kind): - rel = real_component_diagram["model"]["relationships"]["r1"] - rel["stereotype"] = kind + _data_of(real_component_diagram["model"], "r1")["stereotype"] = kind model = process_component_diagram(real_component_diagram) dependency, = (edge for edge in model.relationships if edge.layout["id"] == "r1") assert type(dependency) is ComponentDependency @@ -498,25 +509,24 @@ def test_retired_token_has_no_agentic_semantics(self, real_component_diagram, ki def test_legacy_has_and_revises_load_as_their_successor_kinds(self, agentic_component_diagram): # The released bug_fixing template linked agents to skills with «has» and coder to reviewer with «revises». wire = agentic_component_diagram["model"] - wire["elements"]["elem-skill"] = {"id": "elem-skill", "name": "Search", "type": "Component", "stereotype": "skill"} - wire["relationships"]["rel-submits"]["stereotype"] = "revises" - wire["relationships"]["rel-has"] = { - "id": "rel-has", "type": "ComponentDependency", "stereotype": "«has»", - "source": {"element": "elem-orchestrator-agent"}, "target": {"element": "elem-skill"}, - } + wire["nodes"].append(_node("elem-skill", "component", 700, 100, 160, 80, + {"name": "Search", "stereotype": "skill", "isComponentHeaderShown": True})) + _data_of(wire, "rel-submits")["stereotype"] = "revises" + wire["edges"].append(_edge("rel-has", "ComponentDependency", "elem-orchestrator-agent", "elem-skill", + [], stereotype="«has»")) model = process_component_diagram(agentic_component_diagram) kinds = {edge.layout["id"]: edge.kind for edge in model.agentic_edges()} assert kinds == {"rel-submits": AgenticEdgeKind.SUBMITS, "rel-has": AgenticEdgeKind.KNOWS} assert model.validate()["success"] - relationships = component_object_to_json(model)["relationships"] - assert relationships["rel-submits"]["stereotype"] == "submits" - assert relationships["rel-has"]["stereotype"] == "knows" + out = component_object_to_json(model) + assert _data_of(out, "rel-submits")["stereotype"] == "submits" + assert _data_of(out, "rel-has")["stereotype"] == "knows" def test_legacy_revises_outside_its_successor_roles_stays_plain(self, agentic_component_diagram): wire = agentic_component_diagram["model"] - wire["elements"]["elem-worker-agent"]["stereotype"] = "solution" - wire["relationships"]["rel-submits"]["stereotype"] = "revises" + _data_of(wire, "elem-worker-agent")["stereotype"] = "solution" + _data_of(wire, "rel-submits")["stereotype"] = "revises" model = process_component_diagram(agentic_component_diagram) dependency, = model.relationships @@ -533,9 +543,9 @@ def test_json_drops_a_legacy_permission_suffix_like_the_editor( ): # Stored diagrams from before the permission API still carry the suffix; the editor strips it. wire = agentic_component_diagram["model"] - wire["elements"]["elem-orchestrator-agent"]["stereotype"] = source_role - wire["elements"]["elem-worker-agent"]["stereotype"] = target_role - wire["relationships"]["rel-submits"]["stereotype"] = f"{stereotype} {{permission: repo:merge}}" + _data_of(wire, "elem-orchestrator-agent")["stereotype"] = source_role + _data_of(wire, "elem-worker-agent")["stereotype"] = target_role + _data_of(wire, "rel-submits")["stereotype"] = f"{stereotype} {{permission: repo:merge}}" model = process_component_diagram(agentic_component_diagram) edge, = model.agentic_edges() @@ -547,36 +557,33 @@ def test_json_drops_a_legacy_permission_suffix_like_the_editor( @pytest.mark.parametrize("direction", ["directed", "reciprocal"]) def test_explicit_collaboration_direction_round_trips_in_json(self, agentic_component_diagram, direction): wire = agentic_component_diagram["model"] - wire["elements"]["elem-worker-agent"]["stereotype"] = "solution" - wire["relationships"]["rel-submits"].update( - stereotype="collaborates review", collaborationDirection=direction, - ) + _data_of(wire, "elem-worker-agent")["stereotype"] = "solution" + _data_of(wire, "rel-submits").update(stereotype="collaborates review", collaborationDirection=direction) model = process_component_diagram(agentic_component_diagram) assert model.validate()["success"] - assert component_object_to_json(model)["relationships"] == wire["relationships"] + assert _edges_by_id(component_object_to_json(model)) == _edges_by_id(wire) @pytest.mark.parametrize("direction", [None, "", "DIRECTED", "bidirectional", False, []]) def test_invalid_collaboration_direction_is_rejected(self, agentic_component_diagram, direction): wire = agentic_component_diagram["model"] - wire["elements"]["elem-worker-agent"]["stereotype"] = "solution" - wire["relationships"]["rel-submits"].update( - stereotype="collaborates", collaborationDirection=direction, - ) + _data_of(wire, "elem-worker-agent")["stereotype"] = "solution" + _data_of(wire, "rel-submits").update(stereotype="collaborates", collaborationDirection=direction) with pytest.raises(ConversionError, match="rel-submits.*collaborationDirection"): process_component_diagram(agentic_component_diagram) - @pytest.mark.parametrize(("relationship_type", "stereotype"), [ + @pytest.mark.parametrize(("edge_type", "stereotype"), [ ("ComponentDependency", "submits"), ("ComponentDependency", "«use»"), - ("ComponentInterfaceProvided", "collaborates"), + ("ComponentProvidedInterface", "collaborates"), ]) def test_collaboration_direction_is_rejected_on_other_relationships( - self, agentic_component_diagram, relationship_type, stereotype, + self, agentic_component_diagram, edge_type, stereotype, ): - rel = agentic_component_diagram["model"]["relationships"]["rel-submits"] - rel.update(type=relationship_type, stereotype=stereotype, collaborationDirection="directed") + edge = _edges_by_id(agentic_component_diagram["model"])["rel-submits"] + edge["type"] = edge_type + edge["data"].update(stereotype=stereotype, collaborationDirection="directed") with pytest.raises(ConversionError, match="rel-submits.*collaborationDirection.*COLLABORATES"): process_component_diagram(agentic_component_diagram) @@ -584,12 +591,11 @@ def test_collaboration_direction_is_rejected_on_other_relationships( def test_legacy_reverse_collaboration_pair_loads_as_one_collaboration(self, agentic_component_diagram): # The pre-direction editor derived a two-way BPMN hand-off as two direction-less edges. wire = agentic_component_diagram["model"] - wire["elements"]["elem-worker-agent"]["stereotype"] = "solution" - edge = wire["relationships"]["rel-submits"] - edge["stereotype"] = "collaborates" - wire["relationships"]["rel-reverse"] = { - **edge, "id": "rel-reverse", "source": edge["target"], "target": edge["source"], - } + _data_of(wire, "elem-worker-agent")["stereotype"] = "solution" + edge = _edges_by_id(wire)["rel-submits"] + edge["data"]["stereotype"] = "collaborates" + wire["edges"].append({**edge, "id": "rel-reverse", "source": edge["target"], "target": edge["source"], + "data": dict(edge["data"])}) model = process_component_diagram(agentic_component_diagram) collaboration, = model.agentic_edges() @@ -600,12 +606,11 @@ def test_legacy_reverse_collaboration_pair_loads_as_one_collaboration(self, agen def test_directed_reverse_collaboration_pair_is_still_a_duplicate(self, agentic_component_diagram): wire = agentic_component_diagram["model"] - wire["elements"]["elem-worker-agent"]["stereotype"] = "solution" - edge = wire["relationships"]["rel-submits"] - edge.update(stereotype="collaborates", collaborationDirection="directed") - wire["relationships"]["rel-reverse"] = { - **edge, "id": "rel-reverse", "source": edge["target"], "target": edge["source"], - } + _data_of(wire, "elem-worker-agent")["stereotype"] = "solution" + edge = _edges_by_id(wire)["rel-submits"] + edge["data"].update(stereotype="collaborates", collaborationDirection="directed") + wire["edges"].append({**edge, "id": "rel-reverse", "source": edge["target"], "target": edge["source"], + "data": dict(edge["data"])}) model = process_component_diagram(agentic_component_diagram) assert len(model.agentic_edges()) == 2 @@ -618,9 +623,8 @@ def test_directed_reverse_collaboration_pair_is_still_a_duplicate(self, agentic_ ]) def test_invalid_binding_reference_is_reported(self, real_component_diagram, binding): wire = real_component_diagram["model"] - wire["elements"]["c1"]["stereotype"] = "solution" - wire["relationships"]["r1"]["stereotype"] = "uses" - wire["relationships"]["r1"]["interfaceBinding"] = binding + _data_of(wire, "c1")["stereotype"] = "solution" + _data_of(wire, "r1").update(stereotype="uses", interfaceBinding=binding) with pytest.raises(ConversionError, match="r1.*interfaceBinding"): process_component_diagram(real_component_diagram) @@ -634,68 +638,93 @@ def test_invalid_binding_reference_is_reported(self, real_component_diagram, bin ]) def test_dependency_stereotype_round_trips(self, agentic_component_diagram, stereotype, source_role, target_stereotype): wire = agentic_component_diagram["model"] - wire["elements"]["elem-orchestrator-agent"]["stereotype"] = source_role - wire["elements"]["elem-worker-agent"]["stereotype"] = target_stereotype - dependency = wire["relationships"]["rel-submits"] - dependency["stereotype"] = stereotype + _data_of(wire, "elem-orchestrator-agent")["stereotype"] = source_role + _data_of(wire, "elem-worker-agent")["stereotype"] = target_stereotype + _data_of(wire, "rel-submits")["stereotype"] = stereotype model = process_component_diagram(agentic_component_diagram) edge, = model.agentic_edges() assert edge.kind is AgenticEdgeKind(stereotype) assert model.validate()["success"] - assert component_object_to_json(model)["relationships"] == wire["relationships"] - - def _ids(self, json_dict, key): - """Return the sorted set of element ids from elements or relationships.""" - return sorted((json_dict.get(key) or {}).keys()) - + assert _edges_by_id(component_object_to_json(model)) == _edges_by_id(wire) def test_real_diagram_ids_survive(self, real_component_diagram): model = process_component_diagram(real_component_diagram) out = component_object_to_json(model) - in_elements = self._ids(real_component_diagram["model"], "elements") - out_elements = self._ids(out, "elements") - assert in_elements == out_elements - in_rels = self._ids(real_component_diagram["model"], "relationships") - out_rels = self._ids(out, "relationships") - assert in_rels == out_rels + assert sorted(_nodes_by_id(out)) == sorted(_nodes_by_id(real_component_diagram["model"])) + assert sorted(_edges_by_id(out)) == sorted(_edges_by_id(real_component_diagram["model"])) def test_real_diagram_types_survive(self, real_component_diagram): model = process_component_diagram(real_component_diagram) out = component_object_to_json(model) - for elem_id, original in ( - real_component_diagram["model"]["elements"].items() - ): - assert out["elements"][elem_id]["type"] == original["type"] - for rel_id, original in ( - real_component_diagram["model"]["relationships"].items() - ): - assert out["relationships"][rel_id]["type"] == original["type"] - - def test_real_diagram_owner_chains_survive(self, real_component_diagram): + out_nodes, out_edges = _nodes_by_id(out), _edges_by_id(out) + for node_id, original in _nodes_by_id(real_component_diagram["model"]).items(): + assert out_nodes[node_id]["type"] == original["type"] + for edge_id, original in _edges_by_id(real_component_diagram["model"]).items(): + assert out_edges[edge_id]["type"] == original["type"] + + def test_real_diagram_parent_chains_survive(self, real_component_diagram): model = process_component_diagram(real_component_diagram) - out = component_object_to_json(model) - for elem_id, original in ( - real_component_diagram["model"]["elements"].items() - ): - assert out["elements"][elem_id].get("owner") == original.get("owner") + out_nodes = _nodes_by_id(component_object_to_json(model)) + for node_id, original in _nodes_by_id(real_component_diagram["model"]).items(): + assert out_nodes[node_id].get("parentId") == original.get("parentId") def test_agentic_diagram_stereotype_resolves_and_re_emits( self, agentic_component_diagram, ): model = process_component_diagram(agentic_component_diagram) out = component_object_to_json(model) - rel = out["relationships"]["rel-submits"] + rel = _edges_by_id(out)["rel-submits"] assert rel["type"] == "ComponentDependency" - assert rel["stereotype"] == "submits" + assert rel["data"]["stereotype"] == "submits" # The OrchestratorAgent emits with `solution`. - orchestrator = out["elements"]["elem-orchestrator-agent"] - assert "solution" in orchestrator["stereotype"].split() + orchestrator = _nodes_by_id(out)["elem-orchestrator-agent"] + assert "solution" in orchestrator["data"]["stereotype"].split() def test_agentic_subsystem_children_survive(self, agentic_component_diagram): model = process_component_diagram(agentic_component_diagram) - out = component_object_to_json(model) - # The two child components must keep `owner: "elem-consensus-group"`. + out_nodes = _nodes_by_id(component_object_to_json(model)) + # The two child components keep `parentId: "elem-consensus-group"` and + # their parent-relative positions. for child_id in ("elem-orchestrator-agent", "elem-worker-agent"): - assert out["elements"][child_id]["owner"] == "elem-consensus-group" + assert out_nodes[child_id]["parentId"] == "elem-consensus-group" + assert out_nodes["elem-orchestrator-agent"]["position"] == {"x": 40, "y": 80} + + def test_editor_default_stereotypes_survive_the_buml_file(self): + """The editor writes «component» / «subsystem» on new elements; they must + come back as written, not as "" (direct and through the exported .py).""" + payload = _diagram("Defaults", [ + _node("s", "componentSubsystem", 0, 0, 400, 300, + {"name": "Core", "stereotype": "subsystem", "isComponentSubsystemHeaderShown": True}), + _node("c", "component", 40, 60, 160, 100, + {"name": "Api", "stereotype": "component", "isComponentHeaderShown": True}, parent="s"), + ], []) + model = process_component_diagram(payload) + for out in (component_object_to_json(model), component_buml_to_json(component_model_to_code(model))): + nodes = _nodes_by_id(out) + assert nodes["s"]["data"]["stereotype"] == "subsystem" + assert nodes["c"]["data"]["stereotype"] == "component" + + def test_required_interface_socket_variant_survives(self): + """A ComponentRequiredQuarterInterface edge reads as InterfaceRequired and + comes back with its drawn socket variant, also through a BUML file.""" + payload = _diagram( + "Sockets", + [ + _node("c", "component", 0, 0, 160, 100, + {"name": "Client", "stereotype": "", "isComponentHeaderShown": True}), + _node("i", "componentInterface", 300, 40, 20, 20, {"name": "Port"}), + ], + [_edge("req", "ComponentRequiredQuarterInterface", "c", "i", + [{"x": 160, "y": 50}, {"x": 300, "y": 50}])], + ) + model = process_component_diagram(payload) + (rel,) = model.relationships + assert isinstance(rel, InterfaceRequired) + + direct = _edges_by_id(component_object_to_json(model))["req"] + assert direct["type"] == "ComponentRequiredQuarterInterface" + via_file = _edges_by_id(component_buml_to_json(component_model_to_code(model)))["req"] + assert via_file["type"] == "ComponentRequiredQuarterInterface" + assert via_file["data"]["points"] == [{"x": 160, "y": 50}, {"x": 300, "y": 50}] # --------------------------------------------------------------------------- @@ -760,17 +789,16 @@ def test_tokenise_skips_empty_and_strips(self): def _legacy_component_wire() -> dict: """The JSON diagram the legacy fixtures were exported from.""" - def element(name, stereotype): - return {"id": name.lower(), "name": name, "type": "Component", "owner": None, "stereotype": stereotype, - "bounds": {"x": 0, "y": 0, "width": 100, "height": 80}} + def component(name, stereotype): + return _node(name.lower(), "component", 0, 0, 100, 80, + {"name": name, "stereotype": stereotype, "isComponentHeaderShown": True}) - def dependency(rel_id, source, target, stereotype): - return {"id": rel_id, "name": "", "type": "ComponentDependency", "owner": None, "stereotype": stereotype, - "source": {"element": source}, "target": {"element": target}} + def dependency(edge_id, source, target, stereotype): + return _edge(edge_id, "ComponentDependency", source, target, [], stereotype=stereotype) - elements = [element("Coder", "solution"), element("Tester", "solution"), element("Lead", "supervision"), - element("Search", "skill"), element("Git", "tool")] - relationships = [ + nodes = [component("Coder", "solution"), component("Tester", "solution"), component("Lead", "supervision"), + component("Search", "skill"), component("Git", "tool")] + edges = [ dependency("has", "coder", "search", "has"), dependency("revises", "coder", "lead", "revises"), dependency("revises-peer", "coder", "tester", "revises"), dependency("delegates", "lead", "coder", "delegates"), dependency("implements", "git", "search", "implements"), @@ -779,12 +807,11 @@ def dependency(rel_id, source, target, stereotype): dependency("uses", "coder", "git", "uses {permission: repo:write}"), dependency("supervises", "lead", "coder", "supervises"), ] - return {"title": "Legacy", "model": {"type": "ComponentDiagram", "elements": {e["id"]: e for e in elements}, - "relationships": {r["id"]: r for r in relationships}}} + return _diagram("Legacy", nodes, edges) def _stereotypes_by_id(diagram: dict) -> dict: - return {rel_id: rel.get("stereotype") for rel_id, rel in diagram["relationships"].items()} + return {edge["id"]: edge["data"].get("stereotype") for edge in diagram["edges"]} class TestComponentBumlToJson: @@ -794,11 +821,10 @@ def test_round_trips_via_builder(self, real_component_diagram): source = component_model_to_code(model) result = component_buml_to_json(source) assert result["type"] == "ComponentDiagram" + assert result["version"] == "4.0.0" # ids survive because component_object_to_json reuses layout["id"] # (which the builder emits in .layout = {...} round-trip). - in_ids = sorted(real_component_diagram["model"]["elements"].keys()) - out_ids = sorted(result["elements"].keys()) - assert in_ids == out_ids + assert sorted(_nodes_by_id(result)) == sorted(_nodes_by_id(real_component_diagram["model"])) def test_exec_failure_raises_conversion_error(self): with pytest.raises(ConversionError): @@ -820,8 +846,8 @@ def test_removed_kind_in_python_is_read_like_the_json_importer(self): "source=coder, target=git, kind=AgenticEdgeKind.HAS, name='to_tool'))\n" ) warnings = [] - relationships = component_buml_to_json(source, warnings)["relationships"].values() - assert {rel["name"]: rel["stereotype"] for rel in relationships} == {"to_skill": "knows", "to_tool": "has"} + edges = component_buml_to_json(source, warnings)["edges"] + assert {e["data"]["name"]: e["data"]["stereotype"] for e in edges} == {"to_skill": "knows", "to_tool": "has"} assert len(warnings) == 2 def test_legacy_file_reads_like_the_json_importer(self): @@ -851,7 +877,7 @@ def test_legacy_granted_permission_and_model_permissions_are_dropped(self): ) warnings = [] result = component_buml_to_json(source, warnings) - assert list(result["elements"]) and result["relationships"] == {} + assert result["nodes"] and result["edges"] == [] assert ["merge" in w for w in warnings] == [True, True] assert "GRANTED dependency 'Lead' -> 'merge'" in warnings[1] @@ -860,18 +886,18 @@ def test_legacy_project_imports_every_diagram(self): project = project_to_json(LEGACY_PROJECT_FILE, warnings) component, = project["diagrams"]["ComponentDiagram"] assert _stereotypes_by_id(component["model"]) == LEGACY_READ_AS - classes = project["diagrams"]["ClassDiagram"][0]["model"]["elements"].values() - assert "Book" in {element["name"] for element in classes} + classes = project["diagrams"]["ClassDiagram"][0]["model"]["nodes"] + assert "Book" in {node["data"]["name"] for node in classes} assert len(warnings) == 8 def test_a_component_section_that_does_not_load_is_skipped(self): broken = LEGACY_PROJECT_FILE.replace("AgenticEdgeKind.SUPERVISES", "AgenticEdgeKind.OVERSEES") warnings = [] project = project_to_json(broken, warnings) - classes = project["diagrams"]["ClassDiagram"][0]["model"]["elements"].values() - assert "Book" in {element["name"] for element in classes} + classes = project["diagrams"]["ClassDiagram"][0]["model"]["nodes"] + assert "Book" in {node["data"]["name"] for node in classes} component, = project["diagrams"]["ComponentDiagram"] - assert component["model"]["elements"] == {} + assert component["model"]["nodes"] == [] skipped, = warnings # not what the section read before it failed assert skipped.startswith("Skipped the Component diagram") assert "'AgenticEdgeKind' has no attribute 'OVERSEES'" in skipped @@ -904,6 +930,31 @@ def test_executable_statement_is_rejected(self): with pytest.raises(ConversionError, match="Top-level statement not allowed: Raise"): component_buml_to_json("raise RuntimeError('boom')") + def test_v3_layout_stash_from_older_exports_still_loads(self): + """`.py` files exported before the v4 migration carry the v3 layout stash + (``owner``, ``path`` relative to ``bounds``); they still convert, with the + edge points made absolute.""" + source = ( + "c1 = Component(name='A')\n" + "c1.layout = {'id': 'a', 'owner': None, 'bounds': {'x': 0, 'y': 0, 'width': 160, 'height': 100}," + " 'displayStereotype': True, 'wme_type': 'Component'}\n" + "c2 = Component(name='B')\n" + "c2.layout = {'id': 'b', 'owner': None, 'bounds': {'x': 300, 'y': 0, 'width': 160, 'height': 100}," + " 'displayStereotype': True, 'wme_type': 'Component'}\n" + "component_model = ComponentModel(name='M', components={c1, c2})\n" + "r = ComponentDependency(source=c1, target=c2)\n" + "r.layout = {'id': 'r', 'bounds': {'x': 160, 'y': 50, 'width': 140, 'height': 1}," + " 'path': [{'x': 0, 'y': 0}, {'x': 140, 'y': 0}], 'source_direction': 'Right'," + " 'target_direction': 'Left', 'isManuallyLayouted': False," + " 'wme_type': 'ComponentDependency'}\n" + "component_model.add_relationship(r)\n" + ) + result = component_buml_to_json(source) + edge = _edges_by_id(result)["r"] + assert edge["sourceHandle"] == "right" and edge["targetHandle"] == "left" + assert edge["data"]["points"] == [{"x": 160, "y": 50}, {"x": 300, "y": 50}] + assert sorted(_nodes_by_id(result)) == ["a", "b"] + # --------------------------------------------------------------------------- # LLM / Database / RAG round-trip @@ -911,79 +962,32 @@ def test_executable_statement_is_rejected(self): @pytest.fixture def llm_db_rag_component_diagram(): - """WME diagram with llm/db/rag Components + uses edges from an agent. + """Diagram with llm/db/rag Components + uses edges from an agent. - Mirrors the WME BPMN→Component derivation output for an agent that calls - an LLM, queries a DB, and reads a RAG store. + Mirrors the editor's BPMN→Component derivation output for an agent that + calls an LLM, queries a DB, and reads a RAG store. """ - return { - "title": "LLM DB RAG Diagram", - "model": { - "version": "3.0.0", - "type": "ComponentDiagram", - "size": {"width": 1200, "height": 600}, - "elements": { - "agent-1": { - "id": "agent-1", "name": "ResearchAgent", "type": "Component", - "owner": None, - "bounds": {"x": 100, "y": 200, "width": 160, "height": 80}, - "stereotype": "solution", "displayStereotype": True, - }, - "llm-1": { - "id": "llm-1", "name": "GPT4", "type": "Component", - "owner": None, - "bounds": {"x": 400, "y": 80, "width": 160, "height": 80}, - "stereotype": "llm", "displayStereotype": True, - }, - "db-1": { - "id": "db-1", "name": "OrdersDB", "type": "Component", - "owner": None, - "bounds": {"x": 400, "y": 200, "width": 160, "height": 80}, - "stereotype": "db", "displayStereotype": True, - }, - "rag-1": { - "id": "rag-1", "name": "KnowledgeBase", "type": "Component", - "owner": None, - "bounds": {"x": 400, "y": 320, "width": 160, "height": 80}, - "stereotype": "rag", "displayStereotype": True, - }, - }, - "relationships": { - "uses-llm": { - "id": "uses-llm", "name": "", "type": "ComponentDependency", - "owner": None, - "bounds": {"x": 260, "y": 120, "width": 140, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 140, "y": 0}], - "source": {"element": "agent-1", "direction": "Right"}, - "target": {"element": "llm-1", "direction": "Left"}, - "isManuallyLayouted": False, - "stereotype": "uses", - }, - "uses-db": { - "id": "uses-db", "name": "", "type": "ComponentDependency", - "owner": None, - "bounds": {"x": 260, "y": 240, "width": 140, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 140, "y": 0}], - "source": {"element": "agent-1", "direction": "Right"}, - "target": {"element": "db-1", "direction": "Left"}, - "isManuallyLayouted": False, - "stereotype": "uses", - }, - "uses-rag": { - "id": "uses-rag", "name": "", "type": "ComponentDependency", - "owner": None, - "bounds": {"x": 260, "y": 360, "width": 140, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 140, "y": 0}], - "source": {"element": "agent-1", "direction": "Right"}, - "target": {"element": "rag-1", "direction": "Left"}, - "isManuallyLayouted": False, - "stereotype": "uses", - }, - }, - "interactive": {"elements": {}, "relationships": {}}, - "assessments": {}, - }, - } + def uses(edge_id, target, y): + return _edge(edge_id, "ComponentDependency", "agent-1", target, + [{"x": 260, "y": y}, {"x": 400, "y": y}], stereotype="uses") + + return _diagram( + "LLM DB RAG Diagram", + [ + _node("agent-1", "component", 100, 200, 160, 80, + {"name": "ResearchAgent", "stereotype": "solution", + "isComponentHeaderShown": True}), + _node("llm-1", "component", 400, 80, 160, 80, + {"name": "GPT4", "stereotype": "llm", "isComponentHeaderShown": True}), + _node("db-1", "component", 400, 200, 160, 80, + {"name": "OrdersDB", "stereotype": "db", "isComponentHeaderShown": True}), + _node("rag-1", "component", 400, 320, 160, 80, + {"name": "KnowledgeBase", "stereotype": "rag", + "isComponentHeaderShown": True}), + ], + [uses("uses-llm", "llm-1", 120), uses("uses-db", "db-1", 240), + uses("uses-rag", "rag-1", 360)], + ) class TestLLMDBRAGRoundTrip: @@ -1002,7 +1006,7 @@ def test_import_promotes_to_correct_subtypes(self, llm_db_rag_component_diagram) assert type(components_by_id["rag-1"]) is RAG def test_uses_edges_survive_not_silently_dropped(self, llm_db_rag_component_diagram): - """Regression guard: before 04a the uses edges were silently dropped.""" + """Regression guard: the uses edges were once silently dropped.""" model = process_component_diagram(llm_db_rag_component_diagram) agentic_edges = [r for r in model.relationships if isinstance(r, AgenticEdge)] @@ -1013,14 +1017,14 @@ def test_uses_edges_survive_not_silently_dropped(self, llm_db_rag_component_diag def test_export_emits_correct_subtype_tokens(self, llm_db_rag_component_diagram): """Round-trip: import then export must emit llm/db/rag, never 'tool'.""" model = process_component_diagram(llm_db_rag_component_diagram) - out = component_object_to_json(model) - llm_elem = out["elements"]["llm-1"] - db_elem = out["elements"]["db-1"] - rag_elem = out["elements"]["rag-1"] - assert "llm" in llm_elem["stereotype"].split() - assert "db" in db_elem["stereotype"].split() - assert "rag" in rag_elem["stereotype"].split() + out_nodes = _nodes_by_id(component_object_to_json(model)) + llm_tokens = out_nodes["llm-1"]["data"]["stereotype"].split() + db_tokens = out_nodes["db-1"]["data"]["stereotype"].split() + rag_tokens = out_nodes["rag-1"]["data"]["stereotype"].split() + assert "llm" in llm_tokens + assert "db" in db_tokens + assert "rag" in rag_tokens # Most-derived-first: none of these should emit as plain 'tool'. - assert "tool" not in llm_elem["stereotype"].split() - assert "tool" not in db_elem["stereotype"].split() - assert "tool" not in rag_elem["stereotype"].split() + assert "tool" not in llm_tokens + assert "tool" not in db_tokens + assert "tool" not in rag_tokens diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_component_deployment_identity.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_component_deployment_identity.py index e51848041..4d22608f7 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_component_deployment_identity.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_component_deployment_identity.py @@ -1,9 +1,9 @@ -"""JSON -> BUML -> JSON identity for editor-shaped Component and Deployment diagrams. +"""JSON -> BUML -> JSON identity for editor-shaped v4 Component and Deployment diagrams. -The fixtures carry exactly the keys the web editor serialises for each element -and relationship, so every field the editor writes (cross-diagram links, -stereotypes, owners, layout) must come back unchanged -- both straight through -the metamodel and through a generated BUML file. +The fixtures carry exactly the keys the web editor serialises for each node and +edge, so every field the editor writes (cross-diagram links, stereotypes, +parents, layout) must come back unchanged -- both straight through the +metamodel and through a generated BUML file. """ import copy @@ -29,107 +29,122 @@ from besser.utilities.web_modeling_editor.backend.services.exceptions import ConversionError -def _bounds(x, y, width=160, height=100): - return {"x": x, "y": y, "width": width, "height": height} +def _node(node_id, node_type, x, y, width, height, data, parent=None): + node = { + "id": node_id, "type": node_type, + "position": {"x": x, "y": y}, + "width": width, "height": height, + "measured": {"width": width, "height": height}, + "data": data, + } + if parent is not None: + node["parentId"] = parent + return node -def _edge(rel_id, rel_type, source, target, **extra): - edge = { - "id": rel_id, "name": "", "type": rel_type, "owner": None, - "bounds": _bounds(0, 0, 100, 1), - "path": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], - "source": {"element": source, "direction": "Right"}, - "target": {"element": target, "direction": "Left"}, +def _edge(edge_id, edge_type, source, target, stereotype=None): + data = { + "name": "", "label": "", + "points": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], "isManuallyLayouted": False, } - edge.update(extra) - return edge + if stereotype is not None: + data["stereotype"] = stereotype + return { + "id": edge_id, "source": source, "target": target, "type": edge_type, + "sourceHandle": "right", "targetHandle": "left", "data": data, + } -def _component(elem_id, name, stereotype, owner=None, **refs): - element = { - "id": elem_id, "name": name, "type": "Component", "owner": owner, - "bounds": _bounds(0, 0), "stereotype": stereotype, "displayStereotype": True, +def _component(node_id, name, stereotype, x=0, y=0, parent=None, **refs): + data = { + "name": name, "stereotype": stereotype, "isComponentHeaderShown": True, "realizes": refs.get("realizes", []), "processModelRefs": refs.get("processModelRefs", []), } if "agentModelRef" in refs: - element["agentModelRef"] = refs["agentModelRef"] - return element + data["agentModelRef"] = refs["agentModelRef"] + return _node(node_id, "component", x, y, 160, 100, data, parent) @pytest.fixture def component_diagram(): - elements = { - "sub": {"id": "sub", "name": "Swarm", "type": "Subsystem", "owner": None, - "bounds": _bounds(0, 0, 600, 400), "stereotype": "subsystem", - "displayStereotype": True}, - "coder": _component("coder", "Coder", "solution", owner="sub", - realizes=["class-1"], processModelRefs=["bpmn-1"], - agentModelRef="agent-coder"), - "reviewer": _component("reviewer", "Reviewer", "supervision", owner="sub", - processModelRefs=["bpmn-1"], agentModelRef="agent-reviewer"), - "human": _component("human", "Product Owner", "human", - processModelRefs=["bpmn-1"], agentModelRef="agent-human"), - "frontend": _component("frontend", "Frontend", "component", realizes=["class-2"]), - "llm": _component("llm", "GPT", "llm"), - "api": {"id": "api", "name": "TaskApi", "type": "ComponentInterface", "owner": None, - "bounds": _bounds(0, 0, 20, 20)}, - } - relationships = { - "r-supervises": _edge("r-supervises", "ComponentDependency", "reviewer", "coder", - stereotype="supervises"), - "r-uses": _edge("r-uses", "ComponentDependency", "coder", "llm", stereotype="uses"), - "r-plain": _edge("r-plain", "ComponentDependency", "frontend", "human", stereotype="«use»"), - "r-prov": _edge("r-prov", "ComponentInterfaceProvided", "llm", "api"), - "r-req": _edge("r-req", "ComponentInterfaceRequired", "frontend", "api"), - } + nodes = [ + _node("sub", "componentSubsystem", 0, 0, 600, 400, + {"name": "Swarm", "stereotype": "subsystem", + "isComponentSubsystemHeaderShown": True}), + _component("coder", "Coder", "solution", 20, 60, parent="sub", + realizes=["class-1"], processModelRefs=["bpmn-1"], + agentModelRef="agent-coder"), + _component("reviewer", "Reviewer", "supervision", 300, 60, parent="sub", + processModelRefs=["bpmn-1"], agentModelRef="agent-reviewer"), + _component("human", "Product Owner", "human", 700, 0, + processModelRefs=["bpmn-1"], agentModelRef="agent-human"), + _component("frontend", "Frontend", "component", 700, 200, realizes=["class-2"]), + _component("llm", "GPT", "llm", 700, 400), + _node("api", "componentInterface", 900, 100, 20, 20, {"name": "TaskApi"}), + ] + edges = [ + _edge("r-supervises", "ComponentDependency", "reviewer", "coder", + stereotype="supervises"), + _edge("r-uses", "ComponentDependency", "coder", "llm", stereotype="uses"), + _edge("r-plain", "ComponentDependency", "frontend", "human", stereotype="«use»"), + _edge("r-prov", "ComponentProvidedInterface", "llm", "api"), + _edge("r-req", "ComponentRequiredInterface", "frontend", "api"), + ] return {"title": "Components", "model": { - "version": "3.0.0", "type": "ComponentDiagram", "size": {"width": 800, "height": 600}, - "elements": elements, "relationships": relationships, + "version": "4.0.0", "type": "ComponentDiagram", "title": "Components", + "nodes": nodes, "edges": edges, "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, }} @pytest.fixture def deployment_diagram(): - elements = { - "host": {"id": "host", "name": "Swarm Host", "type": "DeploymentNode", "owner": None, - "bounds": _bounds(0, 0, 700, 400), "stereotype": "docker host", - "displayStereotype": True}, - "plain": {"id": "plain", "name": "Edge", "type": "DeploymentNode", "owner": None, - "bounds": _bounds(800, 0)}, - "generic": {"id": "generic", "name": "Cache", "type": "DeploymentNode", "owner": None, - "bounds": _bounds(800, 200), "stereotype": "node", "displayStereotype": True}, - "ee": {"id": "ee", "name": "Coder", "type": "DeploymentNode", "owner": "host", - "bounds": _bounds(20, 40, 200, 150), "stereotype": "executionEnvironment", - "displayStereotype": True}, - "art": {"id": "art", "name": "Coder [3]", "type": "DeploymentArtifact", "owner": "ee", - "bounds": _bounds(30, 80, 160, 40), "manifests": ["coder"], - "agentModelRef": "agent-coder"}, - "lib": {"id": "lib", "name": "Library", "type": "DeploymentArtifact", "owner": None, - "bounds": _bounds(300, 500, 160, 40), "manifests": []}, - "dc": {"id": "dc", "name": "Coder", "type": "DeploymentComponent", "owner": None, - "bounds": _bounds(20, 450), "stereotype": "component", "displayStereotype": True}, - "iface": {"id": "iface", "name": "Port", "type": "DeploymentInterface", "owner": None, - "bounds": _bounds(500, 500, 20, 20)}, - } - relationships = { - "r-manifest": _edge("r-manifest", "DeploymentDependency", "art", "dc"), - "r-comm": _edge("r-comm", "DeploymentAssociation", "host", "plain"), - "r-deploy": _edge("r-deploy", "DeploymentAssociation", "lib", "generic"), - "r-prov": _edge("r-prov", "DeploymentInterfaceProvided", "lib", "iface"), - } + nodes = [ + _node("host", "deploymentNode", 0, 0, 700, 400, + {"name": "Swarm Host", "stereotype": "docker host", "isComponentHeaderShown": True}), + _node("plain", "deploymentNode", 800, 0, 160, 100, + {"name": "Edge", "stereotype": "", "isComponentHeaderShown": True}), + _node("generic", "deploymentNode", 800, 200, 160, 100, + {"name": "Cache", "stereotype": "node", "isComponentHeaderShown": True}), + _node("ee", "deploymentNode", 20, 40, 200, 150, + {"name": "Coder", "stereotype": "executionEnvironment", + "isComponentHeaderShown": True}, parent="host"), + _node("art", "deploymentArtifact", 10, 40, 160, 40, + {"name": "Coder [3]", "manifests": ["coder"], "agentModelRef": "agent-coder"}, + parent="ee"), + _node("lib", "deploymentArtifact", 300, 500, 160, 40, + {"name": "Library", "manifests": []}), + _node("dc", "deploymentComponent", 20, 450, 160, 100, + {"name": "Coder", "stereotype": "component", "isComponentHeaderShown": True}), + _node("iface", "deploymentInterface", 500, 500, 20, 20, {"name": "Port"}), + ] + edges = [ + _edge("r-manifest", "DeploymentDependency", "art", "dc"), + _edge("r-comm", "DeploymentAssociation", "host", "plain"), + _edge("r-deploy", "DeploymentAssociation", "lib", "generic"), + _edge("r-prov", "DeploymentProvidedInterface", "lib", "iface"), + ] return {"title": "Deployment", "model": { - "version": "3.0.0", "type": "DeploymentDiagram", "size": {"width": 1000, "height": 700}, - "elements": elements, "relationships": relationships, + "version": "4.0.0", "type": "DeploymentDiagram", "title": "Deployment", + "nodes": nodes, "edges": edges, "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, }} +def _by_id(items): + return {item["id"]: item for item in items} + + def _assert_identity(original: dict, round_tripped: dict): - assert round_tripped["elements"] == original["model"]["elements"] - assert round_tripped["relationships"] == original["model"]["relationships"] + assert round_tripped["version"] == "4.0.0" + assert _by_id(round_tripped["nodes"]) == _by_id(original["model"]["nodes"]) + assert _by_id(round_tripped["edges"]) == _by_id(original["model"]["edges"]) + + +def _node_named(diagram, node_id): + return next(n for n in diagram["model"]["nodes"] if n["id"] == node_id) class TestComponentIdentity: @@ -148,8 +163,8 @@ def test_json_buml_file_json_is_identity(self, component_diagram): _assert_identity(original, component_buml_to_json(source)) def test_invalid_edge_raises_instead_of_being_dropped(self, component_diagram): - component_diagram["model"]["relationships"]["r-bad"] = _edge( - "r-bad", "ComponentDependency", "frontend", "llm", stereotype="knows") + component_diagram["model"]["edges"].append(_edge( + "r-bad", "ComponentDependency", "frontend", "llm", stereotype="knows")) with pytest.raises(ConversionError, match="r-bad"): process_component_diagram(component_diagram) @@ -165,20 +180,20 @@ def test_json_buml_file_json_is_identity(self, deployment_diagram): _assert_identity(original, deployment_buml_to_json(source)) def test_permission_suffix_does_not_change_deployment_locality(self, deployment_diagram): - deployment_diagram["model"]["elements"]["host"]["stereotype"] = ( + _node_named(deployment_diagram, "host")["data"]["stereotype"] = ( "device {permission: external, repo:read}" ) model = process_deployment_diagram(deployment_diagram) output = deployment_object_to_json(model) - assert output["elements"]["host"]["stereotype"] == "device" + assert _by_id(output["nodes"])["host"]["data"]["stereotype"] == "device" def test_invalid_association_raises_instead_of_being_dropped(self, deployment_diagram): - deployment_diagram["model"]["relationships"]["r-bad"] = _edge( - "r-bad", "DeploymentAssociation", "plain", "lib") + deployment_diagram["model"]["edges"].append(_edge( + "r-bad", "DeploymentAssociation", "plain", "lib")) with pytest.raises(ConversionError, match="r-bad"): process_deployment_diagram(deployment_diagram) def test_node_nested_in_its_own_child_raises(self, deployment_diagram): - deployment_diagram["model"]["elements"]["host"]["owner"] = "ee" + _node_named(deployment_diagram, "host")["parentId"] = "ee" with pytest.raises(ConversionError): process_deployment_diagram(deployment_diagram) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_converter_roundtrip.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_converter_roundtrip.py index 12195f7d2..c5b01c500 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_converter_roundtrip.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_converter_roundtrip.py @@ -1,17 +1,12 @@ """ Roundtrip tests for JSON -> BUML -> JSON converters. -Validates that essential data survives a full conversion cycle: - 1. Class diagram: JSON -> process_class_diagram -> DomainModel -> class_buml_to_json -> JSON - 2. State machine: JSON -> process_state_machine -> StateMachine -> state_machine_object_to_json -> JSON - 3. Object diagram: JSON -> process_object_diagram -> ObjectModel (data verification only; - there is no ObjectModel-to-JSON converter that works from metamodel objects) - -Layout positions (bounds, path) are intentionally NOT compared because the -BUML-to-JSON converter re-computes layout from scratch. +All tests are written against the v4 wire shape (``{nodes, edges}``). +See ``docs/source/migrations/uml-v4-shape.md``. """ import json +from collections import Counter import pytest @@ -42,596 +37,554 @@ # --------------------------------------------------------------------------- -# Helpers +# v4 helpers # --------------------------------------------------------------------------- -def _resolve_elements(json_data): - """Resolve the elements dict from either input format (model.elements) or output format (elements).""" - elements = json_data.get("elements", {}) - if not elements: - elements = (json_data.get("model") or {}).get("elements", {}) - return elements +def _model(payload): + """Return the inner v4 model dict — accepts both the {title, model} fixture + envelope and the bare ``{nodes, edges, ...}`` converter output.""" + if isinstance(payload, dict) and "nodes" in payload and "edges" in payload: + return payload + return (payload or {}).get("model") or {} -def _resolve_relationships(json_data): - """Resolve the relationships dict from either input format (model.relationships) or output format (relationships).""" - rels = json_data.get("relationships", {}) - if not rels: - rels = (json_data.get("model") or {}).get("relationships", {}) - return rels +def _nodes(payload): + return _model(payload).get("nodes") or [] -def _extract_elements_by_type(json_result, element_type): - """Return a list of elements matching the given type from the JSON result.""" - elements = _resolve_elements(json_result) - return [e for e in elements.values() if e.get("type") == element_type] +def _edges(payload): + return _model(payload).get("edges") or [] -def _extract_relationships_by_type(json_result, rel_type): - """Return a list of relationships matching the given type from the JSON result.""" - relationships = _resolve_relationships(json_result) - return [r for r in relationships.values() if r.get("type") == rel_type] +def _nodes_by_type(payload, node_type): + return [n for n in _nodes(payload) if n.get("type") == node_type] -def _get_class_names(json_data): - """Extract class/abstract-class names from a JSON diagram.""" - elements = _resolve_elements(json_data) - return { - e["name"] - for e in elements.values() - if e.get("type") in ("Class", "AbstractClass") - } +def _edges_by_type(payload, edge_type): + return [e for e in _edges(payload) if e.get("type") == edge_type] -def _get_enum_names(json_data): - """Extract enumeration names from a JSON diagram.""" - elements = _resolve_elements(json_data) - return { - e["name"] - for e in elements.values() - if e.get("type") == "Enumeration" - } +def _data(node): + return node.get("data") or {} -def _get_attribute_names_for_class(json_data, class_name): - """Return attribute names belonging to a given class in the JSON.""" - elements = _resolve_elements(json_data) - # Find the class element - class_elem = None - for e in elements.values(): - if e.get("type") in ("Class", "AbstractClass") and e.get("name") == class_name: - class_elem = e - break - if not class_elem: +def _node_by_id(payload, node_id): + for n in _nodes(payload): + if n.get("id") == node_id: + return n + return None + + +def _class_nodes(payload): + """Return all v4 class nodes (concrete, abstract, enumeration).""" + return _nodes_by_type(payload, "class") + + +def _class_node_by_name(payload, class_name): + for n in _class_nodes(payload): + if (_data(n).get("name") or "") == class_name: + return n + return None + + +def _class_names_by_kind(payload, *, abstract=False, enumeration=False): + """Return the set of names for class nodes matching the given stereotype.""" + out = set() + for n in _class_nodes(payload): + data = _data(n) + st = (data.get("stereotype") or "").strip().lower() + if abstract and st == "abstract": + out.add(data.get("name")) + elif enumeration and st == "enumeration": + out.add(data.get("name")) + elif not abstract and not enumeration and not st: + out.add(data.get("name")) + return out + + +def _all_class_names(payload): + return {(_data(n).get("name") or "") for n in _class_nodes(payload)} + + +def _attribute_names_for_class(payload, class_name): + node = _class_node_by_name(payload, class_name) + if not node: return set() - # Resolve attribute IDs - attr_names = set() - for attr_id in class_elem.get("attributes", []): - attr_elem = elements.get(attr_id, {}) - name = attr_elem.get("name", "") - # New format uses separate 'name' field; legacy encodes "vis name: type" in name - if attr_elem.get("attributeType"): - attr_names.add(name) - else: - # Legacy: parse "+ name: type" or just "name" - attr_names.add(name) - return attr_names + return {(a.get("name") or "") for a in _data(node).get("attributes") or []} -def _get_method_names_for_class(json_data, class_name): - """Return method names belonging to a given class in the JSON. +def _attributes_for_class(payload, class_name): + """Return a name -> attribute-row dict for the given class.""" + node = _class_node_by_name(payload, class_name) + if not node: + return {} + return {a.get("name"): a for a in _data(node).get("attributes") or [] if a.get("name")} - Method names in the output JSON are full signatures like - "+ doStuff(a: int): str". This helper extracts just the bare name - (the part before the opening parenthesis, stripped of visibility prefix). - """ - elements = _resolve_elements(json_data) - class_elem = None - for e in elements.values(): - if e.get("type") in ("Class", "AbstractClass") and e.get("name") == class_name: - class_elem = e - break - if not class_elem: + +def _method_names_for_class(payload, class_name): + """Return the *bare* method names (stripped of visibility / signature).""" + node = _class_node_by_name(payload, class_name) + if not node: return set() - names = set() - for method_id in class_elem.get("methods", []): - method_elem = elements.get(method_id, {}) - sig = method_elem.get("name", "") - # Strip visibility symbol if present + out = set() + for m in _data(node).get("methods") or []: + sig = m.get("name", "") or "" if sig and sig[0] in "+-#~": sig = sig[1:].lstrip() - # Extract name before '(' if "(" in sig: - bare = sig[:sig.index("(")].strip() + out.add(sig[:sig.index("(")].strip()) else: - bare = sig.strip() - names.add(bare) - return names + out.add(sig.strip()) + return out -# =========================================================================== -# Fixtures: reusable JSON payloads -# =========================================================================== +# --------------------------------------------------------------------------- +# Fixtures: hand-authored v4 payloads. +# --------------------------------------------------------------------------- @pytest.fixture def minimal_class_diagram_json(): - """A minimal class diagram with two classes, attributes, a method, and a bidirectional association.""" - # Element IDs are arbitrary but must be consistent within the fixture + """A minimal v4 class diagram with two classes, attributes, a method, + and a bidirectional association.""" return { "title": "LibraryModel", "model": { - "elements": { - "cls-book": { - "id": "cls-book", - "name": "Book", - "type": "Class", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": ["attr-title", "attr-pages"], - "methods": ["meth-summary"], - }, - "attr-title": { - "id": "attr-title", - "name": "title", - "type": "ClassAttribute", - "owner": "cls-book", - "visibility": "public", - "attributeType": "str", - "isOptional": False, - "bounds": {"x": 0, "y": 40, "width": 159, "height": 30}, - }, - "attr-pages": { - "id": "attr-pages", - "name": "pages", - "type": "ClassAttribute", - "owner": "cls-book", - "visibility": "private", - "attributeType": "int", - "isOptional": True, - "bounds": {"x": 0, "y": 70, "width": 159, "height": 30}, - }, - "meth-summary": { - "id": "meth-summary", - "name": "+ summary(verbose: bool): str", - "type": "ClassMethod", - "owner": "cls-book", - "bounds": {"x": 0, "y": 100, "width": 159, "height": 30}, - }, - "cls-author": { - "id": "cls-author", - "name": "Author", - "type": "Class", - "owner": None, - "bounds": {"x": 300, "y": 0, "width": 160, "height": 100}, - "attributes": ["attr-name"], - "methods": [], + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-book", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Book", + "stereotype": None, + "attributes": [ + {"id": "n-book-a-title", "name": "title", "attributeType": "str", "visibility": "public", "isOptional": False, "isId": False, "isExternalId": False}, + {"id": "n-book-a-pages", "name": "pages", "attributeType": "int", "visibility": "private", "isOptional": True, "isId": False, "isExternalId": False}, + ], + "methods": [ + {"id": "n-book-m-summary", "name": "+ summary(verbose: bool): str"}, + ], + }, }, - "attr-name": { - "id": "attr-name", - "name": "name", - "type": "ClassAttribute", - "owner": "cls-author", - "visibility": "public", - "attributeType": "str", - "isOptional": False, - "bounds": {"x": 300, "y": 40, "width": 159, "height": 30}, + { + "id": "n-author", + "type": "class", + "position": {"x": 300, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Author", + "stereotype": None, + "attributes": [ + {"id": "n-author-a-name", "name": "name", "attributeType": "str", "visibility": "public", "isOptional": False}, + ], + "methods": [], + }, }, - }, - "relationships": { - "rel-writes": { - "id": "rel-writes", - "name": "writes", + ], + "edges": [ + { + "id": "e-writes", + "source": "n-author", + "target": "n-book", "type": "ClassBidirectional", - "source": { - "element": "cls-author", - "multiplicity": "1..*", - "role": "author", - }, - "target": { - "element": "cls-book", - "multiplicity": "0..*", - "role": "book", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "writes", + "sourceRole": "author", + "sourceMultiplicity": "1..*", + "targetRole": "book", + "targetMultiplicity": "0..*", + "points": [], }, }, - }, + ], }, } @pytest.fixture def class_diagram_with_inheritance_json(): - """A class diagram with an abstract base class and an inheritance relationship.""" return { "title": "VehicleModel", "model": { - "elements": { - "cls-vehicle": { - "id": "cls-vehicle", - "name": "Vehicle", - "type": "AbstractClass", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": ["attr-speed"], - "methods": [], - }, - "attr-speed": { - "id": "attr-speed", - "name": "speed", - "type": "ClassAttribute", - "owner": "cls-vehicle", - "visibility": "public", - "attributeType": "float", - "isOptional": False, - "bounds": {"x": 0, "y": 40, "width": 159, "height": 30}, - }, - "cls-car": { - "id": "cls-car", - "name": "Car", - "type": "Class", - "owner": None, - "bounds": {"x": 0, "y": 200, "width": 160, "height": 100}, - "attributes": ["attr-doors"], - "methods": [], + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-vehicle", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Vehicle", + "stereotype": "abstract", + "attributes": [ + {"id": "a-speed", "name": "speed", "attributeType": "float", "visibility": "public"}, + ], + "methods": [], + }, }, - "attr-doors": { - "id": "attr-doors", - "name": "doors", - "type": "ClassAttribute", - "owner": "cls-car", - "visibility": "public", - "attributeType": "int", - "isOptional": False, - "bounds": {"x": 0, "y": 240, "width": 159, "height": 30}, + { + "id": "n-car", + "type": "class", + "position": {"x": 0, "y": 200}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Car", + "stereotype": None, + "attributes": [ + {"id": "a-doors", "name": "doors", "attributeType": "int", "visibility": "public"}, + ], + "methods": [], + }, }, - }, - "relationships": { - "rel-inherit": { - "id": "rel-inherit", - "name": "", + ], + "edges": [ + { + "id": "e-inherit", + "source": "n-car", + "target": "n-vehicle", "type": "ClassInheritance", - "source": {"element": "cls-car"}, - "target": {"element": "cls-vehicle"}, + "sourceHandle": "Top", + "targetHandle": "Bottom", + "data": {"points": []}, }, - }, + ], }, } @pytest.fixture def class_diagram_with_enum_json(): - """A class diagram with an enumeration and a class that uses it as an attribute type.""" return { "title": "OrderModel", "model": { - "elements": { - "enum-status": { - "id": "enum-status", - "name": "OrderStatus", - "type": "Enumeration", - "owner": None, - "bounds": {"x": 300, "y": 0, "width": 160, "height": 100}, - "attributes": ["lit-pending", "lit-shipped", "lit-delivered"], - "methods": [], - }, - "lit-pending": { - "id": "lit-pending", - "name": "PENDING", - "type": "ClassAttribute", - "owner": "enum-status", - "bounds": {"x": 300, "y": 40, "width": 159, "height": 30}, - }, - "lit-shipped": { - "id": "lit-shipped", - "name": "SHIPPED", - "type": "ClassAttribute", - "owner": "enum-status", - "bounds": {"x": 300, "y": 70, "width": 159, "height": 30}, - }, - "lit-delivered": { - "id": "lit-delivered", - "name": "DELIVERED", - "type": "ClassAttribute", - "owner": "enum-status", - "bounds": {"x": 300, "y": 100, "width": 159, "height": 30}, - }, - "cls-order": { - "id": "cls-order", - "name": "Order", - "type": "Class", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": ["attr-status", "attr-total"], - "methods": [], - }, - "attr-status": { - "id": "attr-status", - "name": "status", - "type": "ClassAttribute", - "owner": "cls-order", - "visibility": "public", - "attributeType": "OrderStatus", - "isOptional": False, - "bounds": {"x": 0, "y": 40, "width": 159, "height": 30}, + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-status", + "type": "class", + "position": {"x": 300, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "OrderStatus", + "stereotype": "enumeration", + "attributes": [ + {"id": "lit-pending", "name": "PENDING", "attributeType": "str", "visibility": "public"}, + {"id": "lit-shipped", "name": "SHIPPED", "attributeType": "str", "visibility": "public"}, + {"id": "lit-delivered", "name": "DELIVERED", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - "attr-total": { - "id": "attr-total", - "name": "total", - "type": "ClassAttribute", - "owner": "cls-order", - "visibility": "public", - "attributeType": "float", - "isOptional": False, - "bounds": {"x": 0, "y": 70, "width": 159, "height": 30}, + { + "id": "n-order", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Order", + "stereotype": None, + "attributes": [ + {"id": "a-status", "name": "status", "attributeType": "OrderStatus", "visibility": "public", "isOptional": False}, + {"id": "a-total", "name": "total", "attributeType": "float", "visibility": "public", "isOptional": False}, + ], + "methods": [], + }, }, - }, - "relationships": {}, + ], + "edges": [], }, } @pytest.fixture def class_diagram_with_composition_json(): - """A class diagram with a composition relationship.""" return { "title": "CompanyModel", "model": { - "elements": { - "cls-company": { - "id": "cls-company", - "name": "Company", - "type": "Class", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": ["attr-cname"], - "methods": [], - }, - "attr-cname": { - "id": "attr-cname", - "name": "companyName", - "type": "ClassAttribute", - "owner": "cls-company", - "visibility": "public", - "attributeType": "str", - "isOptional": False, - "bounds": {"x": 0, "y": 40, "width": 159, "height": 30}, - }, - "cls-department": { - "id": "cls-department", - "name": "Department", - "type": "Class", - "owner": None, - "bounds": {"x": 300, "y": 0, "width": 160, "height": 100}, - "attributes": ["attr-dname"], - "methods": [], + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-company", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Company", + "stereotype": None, + "attributes": [ + {"id": "a-cname", "name": "companyName", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - "attr-dname": { - "id": "attr-dname", - "name": "deptName", - "type": "ClassAttribute", - "owner": "cls-department", - "visibility": "public", - "attributeType": "str", - "isOptional": False, - "bounds": {"x": 300, "y": 40, "width": 159, "height": 30}, + { + "id": "n-dept", + "type": "class", + "position": {"x": 300, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Department", + "stereotype": None, + "attributes": [ + {"id": "a-dname", "name": "deptName", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - }, - "relationships": { - "rel-has": { - "id": "rel-has", - "name": "has_departments", + ], + "edges": [ + { + "id": "e-has", + "source": "n-company", + "target": "n-dept", "type": "ClassComposition", - "source": { - "element": "cls-company", - "multiplicity": "1", - "role": "company", - }, - "target": { - "element": "cls-department", - "multiplicity": "1..*", - "role": "department", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "has_departments", + "sourceRole": "company", + "sourceMultiplicity": "1", + "targetRole": "department", + "targetMultiplicity": "1..*", + "points": [], }, }, - }, + ], }, } @pytest.fixture def state_machine_json(): - """A state machine with two states, a transition, and code blocks for body and event.""" return { "title": "OrderStateMachine", "model": { - "elements": { - "initial": { - "id": "initial", - "name": "", + "version": "4.0.0", + "type": "StateMachineDiagram", + "nodes": [ + { + "id": "n-init", "type": "StateInitialNode", - "owner": None, - "bounds": {"x": -850, "y": -280, "width": 45, "height": 45}, + "position": {"x": -850, "y": -280}, + "width": 45, "height": 45, + "measured": {"width": 45, "height": 45}, + "data": {"name": ""}, }, - "state-idle": { - "id": "state-idle", - "name": "idle", + { + "id": "n-idle", "type": "State", - "owner": None, - "bounds": {"x": -550, "y": -300, "width": 160, "height": 100}, - "bodies": ["body-idle-body"], - "fallbackBodies": [], - }, - "body-idle-body": { - "id": "body-idle-body", - "name": "idle_body", - "type": "StateBody", - "owner": "state-idle", - "bounds": {"x": -549.5, "y": -259.5, "width": 159, "height": 30}, + "position": {"x": -550, "y": -300}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "idle", + "bodies": [{"id": "body-idle", "name": "idle_body"}], + "fallbackBodies": [], + }, }, - "state-processing": { - "id": "state-processing", - "name": "processing", + { + "id": "n-proc", "type": "State", - "owner": None, - "bounds": {"x": -60, "y": -300, "width": 160, "height": 100}, - "bodies": ["body-proc-body"], - "fallbackBodies": [], - }, - "body-proc-body": { - "id": "body-proc-body", - "name": "process_body", - "type": "StateBody", - "owner": "state-processing", - "bounds": {"x": -59.5, "y": -259.5, "width": 159, "height": 30}, + "position": {"x": -60, "y": -300}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "processing", + "bodies": [{"id": "body-proc", "name": "process_body"}], + "fallbackBodies": [], + }, }, - "code-idle-body": { - "id": "code-idle-body", - "name": "idle_body", + { + "id": "code-idle", "type": "StateCodeBlock", - "owner": None, - "bounds": {"x": -970, "y": 80, "width": 580, "height": 200}, - "code": "def idle_body(session):\n session.reply('Waiting for input.')", - "language": "python", + "position": {"x": -970, "y": 80}, + "width": 580, "height": 200, + "measured": {"width": 580, "height": 200}, + "data": { + "name": "idle_body", + "code": "def idle_body(session):\n session.reply('Waiting for input.')", + "language": "python", + }, }, - "code-proc-body": { - "id": "code-proc-body", - "name": "process_body", + { + "id": "code-proc", "type": "StateCodeBlock", - "owner": None, - "bounds": {"x": -360, "y": 80, "width": 580, "height": 200}, - "code": "def process_body(session):\n session.reply('Processing...')", - "language": "python", + "position": {"x": -360, "y": 80}, + "width": 580, "height": 200, + "measured": {"width": 580, "height": 200}, + "data": { + "name": "process_body", + "code": "def process_body(session):\n session.reply('Processing...')", + "language": "python", + }, }, - "code-start-event": { - "id": "code-start-event", - "name": "start_event", + { + "id": "code-start", "type": "StateCodeBlock", - "owner": None, - "bounds": {"x": 250, "y": 80, "width": 580, "height": 200}, - "code": "def start_event(session):\n return session.message", - "language": "python", + "position": {"x": 250, "y": 80}, + "width": 580, "height": 200, + "measured": {"width": 580, "height": 200}, + "data": { + "name": "start_event", + "code": "def start_event(session):\n return session.message", + "language": "python", + }, }, - }, - "relationships": { - "trans-init": { - "id": "trans-init", - "name": "", + ], + "edges": [ + { + "id": "t-init", + "source": "n-init", + "target": "n-idle", "type": "StateTransition", - "source": {"element": "initial", "direction": "Right"}, - "target": {"element": "state-idle", "direction": "Left"}, + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"name": "", "points": []}, }, - "trans-start": { - "id": "trans-start", - "name": "start_event", + { + "id": "t-start", + "source": "n-idle", + "target": "n-proc", "type": "StateTransition", - "source": {"element": "state-idle", "direction": "Right"}, - "target": {"element": "state-processing", "direction": "Left"}, + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"name": "start_event", "points": []}, }, - }, + ], }, } -def _build_object_diagram_fixture(minimal_class_diagram_json, include_attributes=True): - """Build an object diagram JSON referencing the minimal class diagram. +def _build_object_diagram_v4_fixture( + class_diagram_v4, *, include_attributes=True, attribute_style="split", +): + """Build a v4 object diagram referencing the given v4 class diagram. - Creates two objects (book1 of Book, author1 of Author) and a link between them. - When *include_attributes* is True, objects include attribute slots (which - triggers the DataValue code path). - """ - # Produce the reference class diagram JSON via roundtrip - domain_model = process_class_diagram(minimal_class_diagram_json) - ref_json = class_buml_to_json(domain_model) - ref_elements = ref_json["elements"] - ref_relationships = ref_json["relationships"] - - # Find class IDs and association ID from the produced JSON - book_class_id = None - author_class_id = None - for eid, elem in ref_elements.items(): - if elem.get("type") in ("Class", "AbstractClass"): - if elem["name"] == "Book": - book_class_id = eid - elif elem["name"] == "Author": - author_class_id = eid + Two objects (book1 of Book, author1 of Author) and a link between them. - association_id = None - for rid, rel in ref_relationships.items(): - if rel.get("type") in ("ClassBidirectional", "ClassUnidirectional", "ClassComposition"): - association_id = rid - break - - elements = { - "obj-book1": { + ``attribute_style`` selects the attribute-row shape: ``"split"`` is the + canonical v4 form (separate ``name`` / ``value`` fields, per + ``ObjectNodeAttribute``); ``"legacy"`` bakes the combined + ``"+ name: type = value"`` string into ``name`` (older fixtures). + """ + book_id = "n-book" + author_id = "n-author" + # Re-emit the reference class diagram via the converter so the link's + # ``associationId`` matches a real edge id in the reference. + cd_buml = process_class_diagram(class_diagram_v4) + ref = class_buml_to_json(cd_buml) + # Keep the v4 reference data — both class diagrams are v4. + nodes = [ + { "id": "obj-book1", - "name": "book1", - "type": "ObjectName", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}, - "attributes": [], - "methods": [], - "classId": book_class_id, - "className": "Book", + "type": "objectName", + "position": {"x": 0, "y": 0}, + "width": 200, "height": 100, + "measured": {"width": 200, "height": 100}, + "data": { + "name": "book1 : Book", + "classId": book_id, + "className": "Book", + "attributes": [], + "methods": [], + }, }, - "obj-author1": { + { "id": "obj-author1", - "name": "author1", - "type": "ObjectName", - "owner": None, - "bounds": {"x": 300, "y": 0, "width": 200, "height": 100}, - "attributes": [], - "methods": [], - "classId": author_class_id, - "className": "Author", + "type": "objectName", + "position": {"x": 300, "y": 0}, + "width": 200, "height": 100, + "measured": {"width": 200, "height": 100}, + "data": { + "name": "author1 : Author", + "classId": author_id, + "className": "Author", + "attributes": [], + "methods": [], + }, }, - } - + ] if include_attributes: - elements["oattr-title"] = { - "id": "oattr-title", - "name": "+ title: str = TheGreatGatsby", - "type": "ObjectAttribute", - "owner": "obj-book1", - "bounds": {"x": 0, "y": 30, "width": 199, "height": 30}, - } - elements["obj-book1"]["attributes"] = ["oattr-title"] - - elements["oattr-aname"] = { - "id": "oattr-aname", - "name": "+ name: str = Fitzgerald", - "type": "ObjectAttribute", - "owner": "obj-author1", - "bounds": {"x": 300, "y": 30, "width": 199, "height": 30}, - } - elements["obj-author1"]["attributes"] = ["oattr-aname"] + if attribute_style == "split": + nodes[0]["data"]["attributes"] = [ + {"id": "oa-title", "name": "title", "attributeType": "str", + "value": "TheGreatGatsby"}, + ] + nodes[1]["data"]["attributes"] = [ + {"id": "oa-aname", "name": "name", "attributeType": "str", + "value": "Fitzgerald"}, + ] + else: + nodes[0]["data"]["attributes"] = [ + {"id": "oa-title", "name": "+ title: str = TheGreatGatsby"}, + ] + nodes[1]["data"]["attributes"] = [ + {"id": "oa-aname", "name": "+ name: str = Fitzgerald"}, + ] + + # Pick the first ClassBidirectional edge from the reference for the link's + # associationId. + association_id = None + for e in ref.get("edges") or []: + if e.get("type") in ("ClassBidirectional", "ClassUnidirectional", "ClassComposition"): + association_id = e.get("id") + break + + edges = [ + { + "id": "link-writes", + "source": "obj-author1", + "target": "obj-book1", + "type": "ObjectLink", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"name": "writes_link", "associationId": association_id, "points": []}, + }, + ] return { "title": "LibraryObjects", "model": { - "elements": elements, - "relationships": { - "link-writes": { - "id": "link-writes", - "name": "writes_link", - "type": "ObjectLink", - "source": {"element": "obj-author1"}, - "target": {"element": "obj-book1"}, - "associationId": association_id, - }, - }, - "referenceDiagramData": ref_json, + "version": "4.0.0", + "type": "ObjectDiagram", + "nodes": nodes, + "edges": edges, + "referenceDiagramData": ref, }, } @pytest.fixture def object_diagram_json(minimal_class_diagram_json): - """Object diagram without attribute values (avoids DataValue name validation bug).""" - return _build_object_diagram_fixture(minimal_class_diagram_json, include_attributes=False) + return _build_object_diagram_v4_fixture(minimal_class_diagram_json, include_attributes=False) @pytest.fixture def object_diagram_with_attrs_json(minimal_class_diagram_json): - """Object diagram with attribute values (hits DataValue name validation).""" - return _build_object_diagram_fixture(minimal_class_diagram_json, include_attributes=True) + return _build_object_diagram_v4_fixture(minimal_class_diagram_json, include_attributes=True) + + +@pytest.fixture +def object_diagram_with_legacy_attrs_json(minimal_class_diagram_json): + return _build_object_diagram_v4_fixture( + minimal_class_diagram_json, include_attributes=True, attribute_style="legacy", + ) # =========================================================================== @@ -642,254 +595,155 @@ class TestClassDiagramRoundtrip: """JSON -> BUML -> JSON roundtrip for class diagrams.""" def test_classes_preserved(self, minimal_class_diagram_json): - """Class names survive the roundtrip.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - - original_classes = _get_class_names(minimal_class_diagram_json) - result_classes = _get_class_names(result) - assert original_classes == result_classes + assert _all_class_names(minimal_class_diagram_json) == _all_class_names(result) def test_attributes_preserved(self, minimal_class_diagram_json): - """Attribute names for each class survive the roundtrip.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - for class_name in ("Book", "Author"): - orig_attrs = _get_attribute_names_for_class(minimal_class_diagram_json, class_name) - result_attrs = _get_attribute_names_for_class(result, class_name) - assert orig_attrs == result_attrs, ( - f"Attribute mismatch for class '{class_name}': {orig_attrs} vs {result_attrs}" - ) + assert _attribute_names_for_class(minimal_class_diagram_json, class_name) == \ + _attribute_names_for_class(result, class_name), \ + f"Attribute mismatch for class '{class_name}'" def test_attribute_types_preserved(self, minimal_class_diagram_json): - """Attribute types survive the roundtrip.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - - result_elements = result["elements"] - # Find Book's attributes in the result - book_attrs = {} - for e in result_elements.values(): - if e.get("type") == "ClassAttribute" and e.get("attributeType"): - # Find owner class name - owner_id = e.get("owner") - owner = result_elements.get(owner_id, {}) - if owner.get("name") == "Book": - book_attrs[e["name"]] = e["attributeType"] - - assert book_attrs.get("title") == "str" - assert book_attrs.get("pages") == "int" + attrs = _attributes_for_class(result, "Book") + assert attrs["title"]["attributeType"] == "str" + assert attrs["pages"]["attributeType"] == "int" def test_attribute_visibility_preserved(self, minimal_class_diagram_json): - """Attribute visibility survives the roundtrip.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - - result_elements = result["elements"] - visibilities = {} - for e in result_elements.values(): - if e.get("type") == "ClassAttribute" and e.get("visibility"): - owner_id = e.get("owner") - owner = result_elements.get(owner_id, {}) - if owner.get("name") == "Book": - visibilities[e["name"]] = e["visibility"] - - assert visibilities.get("title") == "public" - assert visibilities.get("pages") == "private" + attrs = _attributes_for_class(result, "Book") + assert attrs["title"]["visibility"] == "public" + assert attrs["pages"]["visibility"] == "private" def test_attribute_optional_preserved(self, minimal_class_diagram_json): - """Attribute isOptional flag survives the roundtrip.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - - result_elements = result["elements"] - optionals = {} - for e in result_elements.values(): - if e.get("type") == "ClassAttribute" and "isOptional" in e: - owner_id = e.get("owner") - owner = result_elements.get(owner_id, {}) - if owner.get("name") == "Book": - optionals[e["name"]] = e["isOptional"] - - assert optionals.get("title") is False - assert optionals.get("pages") is True + attrs = _attributes_for_class(result, "Book") + assert attrs["title"]["isOptional"] is False + assert attrs["pages"]["isOptional"] is True def test_attribute_is_id_and_external_id_preserved(self, minimal_class_diagram_json): - """`isId` and `isExternalId` flags survive the JSON -> BUML -> JSON roundtrip. - - Regression guard for the is_id work (PR #486) and the is_external_id - work (issues #230 / #225). We mutate the fixture in place rather than - building a new one so any future change to the fixture shape doesn't - cause drift. - """ - # Mutate the fixture: mark 'title' as id, 'pages' as external id. - # (isOptional must be False for both — metamodel enforces it.) - for element in minimal_class_diagram_json["model"]["elements"].values(): - if element.get("type") != "ClassAttribute": + """``isId`` / ``isExternalId`` flags survive the roundtrip.""" + # Mutate the fixture in place: title is id, pages is external id. + for node in minimal_class_diagram_json["model"]["nodes"]: + if (node.get("data") or {}).get("name") != "Book": continue - if element["name"] == "title": - element["isId"] = True - element["isExternalId"] = False - element["isOptional"] = False - elif element["name"] == "pages": - element["isId"] = False - element["isExternalId"] = True - element["isOptional"] = False + for attr in node["data"]["attributes"]: + if attr["name"] == "title": + attr["isId"] = True + attr["isExternalId"] = False + attr["isOptional"] = False + elif attr["name"] == "pages": + attr["isId"] = False + attr["isExternalId"] = True + attr["isOptional"] = False domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - flags_by_name = {} - for element in result["elements"].values(): - if element.get("type") != "ClassAttribute": - continue - owner = result["elements"].get(element.get("owner"), {}) - if owner.get("name") != "Book": - continue - flags_by_name[element["name"]] = { - "isId": element.get("isId"), - "isExternalId": element.get("isExternalId"), - } - - assert flags_by_name["title"] == {"isId": True, "isExternalId": False} - assert flags_by_name["pages"] == {"isId": False, "isExternalId": True} + attrs = _attributes_for_class(result, "Book") + assert attrs["title"].get("isId") is True + assert attrs["title"].get("isExternalId") is False + assert attrs["pages"].get("isId") is False + assert attrs["pages"].get("isExternalId") is True def test_methods_preserved(self, minimal_class_diagram_json): - """Method names survive the roundtrip.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - - orig_methods = _get_method_names_for_class(minimal_class_diagram_json, "Book") - result_methods = _get_method_names_for_class(result, "Book") - assert orig_methods == result_methods + assert _method_names_for_class(minimal_class_diagram_json, "Book") == \ + _method_names_for_class(result, "Book") def test_method_parameters_preserved(self, minimal_class_diagram_json): - """Method parameters survive the roundtrip (encoded in the signature string).""" + """The converter emits the canonical inspector shape: a bare method + ``name`` plus structured ``parameters`` rows and ``returnType`` + mirrored onto ``attributeType`` (never a fused signature string).""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - result_elements = result["elements"] - method_signatures = [] - for e in result_elements.values(): - if e.get("type") == "ClassMethod": - method_signatures.append(e["name"]) - - # The original method is: "+ summary(verbose: bool): str" - # After roundtrip, the signature should contain the same info - assert len(method_signatures) == 1 - sig = method_signatures[0] - assert "summary" in sig - assert "verbose" in sig - assert "bool" in sig - assert "str" in sig # return type + book_node = _class_node_by_name(result, "Book") + methods = _data(book_node).get("methods") or [] + + assert len(methods) == 1 + method = methods[0] + assert method.get("name") == "summary" + assert method.get("returnType") == "str" + assert method.get("attributeType") == "str" + params = method.get("parameters") or [] + assert len(params) == 1 + assert params[0].get("name") == "verbose" + assert params[0].get("parameterType") == "bool" def test_association_preserved(self, minimal_class_diagram_json): - """Bidirectional association survives the roundtrip.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - bidir_rels = _extract_relationships_by_type(result, "ClassBidirectional") - assert len(bidir_rels) == 1 - rel = bidir_rels[0] + bidir_edges = _edges_by_type(result, "ClassBidirectional") + assert len(bidir_edges) == 1 + edge_data = _data(bidir_edges[0]) - # Verify roles survive - roles = {rel["source"]["role"], rel["target"]["role"]} + roles = {edge_data.get("sourceRole"), edge_data.get("targetRole")} assert roles == {"author", "book"} - # Verify multiplicities survive - mults = {rel["source"]["multiplicity"], rel["target"]["multiplicity"]} + mults = {edge_data.get("sourceMultiplicity"), edge_data.get("targetMultiplicity")} assert "1..*" in mults assert "0..*" in mults def test_association_name_preserved(self, minimal_class_diagram_json): - """Association name survives the roundtrip.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) - bidir_rels = _extract_relationships_by_type(result, "ClassBidirectional") - assert len(bidir_rels) == 1 - assert bidir_rels[0]["name"] == "writes" + bidir_edges = _edges_by_type(result, "ClassBidirectional") + assert len(bidir_edges) == 1 + assert _data(bidir_edges[0]).get("name") == "writes" def test_inheritance_preserved(self, class_diagram_with_inheritance_json): - """Inheritance relationship and abstract class flag survive the roundtrip.""" domain_model = process_class_diagram(class_diagram_with_inheritance_json) result = class_buml_to_json(domain_model) - # Verify classes - assert _get_class_names(result) == {"Vehicle", "Car"} - - # Verify Vehicle is abstract - abstract_classes = _extract_elements_by_type(result, "AbstractClass") - assert len(abstract_classes) == 1 - assert abstract_classes[0]["name"] == "Vehicle" + assert _all_class_names(result) == {"Vehicle", "Car"} + assert _class_names_by_kind(result, abstract=True) == {"Vehicle"} + # Concrete (no stereotype) classes. + assert _class_names_by_kind(result) == {"Car"} - # Verify concrete Car class - concrete_classes = _extract_elements_by_type(result, "Class") - assert len(concrete_classes) == 1 - assert concrete_classes[0]["name"] == "Car" - - # Verify inheritance relationship - inherit_rels = _extract_relationships_by_type(result, "ClassInheritance") - assert len(inherit_rels) == 1 - - # Source (specific) should be Car, target (general) should be Vehicle - rel = inherit_rels[0] - result_elements = result["elements"] - source_elem = result_elements[rel["source"]["element"]] - target_elem = result_elements[rel["target"]["element"]] - assert source_elem["name"] == "Car" - assert target_elem["name"] == "Vehicle" + inherit_edges = _edges_by_type(result, "ClassInheritance") + assert len(inherit_edges) == 1 + edge = inherit_edges[0] + source = _node_by_id(result, edge["source"]) + target = _node_by_id(result, edge["target"]) + assert _data(source).get("name") == "Car" + assert _data(target).get("name") == "Vehicle" def test_enumeration_preserved(self, class_diagram_with_enum_json): - """Enumerations and their literals survive the roundtrip.""" domain_model = process_class_diagram(class_diagram_with_enum_json) result = class_buml_to_json(domain_model) - # Verify enumeration exists - enum_names = _get_enum_names(result) - assert "OrderStatus" in enum_names - - # Verify literals - result_elements = result["elements"] - enum_elem = None - for e in result_elements.values(): - if e.get("type") == "Enumeration" and e.get("name") == "OrderStatus": - enum_elem = e - break - - assert enum_elem is not None - literal_names = set() - for lit_id in enum_elem.get("attributes", []): - lit = result_elements.get(lit_id, {}) - literal_names.add(lit.get("name")) + assert _class_names_by_kind(result, enumeration=True) == {"OrderStatus"} + enum_node = _class_node_by_name(result, "OrderStatus") + assert enum_node is not None + literal_names = {a.get("name") for a in _data(enum_node).get("attributes") or []} assert literal_names == {"PENDING", "SHIPPED", "DELIVERED"} def test_enum_attribute_type_preserved(self, class_diagram_with_enum_json): - """An attribute typed with an enumeration survives the roundtrip.""" domain_model = process_class_diagram(class_diagram_with_enum_json) result = class_buml_to_json(domain_model) - - result_elements = result["elements"] - # Find the Order class's 'status' attribute - for e in result_elements.values(): - if e.get("type") == "ClassAttribute" and e.get("name") == "status": - assert e["attributeType"] == "OrderStatus" - break - else: - pytest.fail("Could not find 'status' attribute in result JSON") + attrs = _attributes_for_class(result, "Order") + assert attrs["status"]["attributeType"] == "OrderStatus" def test_composition_preserved(self, class_diagram_with_composition_json): - """Composition relationship survives the roundtrip.""" domain_model = process_class_diagram(class_diagram_with_composition_json) result = class_buml_to_json(domain_model) - comp_rels = _extract_relationships_by_type(result, "ClassComposition") - assert len(comp_rels) == 1 - - rel = comp_rels[0] - roles = {rel["source"]["role"], rel["target"]["role"]} + comp_edges = _edges_by_type(result, "ClassComposition") + assert len(comp_edges) == 1 + edge_data = _data(comp_edges[0]) + roles = {edge_data.get("sourceRole"), edge_data.get("targetRole")} assert roles == {"company", "department"} def test_unidirectional_association(self): @@ -897,43 +751,37 @@ def test_unidirectional_association(self): json_data = { "title": "UniModel", "model": { - "elements": { - "cls-a": { - "id": "cls-a", - "name": "ClassA", - "type": "Class", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": [], - "methods": [], + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-a", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "ClassA", "stereotype": None, + "attributes": [], "methods": []}, }, - "cls-b": { - "id": "cls-b", - "name": "ClassB", - "type": "Class", - "owner": None, - "bounds": {"x": 300, "y": 0, "width": 160, "height": 100}, - "attributes": [], - "methods": [], + { + "id": "n-b", "type": "class", + "position": {"x": 300, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "ClassB", "stereotype": None, + "attributes": [], "methods": []}, }, - }, - "relationships": { - "rel-uni": { - "id": "rel-uni", - "name": "uses", + ], + "edges": [ + { + "id": "e-uni", "source": "n-a", "target": "n-b", "type": "ClassUnidirectional", - "source": { - "element": "cls-a", - "multiplicity": "1", - "role": "classA", - }, - "target": { - "element": "cls-b", - "multiplicity": "0..1", - "role": "classB", + "sourceHandle": "Right", "targetHandle": "Left", + "data": { + "name": "uses", + "sourceRole": "classA", "sourceMultiplicity": "1", + "targetRole": "classB", "targetMultiplicity": "0..1", + "points": [], }, }, - }, + ], }, } domain_model = process_class_diagram(json_data) @@ -941,154 +789,222 @@ def test_unidirectional_association(self): # A legacy ClassUnidirectional comes back as ClassBidirectional with explicit # per-end navigability (source non-navigable), orientation unchanged. - assert _extract_relationships_by_type(result, "ClassUnidirectional") == [] - rels = _extract_relationships_by_type(result, "ClassBidirectional") - assert len(rels) == 1 - assert rels[0]["name"] == "uses" - assert rels[0]["source"]["role"] == "classA" and rels[0]["source"]["navigable"] is False - assert rels[0]["target"]["role"] == "classB" and rels[0]["target"]["navigable"] is True + assert _edges_by_type(result, "ClassUnidirectional") == [] + bi_edges = _edges_by_type(result, "ClassBidirectional") + assert len(bi_edges) == 1 + edge_data = _data(bi_edges[0]) + assert edge_data.get("name") == "uses" + assert edge_data["sourceRole"] == "classA" and edge_data["sourceNavigable"] is False + assert edge_data["targetRole"] == "classB" and edge_data["targetNavigable"] is True def test_diagram_type_preserved(self, minimal_class_diagram_json): - """The output JSON has the correct diagram type.""" domain_model = process_class_diagram(minimal_class_diagram_json) result = class_buml_to_json(domain_model) assert result["type"] == "ClassDiagram" def test_double_roundtrip_stable(self, minimal_class_diagram_json): - """Two consecutive roundtrips produce equivalent essential data.""" - # First roundtrip dm1 = process_class_diagram(minimal_class_diagram_json) json1 = class_buml_to_json(dm1) - # Second roundtrip: wrap in expected format json1_input = {"title": "LibraryModel", "model": json1} dm2 = process_class_diagram(json1_input) json2 = class_buml_to_json(dm2) - # Compare essential data - assert _get_class_names(json1) == _get_class_names(json2) - assert _get_enum_names(json1) == _get_enum_names(json2) - for cls_name in _get_class_names(json1): - assert _get_attribute_names_for_class(json1, cls_name) == \ - _get_attribute_names_for_class(json2, cls_name) - assert _get_method_names_for_class(json1, cls_name) == \ - _get_method_names_for_class(json2, cls_name) + assert _all_class_names(json1) == _all_class_names(json2) + assert _class_names_by_kind(json1, enumeration=True) == \ + _class_names_by_kind(json2, enumeration=True) + for cls_name in _all_class_names(json1): + assert _attribute_names_for_class(json1, cls_name) == \ + _attribute_names_for_class(json2, cls_name) + assert _method_names_for_class(json1, cls_name) == \ + _method_names_for_class(json2, cls_name) def test_method_with_code_roundtrip(self): - """Method code attribute survives the roundtrip.""" json_data = { "title": "CodeModel", "model": { - "elements": { - "cls-calc": { - "id": "cls-calc", - "name": "Calculator", - "type": "Class", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": [], - "methods": ["meth-add"], - }, - "meth-add": { - "id": "meth-add", - "name": "+ add(a: int, b: int): int", - "type": "ClassMethod", - "owner": "cls-calc", - "bounds": {"x": 0, "y": 40, "width": 159, "height": 30}, - "code": "def add(self, a, b):\n return a + b", - "implementationType": "code", + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-calc", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Calculator", "stereotype": None, + "attributes": [], + "methods": [ + { + "id": "m-add", + "name": "+ add(a: int, b: int): int", + "code": "def add(self, a, b):\n return a + b", + "implementationType": "code", + }, + ], + }, }, - }, - "relationships": {}, + ], + "edges": [], }, } domain_model = process_class_diagram(json_data) result = class_buml_to_json(domain_model) - method_elems = _extract_elements_by_type(result, "ClassMethod") - assert len(method_elems) == 1 - assert method_elems[0].get("code") == "def add(self, a, b):\n return a + b" - assert method_elems[0].get("implementationType") == "code" + calc_node = _class_node_by_name(result, "Calculator") + methods = _data(calc_node).get("methods") or [] + assert len(methods) == 1 + assert methods[0].get("code") == "def add(self, a, b):\n return a + b" + assert methods[0].get("implementationType") == "code" + + def test_abstract_stereotype_emitted_capitalized(self, class_diagram_with_inheritance_json): + """The frontend compares stereotypes case-sensitively against the + capitalized canonical forms — emit exactly 'Abstract' (the + processor keeps reading case-insensitively, so lowercase input + still ingests).""" + domain_model = process_class_diagram(class_diagram_with_inheritance_json) + result = class_buml_to_json(domain_model) + vehicle = _class_node_by_name(result, "Vehicle") + assert _data(vehicle).get("stereotype") == "Abstract" + + def test_enumeration_stereotype_emitted_capitalized(self, class_diagram_with_enum_json): + domain_model = process_class_diagram(class_diagram_with_enum_json) + result = class_buml_to_json(domain_model) + status = _class_node_by_name(result, "OrderStatus") + assert _data(status).get("stereotype") == "Enumeration" + + def test_comment_round_trip(self, minimal_class_diagram_json): + """``comment`` nodes tethered by ``CommentLink`` edges land on the + class metadata, which re-emits as the class's ``data.description``. + + B-UML keeps one description per class, so a linked comment and the + inspector's description field cannot both come back; the field the + class inspector edits wins.""" + model = minimal_class_diagram_json["model"] + model["nodes"].append({ + "id": "n-note", + "type": "comment", + "position": {"x": -300, "y": 0}, + "width": 160, "height": 75, + "measured": {"width": 160, "height": 75}, + "data": {"name": "Books are the unit of lending."}, + }) + model["edges"].append({ + "id": "e-note", + "source": "n-note", + "target": "n-book", + "type": "CommentLink", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"points": []}, + }) + + domain_model = process_class_diagram(minimal_class_diagram_json) + book = next(t for t in domain_model.types if t.name == "Book") + assert book.metadata is not None + assert book.metadata.description == "Books are the unit of lending." + + result = class_buml_to_json(domain_model) + book_node = _class_node_by_name(result, "Book") + assert _data(book_node).get("description") == "Books are the unit of lending." + assert _nodes_by_type(result, "comment") == [] + assert _edges_by_type(result, "CommentLink") == [] + + def test_legacy_comments_link_spelling_still_ingests(self, minimal_class_diagram_json): + """Older fixtures use ``Comments`` / ``Link`` — keep accepting them.""" + model = minimal_class_diagram_json["model"] + model["nodes"].append({ + "id": "n-note", + "type": "Comments", + "position": {"x": -300, "y": 0}, + "width": 160, "height": 75, + "measured": {"width": 160, "height": 75}, + "data": {"name": "Legacy note."}, + }) + model["edges"].append({ + "id": "e-note", + "source": "n-note", + "target": "n-book", + "type": "Link", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"points": []}, + }) + domain_model = process_class_diagram(minimal_class_diagram_json) + book = next(t for t in domain_model.types if t.name == "Book") + assert book.metadata is not None + assert book.metadata.description == "Legacy note." def test_method_with_neural_network_roundtrip(self): """A method implemented by a neural network keeps its type and NN reference.""" json_data = { "title": "NNModel", "model": { - "elements": { - "cls-classifier": { - "id": "cls-classifier", - "name": "ImageClassifier", - "type": "Class", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": [], - "methods": ["meth-predict"], - }, - "meth-predict": { - "id": "meth-predict", - "name": "+ predict(image: str): str", - "type": "ClassMethod", - "owner": "cls-classifier", - "bounds": {"x": 0, "y": 40, "width": 159, "height": 30}, - "implementationType": "neural_network", - "neuralNetworkId": "nn-diagram-1", + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "cls-classifier", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "ImageClassifier", "stereotype": None, + "attributes": [], + "methods": [ + { + "id": "meth-predict", "name": "predict", + "visibility": "public", + "parameters": [{"id": "p-image", "name": "image", "parameterType": "str"}], + "returnType": "str", "attributeType": "str", + "implementationType": "neural_network", + "neuralNetworkId": "nn-diagram-1", + }, + ], + }, }, - }, - "relationships": {}, + ], + "edges": [], }, } domain_model = process_class_diagram(json_data) method = next(iter(domain_model.get_class_by_name("ImageClassifier").methods)) assert method.implementation_type == MethodImplementationType.NEURAL_NETWORK + assert domain_model.method_diagram_refs[("ImageClassifier", "predict")]["neuralNetworkId"] == "nn-diagram-1" result = class_buml_to_json(domain_model) - method_elems = _extract_elements_by_type(result, "ClassMethod") - assert len(method_elems) == 1 - assert method_elems[0].get("implementationType") == "neural_network" - assert method_elems[0].get("neuralNetworkId") == "nn-diagram-1" - assert "quantumCircuitId" not in method_elems[0] + methods = _data(_class_node_by_name(result, "ImageClassifier"))["methods"] + assert len(methods) == 1 + assert methods[0].get("implementationType") == "neural_network" + assert methods[0].get("neuralNetworkId") == "nn-diagram-1" + assert "quantumCircuitId" not in methods[0] def test_attribute_default_value_preserved(self): - """Attribute default values survive the roundtrip.""" json_data = { "title": "DefaultsModel", "model": { - "elements": { - "cls-config": { - "id": "cls-config", - "name": "Config", - "type": "Class", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": ["attr-retries"], - "methods": [], - }, - "attr-retries": { - "id": "attr-retries", - "name": "retries", - "type": "ClassAttribute", - "owner": "cls-config", - "visibility": "public", - "attributeType": "int", - "isOptional": False, - "defaultValue": "3", - "bounds": {"x": 0, "y": 40, "width": 159, "height": 30}, + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-config", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Config", "stereotype": None, + "attributes": [ + {"id": "a-retries", "name": "retries", "attributeType": "int", + "visibility": "public", "isOptional": False, "defaultValue": "3"}, + ], + "methods": [], + }, }, - }, - "relationships": {}, + ], + "edges": [], }, } domain_model = process_class_diagram(json_data) result = class_buml_to_json(domain_model) - - result_elements = result["elements"] - for e in result_elements.values(): - if e.get("type") == "ClassAttribute" and e.get("name") == "retries": - assert e.get("defaultValue") == "3" - break - else: - pytest.fail("Could not find 'retries' attribute in result JSON") + attrs = _attributes_for_class(result, "Config") + assert attrs["retries"].get("defaultValue") == "3" # =========================================================================== @@ -1099,32 +1015,33 @@ def test_attribute_default_value_preserved(self): def _with_writes_relationship(diagram_json, rel_type, source_navigable=_OMIT, target_navigable=_OMIT): - """Return a copy of *diagram_json* whose Author -> Book 'writes' relationship has the - given type and per-end ``navigable`` values (``_OMIT`` leaves the key out, as legacy payloads do).""" + """Return a copy of *diagram_json* whose Author -> Book 'writes' edge has the given + type and per-end ``sourceNavigable`` / ``targetNavigable`` values (``_OMIT`` leaves + the key out, as legacy payloads do).""" data = json.loads(json.dumps(diagram_json)) - rel = data["model"]["relationships"]["rel-writes"] - rel["type"] = rel_type + edge = next(e for e in data["model"]["edges"] if e["id"] == "e-writes") + edge["type"] = rel_type if source_navigable is not _OMIT: - rel["source"]["navigable"] = source_navigable + edge["data"]["sourceNavigable"] = source_navigable if target_navigable is not _OMIT: - rel["target"]["navigable"] = target_navigable + edge["data"]["targetNavigable"] = target_navigable return data def _roundtrip_writes(diagram_json): - """Run JSON -> BUML -> JSON and return (domain_model, the single output association relationship).""" + """Run JSON -> BUML -> JSON and return (domain_model, the single output association edge).""" domain_model = process_class_diagram(diagram_json) result = class_buml_to_json(domain_model) - elements = result["elements"] - rels = [ - r for r in result["relationships"].values() - if r.get("type") in ("ClassBidirectional", "ClassUnidirectional", "ClassComposition", "ClassAggregation") + nodes_by_id = {n["id"]: n for n in _nodes(result)} + edges = [ + e for e in _edges(result) + if e.get("type") in ("ClassBidirectional", "ClassUnidirectional", "ClassComposition", "ClassAggregation") ] - assert len(rels) == 1 - rel = rels[0] - rel["_source_class"] = elements[rel["source"]["element"]]["name"] - rel["_target_class"] = elements[rel["target"]["element"]]["name"] - return domain_model, rel + assert len(edges) == 1 + edge = edges[0] + edge["_source_class"] = _data(nodes_by_id[edge["source"]])["name"] + edge["_target_class"] = _data(nodes_by_id[edge["target"]])["name"] + return domain_model, edge class TestAssociationNavigabilityRoundtrip: @@ -1134,8 +1051,10 @@ class TestAssociationNavigabilityRoundtrip: ("ClassBidirectional", True, True, "ClassBidirectional", True, True), ("ClassBidirectional", False, True, "ClassBidirectional", False, True), ("ClassBidirectional", True, False, "ClassBidirectional", True, False), - # Legacy payload without "navigable": ClassUnidirectional => source non-navigable + # Legacy payload without the flags: ClassUnidirectional => source non-navigable ("ClassUnidirectional", _OMIT, _OMIT, "ClassBidirectional", False, True), + # Legacy payload without the flags: plain association => both navigable + ("ClassBidirectional", _OMIT, _OMIT, "ClassBidirectional", True, True), ("ClassComposition", True, True, "ClassComposition", True, True), # Composition whose composite (whole, target) end is non-navigable ("ClassComposition", True, False, "ClassComposition", True, False), @@ -1147,32 +1066,46 @@ def test_navigability_and_orientation_preserved( self, minimal_class_diagram_json, in_type, src_nav, tgt_nav, out_type, out_src, out_tgt ): payload = _with_writes_relationship(minimal_class_diagram_json, in_type, src_nav, tgt_nav) - domain_model, rel = _roundtrip_writes(payload) + domain_model, edge = _roundtrip_writes(payload) + edge_data = _data(edge) - assert rel["type"] == out_type - assert rel["source"]["navigable"] is out_src - assert rel["target"]["navigable"] is out_tgt + assert edge["type"] == out_type + assert edge_data["sourceNavigable"] is out_src + assert edge_data["targetNavigable"] is out_tgt # Orientation as drawn: Author (role "author") is the source, Book (role "book") the target - assert (rel["_source_class"], rel["source"]["role"]) == ("Author", "author") - assert (rel["_target_class"], rel["target"]["role"]) == ("Book", "book") + assert (edge["_source_class"], edge_data["sourceRole"]) == ("Author", "author") + assert (edge["_target_class"], edge_data["targetRole"]) == ("Book", "book") assert domain_model.ocl_warnings == [] + def test_navigability_maps_to_metamodel_ends(self, minimal_class_diagram_json): + payload = _with_writes_relationship(minimal_class_diagram_json, "ClassBidirectional", False, True) + domain_model = process_class_diagram(payload) + assoc = next(a for a in domain_model.associations if a.name == "writes") + by_name = {end.name: end for end in assoc.ends} + assert by_name["author"].is_navigable is False + assert by_name["book"].is_navigable is True + def test_saved_endpoint_layout_stays_on_its_end(self, minimal_class_diagram_json): - """A one-way association keeps each saved endpoint layout on the end it was drawn on.""" + """A one-way association keeps each saved endpoint handle on the end it was drawn on, + even when the drawn source sorts after the target.""" payload = _with_writes_relationship(minimal_class_diagram_json, "ClassBidirectional", True, False) - rel_in = payload["model"]["relationships"]["rel-writes"] - rel_in["bounds"] = {"x": 160, "y": 40, "width": 140, "height": 1} - rel_in["path"] = [{"x": 0, "y": 0}, {"x": 140, "y": 0}] - rel_in["source"].update(direction="Left", bounds={"x": 300, "y": 40, "width": 0, "height": 0}) - rel_in["target"].update(direction="Right", bounds={"x": 160, "y": 40, "width": 0, "height": 0}) - - _, rel = _roundtrip_writes(payload) - assert rel["_source_class"] == "Author" - assert rel["source"]["direction"] == "Left" - assert rel["source"]["bounds"] == {"x": 300, "y": 40, "width": 0, "height": 0} - assert rel["_target_class"] == "Book" - assert rel["target"]["direction"] == "Right" - assert rel["target"]["bounds"] == {"x": 160, "y": 40, "width": 0, "height": 0} + edge_in = next(e for e in payload["model"]["edges"] if e["id"] == "e-writes") + # Draw Book -> Author (the roles sort the other way round). + edge_in["source"], edge_in["target"] = "n-book", "n-author" + edge_in["data"]["sourceRole"], edge_in["data"]["targetRole"] = "book", "author" + edge_in["sourceHandle"], edge_in["targetHandle"] = "Left", "Right" + edge_in["data"]["points"] = [{"x": 0, "y": 0}, {"x": 140, "y": 0}] + + _, edge = _roundtrip_writes(payload) + edge_data = _data(edge) + assert edge["_source_class"] == "Book" + assert edge_data["sourceRole"] == "book" + assert edge_data["sourceNavigable"] is True + assert edge["sourceHandle"] == "left" # legacy capitalised handle comes back as the v4 id + assert edge["_target_class"] == "Author" + assert edge_data["targetNavigable"] is False + assert edge["targetHandle"] == "right" + assert edge_data["points"] == [{"x": 0, "y": 0}, {"x": 140, "y": 0}] @pytest.mark.parametrize("class_name, role", [ ("Author", "author"), @@ -1185,49 +1118,52 @@ def test_orientation_survives_a_buml_script_roundtrip(self, minimal_class_diagra """An exported .py carries no saved layout, so the drawn source/target was re-chosen by end name: renaming a class could flip which side an association is drawn from (#679).""" payload = _with_writes_relationship(minimal_class_diagram_json, "ClassBidirectional", True, True) - payload["model"]["elements"]["cls-author"]["name"] = class_name - payload["model"]["relationships"]["rel-writes"]["source"]["role"] = role + edge = next(e for e in payload["model"]["edges"] if e["id"] == "e-writes") + author = next(n for n in payload["model"]["nodes"] if n["id"] == edge["source"]) + author["data"]["name"] = class_name + edge["data"]["sourceRole"] = role script = tmp_path / "model.py" domain_model_to_code(process_class_diagram(payload), str(script)) result = class_buml_to_json(parse_buml_content(script.read_text())) - rel = next(r for r in result["relationships"].values() if r.get("type") == "ClassBidirectional") - source = result["elements"][rel["source"]["element"]]["name"] - target = result["elements"][rel["target"]["element"]]["name"] - assert (source, rel["source"]["role"], rel["source"]["multiplicity"]) == ( + names = {n["id"]: _data(n)["name"] for n in _nodes(result)} + rel = next(e for e in _edges(result) if e.get("type") == "ClassBidirectional") + rel_data = _data(rel) + assert (names[rel["source"]], rel_data["sourceRole"], rel_data["sourceMultiplicity"]) == ( class_name, role or class_name.lower(), "1..*") - assert (target, rel["target"]["role"], rel["target"]["multiplicity"]) == ("Book", "book", "0..*") + assert (names[rel["target"]], rel_data["targetRole"], rel_data["targetMultiplicity"]) == ( + "Book", "book", "0..*") def test_no_navigable_end_is_corrected_with_warning(self, minimal_class_diagram_json): payload = _with_writes_relationship(minimal_class_diagram_json, "ClassBidirectional", False, False) - domain_model, rel = _roundtrip_writes(payload) + domain_model, edge = _roundtrip_writes(payload) - assert rel["source"]["navigable"] is False - assert rel["target"]["navigable"] is True - assert any("rel-writes" in w and "at least one end must be navigable" in w + assert _data(edge)["sourceNavigable"] is False + assert _data(edge)["targetNavigable"] is True + assert any("e-writes" in w and "at least one end must be navigable" in w for w in domain_model.ocl_warnings) def test_composition_part_end_non_navigable_is_corrected_with_warning(self, minimal_class_diagram_json): payload = _with_writes_relationship(minimal_class_diagram_json, "ClassComposition", False, True) - domain_model, rel = _roundtrip_writes(payload) + domain_model, edge = _roundtrip_writes(payload) - assert rel["type"] == "ClassComposition" - assert rel["source"]["navigable"] is True - assert rel["target"]["navigable"] is True - assert any("rel-writes" in w and "part (source) end of a composition must be navigable" in w + assert edge["type"] == "ClassComposition" + assert _data(edge)["sourceNavigable"] is True + assert _data(edge)["targetNavigable"] is True + assert any("e-writes" in w and "part (source) end of a composition must be navigable" in w for w in domain_model.ocl_warnings) @pytest.mark.parametrize("bad_value", ["false", None, 0, "true"]) def test_non_bool_navigable_falls_back_with_warning(self, minimal_class_diagram_json, bad_value): - """A non-boolean ``navigable`` is not coerced (``"false"`` must not become True): the legacy - default for the relationship type is used and a warning is recorded.""" + """A non-boolean ``sourceNavigable`` is not coerced (``"false"`` must not become True): + the legacy default for the relationship type is used and a warning is recorded.""" payload = _with_writes_relationship(minimal_class_diagram_json, "ClassUnidirectional", bad_value, True) - domain_model, rel = _roundtrip_writes(payload) + domain_model, edge = _roundtrip_writes(payload) # Legacy default for a ClassUnidirectional source end is non-navigable - assert rel["source"]["navigable"] is False - assert rel["target"]["navigable"] is True - assert any("rel-writes" in w and "source 'navigable' must be true or false" in w + assert _data(edge)["sourceNavigable"] is False + assert _data(edge)["targetNavigable"] is True + assert any("e-writes" in w and "sourceNavigable must be true or false" in w for w in domain_model.ocl_warnings) @@ -1239,194 +1175,242 @@ class TestStateMachineRoundtrip: """JSON -> BUML -> JSON roundtrip for state machine diagrams.""" def test_states_preserved(self, state_machine_json): - """State names survive the roundtrip.""" sm = process_state_machine(state_machine_json) result = state_machine_object_to_json(sm) - - state_elems = _extract_elements_by_type(result, "State") - state_names = {s["name"] for s in state_elems} - assert state_names == {"idle", "processing"} + states = _nodes_by_type(result, "State") + names = {(_data(s).get("name") or "") for s in states} + assert names == {"idle", "processing"} def test_initial_state_preserved(self, state_machine_json): - """The initial state marker survives the roundtrip.""" sm = process_state_machine(state_machine_json) result = state_machine_object_to_json(sm) - # There should be a StateInitialNode - initial_nodes = _extract_elements_by_type(result, "StateInitialNode") + initial_nodes = _nodes_by_type(result, "StateInitialNode") assert len(initial_nodes) == 1 + initial_id = initial_nodes[0]["id"] - # There should be a transition from the initial node to a state - transitions = _extract_relationships_by_type(result, "StateTransition") - initial_transitions = [ - t for t in transitions - if result["elements"].get(t["source"]["element"], {}).get("type") == "StateInitialNode" - ] - assert len(initial_transitions) == 1 + transitions = _edges_by_type(result, "StateTransition") + from_initial = [t for t in transitions if t["source"] == initial_id] + assert len(from_initial) == 1 - # The target of the initial transition should be "idle" - target_id = initial_transitions[0]["target"]["element"] - target_elem = result["elements"][target_id] - assert target_elem["name"] == "idle" + target_node = _node_by_id(result, from_initial[0]["target"]) + assert _data(target_node).get("name") == "idle" def test_transitions_preserved(self, state_machine_json): - """Non-initial transitions survive the roundtrip.""" sm = process_state_machine(state_machine_json) result = state_machine_object_to_json(sm) - transitions = _extract_relationships_by_type(result, "StateTransition") - # Filter out initial node transitions - state_transitions = [ - t for t in transitions - if result["elements"].get(t["source"]["element"], {}).get("type") != "StateInitialNode" + initial_ids = {n["id"] for n in _nodes_by_type(result, "StateInitialNode")} + transitions = [ + t for t in _edges_by_type(result, "StateTransition") + if t["source"] not in initial_ids ] - assert len(state_transitions) == 1 - - t = state_transitions[0] - assert t["name"] == "start_event" + assert len(transitions) == 1 + t = transitions[0] + assert _data(t).get("name") == "start_event" - # Source should be "idle", target should be "processing" - source_elem = result["elements"][t["source"]["element"]] - target_elem = result["elements"][t["target"]["element"]] - assert source_elem["name"] == "idle" - assert target_elem["name"] == "processing" + source_node = _node_by_id(result, t["source"]) + target_node = _node_by_id(result, t["target"]) + assert _data(source_node).get("name") == "idle" + assert _data(target_node).get("name") == "processing" def test_bodies_preserved(self, state_machine_json): - """State body associations survive the roundtrip.""" sm = process_state_machine(state_machine_json) result = state_machine_object_to_json(sm) - # Check that states have their body references - state_elems = _extract_elements_by_type(result, "State") - for state in state_elems: - if state["name"] == "idle": - body_ids = state.get("bodies", []) - assert len(body_ids) == 1 - body_elem = result["elements"][body_ids[0]] - assert body_elem["name"] == "idle_body" - assert body_elem["type"] == "StateBody" - elif state["name"] == "processing": - body_ids = state.get("bodies", []) - assert len(body_ids) == 1 - body_elem = result["elements"][body_ids[0]] - assert body_elem["name"] == "process_body" - assert body_elem["type"] == "StateBody" + for state in _nodes_by_type(result, "State"): + data = _data(state) + bodies = data.get("bodies") or [] + if data.get("name") == "idle": + assert len(bodies) == 1 + assert bodies[0].get("name") == "idle_body" + elif data.get("name") == "processing": + assert len(bodies) == 1 + assert bodies[0].get("name") == "process_body" def test_code_blocks_preserved(self, state_machine_json): - """Code block elements (body and event functions) survive the roundtrip.""" sm = process_state_machine(state_machine_json) result = state_machine_object_to_json(sm) - code_blocks = _extract_elements_by_type(result, "StateCodeBlock") - code_names = {cb["name"] for cb in code_blocks} - - # Body functions - assert "idle_body" in code_names - assert "process_body" in code_names - # Event function - assert "start_event" in code_names + code_blocks = _nodes_by_type(result, "StateCodeBlock") + names = {_data(cb).get("name") for cb in code_blocks} + assert "idle_body" in names + assert "process_body" in names + assert "start_event" in names def test_code_block_content_preserved(self, state_machine_json): - """Code block source code survives the roundtrip.""" sm = process_state_machine(state_machine_json) result = state_machine_object_to_json(sm) - code_blocks = _extract_elements_by_type(result, "StateCodeBlock") - for cb in code_blocks: - if cb["name"] == "idle_body": - assert "idle_body" in cb["code"] - assert "session.reply" in cb["code"] - elif cb["name"] == "process_body": - assert "process_body" in cb["code"] - assert "Processing" in cb["code"] - elif cb["name"] == "start_event": - assert "start_event" in cb["code"] - assert "session.message" in cb["code"] + for cb in _nodes_by_type(result, "StateCodeBlock"): + data = _data(cb) + name = data.get("name") + code = data.get("code") or "" + if name == "idle_body": + assert "idle_body" in code + assert "session.reply" in code + elif name == "process_body": + assert "process_body" in code + assert "Processing" in code + elif name == "start_event": + assert "start_event" in code + assert "session.message" in code def test_diagram_type_preserved(self, state_machine_json): - """The output JSON has the correct diagram type.""" sm = process_state_machine(state_machine_json) result = state_machine_object_to_json(sm) assert result["type"] == "StateMachineDiagram" def test_state_machine_with_guard(self): - """Transition guard conditions survive the roundtrip.""" json_data = { "title": "GuardTest", "model": { - "elements": { - "initial": { - "id": "initial", - "name": "", - "type": "StateInitialNode", - "owner": None, - "bounds": {"x": -850, "y": -280, "width": 45, "height": 45}, + "version": "4.0.0", + "type": "StateMachineDiagram", + "nodes": [ + { + "id": "n-init", "type": "StateInitialNode", + "position": {"x": -850, "y": -280}, + "width": 45, "height": 45, + "measured": {"width": 45, "height": 45}, + "data": {"name": ""}, }, - "state-a": { - "id": "state-a", - "name": "stateA", - "type": "State", - "owner": None, - "bounds": {"x": -550, "y": -300, "width": 160, "height": 100}, - "bodies": [], - "fallbackBodies": [], + { + "id": "n-a", "type": "State", + "position": {"x": -550, "y": -300}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "stateA", "bodies": [], "fallbackBodies": []}, }, - "state-b": { - "id": "state-b", - "name": "stateB", - "type": "State", - "owner": None, - "bounds": {"x": -60, "y": -300, "width": 160, "height": 100}, - "bodies": [], - "fallbackBodies": [], + { + "id": "n-b", "type": "State", + "position": {"x": -60, "y": -300}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "stateB", "bodies": [], "fallbackBodies": []}, }, - }, - "relationships": { - "trans-init": { - "id": "trans-init", - "name": "", + ], + "edges": [ + { + "id": "t-init", "source": "n-init", "target": "n-a", "type": "StateTransition", - "source": {"element": "initial"}, - "target": {"element": "state-a"}, + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "", "points": []}, }, - "trans-guarded": { - "id": "trans-guarded", - "name": "trigger_event", + { + "id": "t-guard", "source": "n-a", "target": "n-b", "type": "StateTransition", - "source": {"element": "state-a"}, - "target": {"element": "state-b"}, - "guard": "x > 10", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "trigger_event", "guard": "x > 10", "points": []}, }, - }, + ], }, } sm = process_state_machine(json_data) result = state_machine_object_to_json(sm) - transitions = _extract_relationships_by_type(result, "StateTransition") - guarded = [t for t in transitions if t.get("guard")] + guarded = [t for t in _edges_by_type(result, "StateTransition") if _data(t).get("guard")] assert len(guarded) == 1 - assert guarded[0]["guard"] == "x > 10" - assert guarded[0]["name"] == "trigger_event" + assert _data(guarded[0]).get("guard") == "x > 10" + assert _data(guarded[0]).get("name") == "trigger_event" + + def test_guarded_transitions_survive_the_python_round_trip(self): + """Importing the exported B-UML ``.py`` kept only plain + ``when_event(..).go_to(..)`` transitions: guarded ones vanished.""" + from besser.utilities.buml_code_builder.state_machine_builder import state_machine_to_code + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.state_machine_converter import ( + state_machine_to_json, + ) + + def state(node_id, name): + return {"id": node_id, "type": "State", "position": {"x": 0, "y": 0}, + "width": 160, "height": 40, "data": {"name": name, "bodies": [], "fallbackBodies": []}} + + def transition(edge_id, source, target, data): + return {"id": edge_id, "source": source, "target": target, "type": "StateTransition", + "data": {"points": [], **data}} + + json_data = {"title": "Guards", "model": { + "version": "4.0.0", "type": "StateMachineDiagram", + "nodes": [ + {"id": "i", "type": "StateInitialNode", "position": {"x": 0, "y": 0}, "data": {"name": ""}}, + state("a", "Idle"), state("b", "Busy"), state("c", "Done"), + {"id": "g", "type": "StateCodeBlock", "position": {"x": 0, "y": 0}, + "data": {"name": "", "code": "def is_ready(session):\n return True", "language": "python"}}, + ], + "edges": [ + transition("t0", "i", "a", {"name": ""}), + transition("t1", "a", "b", {"name": "start", "guard": "is_ready"}), + transition("t2", "b", "c", {"name": "", "guard": "is_ready"}), + ], + }} + code = state_machine_to_code(process_state_machine(json_data)) + result = state_machine_to_json(code) + + names = {n["id"]: _data(n).get("name") for n in result["nodes"]} + guarded = sorted( + (names[e["source"]], names[e["target"]], _data(e).get("name") or "", _data(e).get("guard")) + for e in _edges_by_type(result, "StateTransition") + if _data(e).get("guard") + ) + assert guarded == [("Busy", "Done", "", "is_ready"), ("Idle", "Busy", "start", "is_ready")] + + def test_comment_round_trip(self, state_machine_json): + """``comment`` nodes tethered by ``CommentLink`` edges land on the + state metadata and re-emit with the same node / edge types.""" + model = state_machine_json["model"] + model["nodes"].append({ + "id": "n-note", + "type": "comment", + "position": {"x": -900, "y": -500}, + "width": 160, "height": 75, + "measured": {"width": 160, "height": 75}, + "data": {"name": "Waits for the next order."}, + }) + model["edges"].append({ + "id": "e-note", + "source": "n-note", + "target": "n-idle", + "type": "CommentLink", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": {"points": []}, + }) + + sm = process_state_machine(state_machine_json) + idle = next(s for s in sm.states if s.name == "idle") + assert idle.metadata is not None + assert idle.metadata.description == "Waits for the next order." + + result = state_machine_object_to_json(sm) + comments = _nodes_by_type(result, "comment") + assert [_data(c).get("name") for c in comments] == [ + "Waits for the next order.", + ] + links = _edges_by_type(result, "CommentLink") + assert len(links) == 1 + linked = {links[0]["source"], links[0]["target"]} + assert comments[0]["id"] in linked + idle_node = next( + n for n in _nodes_by_type(result, "State") + if _data(n).get("name") == "idle" + ) + assert idle_node["id"] in linked def test_double_roundtrip_stable(self, state_machine_json): - """Two consecutive roundtrips produce equivalent essential data.""" - # First roundtrip sm1 = process_state_machine(state_machine_json) json1 = state_machine_object_to_json(sm1) - # Second roundtrip json1_input = {"title": "OrderStateMachine", "model": json1} sm2 = process_state_machine(json1_input) json2 = state_machine_object_to_json(sm2) - # Compare essential data - states1 = {s["name"] for s in _extract_elements_by_type(json1, "State")} - states2 = {s["name"] for s in _extract_elements_by_type(json2, "State")} + states1 = {_data(s).get("name") for s in _nodes_by_type(json1, "State")} + states2 = {_data(s).get("name") for s in _nodes_by_type(json2, "State")} assert states1 == states2 - code1 = {cb["name"] for cb in _extract_elements_by_type(json1, "StateCodeBlock")} - code2 = {cb["name"] for cb in _extract_elements_by_type(json2, "StateCodeBlock")} + code1 = {_data(cb).get("name") for cb in _nodes_by_type(json1, "StateCodeBlock")} + code2 = {_data(cb).get("name") for cb in _nodes_by_type(json2, "StateCodeBlock")} assert code1 == code2 @@ -1437,55 +1421,47 @@ def test_double_roundtrip_stable(self, state_machine_json): class TestObjectDiagramRoundtrip: """JSON -> BUML roundtrip for object diagrams. - Since there is no ObjectModel-to-JSON converter that works from the - metamodel object, these tests verify that the BUML ObjectModel produced - from JSON contains the correct data rather than doing a full roundtrip. - - Note: Some tests are marked xfail because DataValue.__init__ passes - name="" to NamedElement which now rejects empty names. This is a - pre-existing bug (DataValue default name conflicts with NamedElement - validation), not specific to the converter code. + No metamodel-to-JSON converter exists for ObjectModel that runs without + parsing generated code, so these tests verify that the BUML ObjectModel + produced from JSON contains the correct data. """ def test_objects_created(self, object_diagram_json, minimal_class_diagram_json): - """Objects (without attribute slots) are created from the JSON input.""" domain_model = process_class_diagram(minimal_class_diagram_json) obj_model = process_object_diagram(object_diagram_json, domain_model) - obj_names = {obj.name for obj in obj_model.objects} - assert "book1" in obj_names - assert "author1" in obj_names + # The processor preserves the full ``"name : Class"`` label. + names = {obj.name or "" for obj in obj_model.objects} + assert any("book1" in n for n in names) + assert any("author1" in n for n in names) def test_object_classifiers(self, object_diagram_json, minimal_class_diagram_json): - """Objects have the correct classifier (class) assigned.""" domain_model = process_class_diagram(minimal_class_diagram_json) obj_model = process_object_diagram(object_diagram_json, domain_model) - classifiers = {obj.name: obj.classifier.name for obj in obj_model.objects} - assert classifiers["book1"] == "Book" - assert classifiers["author1"] == "Author" + for obj in obj_model.objects: + label = obj.name or "" + classifier_name = obj.classifier.name + if "book1" in label: + assert classifier_name == "Book" + elif "author1" in label: + assert classifier_name == "Author" def test_object_count(self, object_diagram_json, minimal_class_diagram_json): - """The correct number of objects is created.""" domain_model = process_class_diagram(minimal_class_diagram_json) obj_model = process_object_diagram(object_diagram_json, domain_model) - assert len(obj_model.objects) == 2 def test_object_links_created(self, object_diagram_json, minimal_class_diagram_json): - """Links between objects are correctly created.""" domain_model = process_class_diagram(minimal_class_diagram_json) obj_model = process_object_diagram(object_diagram_json, domain_model) - # Collect all links from all objects all_links = set() for obj in obj_model.objects: for link in obj.links: all_links.add(link) assert len(all_links) >= 1 - - # Verify the link connects to the correct association link = next(iter(all_links)) assert link.association is not None end_types = {end.type.name for end in link.association.ends} @@ -1493,98 +1469,148 @@ def test_object_links_created(self, object_diagram_json, minimal_class_diagram_j assert "Author" in end_types def test_object_attribute_values(self, object_diagram_with_attrs_json, minimal_class_diagram_json): - """Object attribute (slot) values are correctly parsed.""" + """Canonical v4 rows keep name and runtime value in separate + fields (``ObjectNodeAttribute.value``).""" domain_model = process_class_diagram(minimal_class_diagram_json) obj_model = process_object_diagram(object_diagram_with_attrs_json, domain_model) for obj in obj_model.objects: - if obj.name == "book1": - slot_values = { - slot.attribute.name: slot.value.value - for slot in obj.slots - } + label = obj.name or "" + slot_values = {slot.attribute.name: slot.value.value for slot in obj.slots} + if "book1" in label: assert slot_values.get("title") == "TheGreatGatsby" - elif obj.name == "author1": - slot_values = { - slot.attribute.name: slot.value.value - for slot in obj.slots - } + elif "author1" in label: assert slot_values.get("name") == "Fitzgerald" - def test_user_model_equality_attribute_value(self, minimal_class_diagram_json): - """UserModelAttribute equality criteria ('==') are parsed, not dropped. + def test_object_attribute_values_legacy_combined_strings( + self, object_diagram_with_legacy_attrs_json, minimal_class_diagram_json, + ): + """Legacy rows bake ``"+ name: type = value"`` into ``name`` — + the fallback parser must keep ingesting them.""" + domain_model = process_class_diagram(minimal_class_diagram_json) + obj_model = process_object_diagram( + object_diagram_with_legacy_attrs_json, domain_model, + ) - Regression test: the editor renders equality as a single '=' (e.g. - "title = TheGreatGatsby") while storing attributeOperator as '=='. The - parser must split on the displayed symbol; otherwise every '==' - criterion falls through with an empty value ("attributes are empty"). - """ + slot_map: dict = {} + for obj in obj_model.objects: + for slot in obj.slots: + slot_map[slot.attribute.name] = slot.value.value + assert slot_map == {"title": "TheGreatGatsby", "name": "Fitzgerald"} + + def test_user_model_nodes_and_user_model_link( + self, object_diagram_json, minimal_class_diagram_json, + ): + """UserDiagram payloads use ``UserModelName`` nodes whose rows + carry ``value`` / ``defaultValue`` plus an ``attributeOperator`` + comparator, linked by ``UserModelLink`` edges — all must ingest + exactly like their Object-diagram counterparts.""" + domain_model = process_class_diagram(minimal_class_diagram_json) + model = object_diagram_json["model"] + for node in model["nodes"]: + node["type"] = "UserModelName" + model["nodes"][0]["data"]["attributes"] = [ + {"id": "ua-title", "name": "title", "attributeType": "str", + "attributeOperator": "==", "value": "TheGreatGatsby"}, + ] + model["nodes"][1]["data"]["attributes"] = [ + # ``defaultValue`` is the secondary carrier when ``value`` is + # absent (``UserModelAttributeRow``). + {"id": "ua-name", "name": "name", "attributeType": "str", + "attributeOperator": "==", "defaultValue": "Fitzgerald"}, + ] + for edge in model["edges"]: + edge["type"] = "UserModelLink" + + obj_model = process_object_diagram(object_diagram_json, domain_model) + assert len(obj_model.objects) == 2 + + slot_map: dict = {} + for obj in obj_model.objects: + for slot in obj.slots: + slot_map[slot.attribute.name] = slot.value.value + assert slot_map == {"title": "TheGreatGatsby", "name": "Fitzgerald"} + + all_links = {link for obj in obj_model.objects for link in obj.links} + assert len(all_links) >= 1 + link = next(iter(all_links)) + end_types = {end.type.name for end in link.association.ends} + assert end_types == {"Book", "Author"} + + def test_user_model_legacy_embedded_operator_string( + self, object_diagram_json, minimal_class_diagram_json, + ): + """Legacy user rows embed ``"name value"`` in ``name`` — + the comparator split must keep working as a fallback.""" domain_model = process_class_diagram(minimal_class_diagram_json) - user_diagram_json = { + model = object_diagram_json["model"] + for node in model["nodes"]: + node["type"] = "UserModelName" + model["nodes"][0]["data"]["attributes"] = [ + {"id": "ua-title", "name": "title == TheGreatGatsby", + "attributeOperator": "=="}, + ] + obj_model = process_object_diagram(object_diagram_json, domain_model) + book1 = next(o for o in obj_model.objects if "book1" in (o.name or "")) + slot_values = {s.attribute.name: s.value.value for s in book1.slots} + assert slot_values == {"title": "TheGreatGatsby"} + + @staticmethod + def _user_diagram_json(attribute_row): + """A v4 UserDiagram with one ``UserModelName`` node (``book1 : Book``).""" + return { "title": "UserProfile", "model": { + "version": "4.0.0", "type": "UserDiagram", - "elements": { - "u-book1": { - "id": "u-book1", - "name": "book1", - "type": "UserModelName", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}, - "attributes": ["u-title"], - "methods": [], - "className": "Book", - }, - "u-title": { - "id": "u-title", - "name": "title = TheGreatGatsby", - "type": "UserModelAttribute", - "owner": "u-book1", - "attributeOperator": "==", - "bounds": {"x": 0, "y": 30, "width": 199, "height": 30}, + "nodes": [ + { + "id": "u-book1", "type": "UserModelName", + "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "measured": {"width": 200, "height": 100}, + "data": { + "name": "book1", "className": "Book", + "attributes": [attribute_row], "methods": [], + }, }, - }, - "relationships": {}, + ], + "edges": [], }, } + def test_user_model_equality_attribute_value(self, minimal_class_diagram_json): + """UserModelAttribute equality criteria ('==') are parsed, not dropped. + + Regression test: the editor renders equality as a single '=' (e.g. + "title = TheGreatGatsby") while storing attributeOperator as '=='. The + parser must split on the displayed symbol; otherwise every '==' + criterion falls through with an empty value ("attributes are empty"). + """ + domain_model = process_class_diagram(minimal_class_diagram_json) + user_diagram_json = self._user_diagram_json({ + "id": "u-title", "name": "title = TheGreatGatsby", + "attributeOperator": "==", + }) obj_model = process_object_diagram(user_diagram_json, domain_model) - book = next(obj for obj in obj_model.objects if obj.name == "book1") + book = next(obj for obj in obj_model.objects if "book1" in (obj.name or "")) slot_values = {slot.attribute.name: slot.value.value for slot in book.slots} assert slot_values.get("title") == "TheGreatGatsby" def test_user_model_stored_operator_equality(self, minimal_class_diagram_json): """A manually-typed '==' criterion splits on '==', not the first '='. - Regression: the earlier fix split every '==' on the displayed '=', so - "title == TheGreatGatsby" captured "= TheGreatGatsby" as the value and - broke type conversion. The stored operator must be tried first. + Regression: splitting every '==' on the displayed '=' captured + "= TheGreatGatsby" as the value and broke type conversion. The stored + operator must be tried first. """ domain_model = process_class_diagram(minimal_class_diagram_json) - user_diagram_json = { - "title": "UserProfile", - "model": { - "type": "UserDiagram", - "elements": { - "u-book1": { - "id": "u-book1", "name": "book1", "type": "UserModelName", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}, - "attributes": ["u-title"], "methods": [], "className": "Book", - }, - "u-title": { - "id": "u-title", "name": "title == TheGreatGatsby", - "type": "UserModelAttribute", "owner": "u-book1", - "attributeOperator": "==", - "bounds": {"x": 0, "y": 30, "width": 199, "height": 30}, - }, - }, - "relationships": {}, - }, - } + user_diagram_json = self._user_diagram_json({ + "id": "u-title", "name": "title == TheGreatGatsby", + "attributeOperator": "==", + }) obj_model = process_object_diagram(user_diagram_json, domain_model) - book = next(obj for obj in obj_model.objects if obj.name == "book1") + book = next(obj for obj in obj_model.objects if "book1" in (obj.name or "")) slot_values = {slot.attribute.name: slot.value.value for slot in book.slots} assert slot_values.get("title") == "TheGreatGatsby" @@ -1593,81 +1619,111 @@ def test_user_model_blank_criterion_skipped(self, minimal_class_diagram_json): empty-valued slot (which would break type conversion / OCL evaluation). """ domain_model = process_class_diagram(minimal_class_diagram_json) - user_diagram_json = { - "title": "UserProfile", - "model": { - "type": "UserDiagram", - "elements": { - "u-book1": { - "id": "u-book1", "name": "book1", "type": "UserModelName", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}, - "attributes": ["u-title"], "methods": [], "className": "Book", - }, - "u-title": { - "id": "u-title", "name": "title = ", - "type": "UserModelAttribute", "owner": "u-book1", - "attributeOperator": "==", - "bounds": {"x": 0, "y": 30, "width": 199, "height": 30}, - }, - }, - "relationships": {}, - }, - } + user_diagram_json = self._user_diagram_json({ + "id": "u-title", "name": "title = ", "attributeOperator": "==", + }) obj_model = process_object_diagram(user_diagram_json, domain_model) - book = next(obj for obj in obj_model.objects if obj.name == "book1") + book = next(obj for obj in obj_model.objects if "book1" in (obj.name or "")) slot_names = {slot.attribute.name for slot in book.slots} assert "title" not in slot_names + def test_user_model_blank_value_row_skipped(self, minimal_class_diagram_json): + """A v4 row whose structured ``value`` is empty is skipped as well.""" + domain_model = process_class_diagram(minimal_class_diagram_json) + user_diagram_json = self._user_diagram_json({ + "id": "u-pages", "name": "pages", "attributeType": "int", + "attributeOperator": "==", "value": "", + }) + obj_model = process_object_diagram(user_diagram_json, domain_model) + book = next(obj for obj in obj_model.objects if "book1" in (obj.name or "")) + assert "pages" not in {slot.attribute.name for slot in book.slots} + # =========================================================================== -# NN Diagram Roundtrip: JSON -> NN -> JSON +# NN Diagram Roundtrip # =========================================================================== +def _nn_layer_attrs(node): + """Return the ``data.attributes`` dict on an NN layer node.""" + attrs = (node.get("data") or {}).get("attributes") or {} + return attrs if isinstance(attrs, dict) else {} + + class TestNNDiagramRoundtrip: - """Roundtrip tests for NNDiagram: JSON -> NN -> JSON preserves essential data.""" + """Roundtrip tests for NNDiagram.""" @staticmethod def _minimal_nn_json(): - """A minimal NN diagram: container + Conv2D + Linear + configuration + datasets.""" + """A minimal v4 NN diagram: container + Conv2D + Linear + configuration + datasets.""" return { "title": "TestNet", "model": { + "version": "4.0.0", "type": "NNDiagram", - "version": "3.0.0", "size": {"width": 1400, "height": 740}, - "elements": { - "c1": {"id": "c1", "type": "NNContainer", "name": "TestNet", "owner": None, "bounds": {"x": 0, "y": 0, "width": 600, "height": 200}}, - "l1": {"id": "l1", "type": "Conv2DLayer", "name": "Conv2DLayer", "owner": "c1", "bounds": {"x": 20, "y": 60, "width": 110, "height": 110}, "attributes": ["l1a1", "l1a2", "l1a3"], "methods": []}, - "l1a1": {"id": "l1a1", "type": "NameAttributeConv2D", "attributeName": "name", "value": "c1", "owner": "l1"}, - "l1a2": {"id": "l1a2", "type": "KernelDimAttributeConv2D", "attributeName": "kernel_dim", "value": "[3, 3]", "owner": "l1"}, - "l1a3": {"id": "l1a3", "type": "OutChannelsAttributeConv2D", "attributeName": "out_channels", "value": "16", "owner": "l1"}, - "l2": {"id": "l2", "type": "LinearLayer", "name": "LinearLayer", "owner": "c1", "bounds": {"x": 150, "y": 60, "width": 110, "height": 110}, "attributes": ["l2a1", "l2a2"], "methods": []}, - "l2a1": {"id": "l2a1", "type": "NameAttributeLinear", "attributeName": "name", "value": "lin", "owner": "l2"}, - "l2a2": {"id": "l2a2", "type": "OutFeaturesAttributeLinear", "attributeName": "out_features", "value": "10", "owner": "l2"}, - "cfg": {"id": "cfg", "type": "Configuration", "name": "Configuration", "owner": None, "bounds": {"x": 700, "y": 0, "width": 160, "height": 200}, "attributes": ["cfg1", "cfg2", "cfg3", "cfg4", "cfg5", "cfg6"], "methods": []}, - "cfg1": {"id": "cfg1", "type": "BatchSizeAttributeConfiguration", "attributeName": "batch_size", "value": "32", "owner": "cfg"}, - "cfg2": {"id": "cfg2", "type": "EpochsAttributeConfiguration", "attributeName": "epochs", "value": "10", "owner": "cfg"}, - "cfg3": {"id": "cfg3", "type": "LearningRateAttributeConfiguration", "attributeName": "learning_rate", "value": "0.001", "owner": "cfg"}, - "cfg4": {"id": "cfg4", "type": "OptimizerAttributeConfiguration", "attributeName": "optimizer", "value": "adam", "owner": "cfg"}, - "cfg5": {"id": "cfg5", "type": "LossFunctionAttributeConfiguration", "attributeName": "loss_function", "value": "crossentropy", "owner": "cfg"}, - "cfg6": {"id": "cfg6", "type": "MetricsAttributeConfiguration", "attributeName": "metrics", "value": "[accuracy]", "owner": "cfg"}, - "ds1": {"id": "ds1", "type": "TrainingDataset", "name": "TrainingDataset", "owner": None, "bounds": {"x": 0, "y": 400, "width": 110, "height": 110}, "attributes": ["ds1a1", "ds1a2", "ds1a3", "ds1a4", "ds1a5", "ds1a6"], "methods": []}, - "ds1a1": {"id": "ds1a1", "attributeName": "name", "value": "train", "owner": "ds1"}, - "ds1a2": {"id": "ds1a2", "attributeName": "path_data", "value": "/data/train", "owner": "ds1"}, - "ds1a3": {"id": "ds1a3", "attributeName": "task_type", "value": "multi_class", "owner": "ds1"}, - "ds1a4": {"id": "ds1a4", "attributeName": "input_format", "value": "images", "owner": "ds1"}, - "ds1a5": {"id": "ds1a5", "attributeName": "shape", "value": "[32, 32, 3]", "owner": "ds1"}, - "ds1a6": {"id": "ds1a6", "attributeName": "normalize", "value": "false", "owner": "ds1"}, - "ds2": {"id": "ds2", "type": "TestDataset", "name": "TestDataset", "owner": None, "bounds": {"x": 300, "y": 400, "width": 110, "height": 110}, "attributes": ["ds2a1", "ds2a2"], "methods": []}, - "ds2a1": {"id": "ds2a1", "attributeName": "name", "value": "test", "owner": "ds2"}, - "ds2a2": {"id": "ds2a2", "attributeName": "path_data", "value": "/data/test", "owner": "ds2"}, - }, - "relationships": { - "r1": {"id": "r1", "type": "NNNext", "source": {"element": "l1"}, "target": {"element": "l2"}, "name": "next"}, - }, - "interactive": {"elements": {}, "relationships": {}}, - "assessments": {}, + "nodes": [ + {"id": "c1", "type": "NNContainer", + "position": {"x": 0, "y": 0}, "width": 600, "height": 200, + "measured": {"width": 600, "height": 200}, + "data": {"name": "TestNet"}}, + {"id": "l1", "type": "Conv2DLayer", + "parentId": "c1", + "position": {"x": 20, "y": 60}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": "c1", + "attributes": { + "name": "c1", + "kernel_dim": "[3, 3]", + "out_channels": "16", + }}}, + {"id": "l2", "type": "LinearLayer", + "parentId": "c1", + "position": {"x": 150, "y": 60}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": "lin", + "attributes": { + "name": "lin", + "out_features": "10", + }}}, + {"id": "cfg", "type": "Configuration", + "position": {"x": 700, "y": 0}, "width": 160, "height": 200, + "measured": {"width": 160, "height": 200}, + "data": {"name": "Configuration", + "attributes": { + "batch_size": "32", + "epochs": "10", + "learning_rate": "0.001", + "optimizer": "adam", + "loss_function": "crossentropy", + "metrics": "[accuracy]", + }}}, + {"id": "ds1", "type": "TrainingDataset", + "position": {"x": 0, "y": 400}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": "TrainingDataset", + "attributes": { + "name": "train", + "path_data": "/data/train", + "task_type": "multi_class", + "input_format": "images", + "shape": "[32, 32, 3]", + "normalize": "false", + }}}, + {"id": "ds2", "type": "TestDataset", + "position": {"x": 300, "y": 400}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": "TestDataset", + "attributes": { + "name": "test", + "path_data": "/data/test", + }}}, + ], + "edges": [ + {"id": "r1", "source": "l1", "target": "l2", + "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}}, + ], }, } @@ -1681,90 +1737,91 @@ def test_diagram_type_preserved(self): def test_container_preserved(self): out = self._roundtrip(self._minimal_nn_json()) - containers = _extract_elements_by_type(out, "NNContainer") + containers = _nodes_by_type(out, "NNContainer") assert len(containers) == 1 - assert containers[0]["name"] == "TestNet" + assert _data(containers[0]).get("name") == "TestNet" def test_layers_preserved(self): out = self._roundtrip(self._minimal_nn_json()) - assert len(_extract_elements_by_type(out, "Conv2DLayer")) == 1 - assert len(_extract_elements_by_type(out, "LinearLayer")) == 1 + assert len(_nodes_by_type(out, "Conv2DLayer")) == 1 + assert len(_nodes_by_type(out, "LinearLayer")) == 1 def test_nnnext_preserved(self): out = self._roundtrip(self._minimal_nn_json()) - nexts = _extract_relationships_by_type(out, "NNNext") - assert len(nexts) == 1 + assert len(_edges_by_type(out, "NNNext")) == 1 def test_configuration_preserved(self): out = self._roundtrip(self._minimal_nn_json()) - configs = _extract_elements_by_type(out, "Configuration") + configs = _nodes_by_type(out, "Configuration") assert len(configs) == 1 - elements = _resolve_elements(out) - attr_values = {elements[aid]["attributeName"]: elements[aid]["value"] for aid in configs[0]["attributes"]} - assert attr_values["batch_size"] == "32" - assert attr_values["optimizer"] == "adam" + attrs = _nn_layer_attrs(configs[0]) + assert attrs.get("batch_size") == "32" + assert attrs.get("optimizer") == "adam" def test_training_dataset_preserved(self): out = self._roundtrip(self._minimal_nn_json()) - training = _extract_elements_by_type(out, "TrainingDataset") + training = _nodes_by_type(out, "TrainingDataset") assert len(training) == 1 - elements = _resolve_elements(out) - attrs = {elements[aid]["attributeName"]: elements[aid]["value"] for aid in training[0]["attributes"]} - assert attrs["name"] == "train" - assert attrs["path_data"] == "/data/train" - assert attrs["task_type"] == "multi_class" - assert attrs["input_format"] == "images" - assert attrs["shape"] == "[32, 32, 3]" - assert attrs["normalize"] == "false" + attrs = _nn_layer_attrs(training[0]) + assert attrs.get("name") == "train" + assert attrs.get("path_data") == "/data/train" + assert attrs.get("task_type") == "multi_class" + assert attrs.get("input_format") == "images" + assert attrs.get("shape") == "[32, 32, 3]" + assert attrs.get("normalize") == "false" def test_test_dataset_preserved(self): out = self._roundtrip(self._minimal_nn_json()) - testing = _extract_elements_by_type(out, "TestDataset") + testing = _nodes_by_type(out, "TestDataset") assert len(testing) == 1 - elements = _resolve_elements(out) - attrs = {elements[aid]["attributeName"]: elements[aid]["value"] for aid in testing[0]["attributes"]} - assert attrs["name"] == "test" - assert attrs["path_data"] == "/data/test" + attrs = _nn_layer_attrs(testing[0]) + assert attrs.get("name") == "test" + assert attrs.get("path_data") == "/data/test" assert "input_format" not in attrs def test_double_roundtrip_stable(self): - """Second roundtrip yields the same structural shape.""" - from collections import Counter first = self._roundtrip(self._minimal_nn_json()) second = self._roundtrip(first) + def counts(j): - return Counter(e.get("type") for e in _resolve_elements(j).values() if "Attribute" not in (e.get("type") or "")) + return Counter(n.get("type") for n in _nodes(j)) assert counts(first) == counts(second) def test_nn_model_to_json_is_deterministic(self): - """Identical NN input must produce byte-identical JSON across calls. - - Locks in the uuid5 + thread-local counter scheme in nn_diagram_converter. - Regression guard: if anyone reintroduces uuid.uuid4() for IDs, the two - serializations will diverge and this test fails. - """ + """Identical NN input must produce byte-identical JSON across calls.""" + import json nn = process_nn_diagram(self._minimal_nn_json()) first = json.dumps(nn_model_to_json(nn), sort_keys=True) second = json.dumps(nn_model_to_json(nn), sort_keys=True) - assert first == second, "nn_model_to_json output must be deterministic" + assert first == second def test_nnreference_cycle_is_rejected(self): - """Two NNContainers that reference each other must raise a clear error.""" cyclic = { "title": "CyclicRefs", "model": { + "version": "4.0.0", "type": "NNDiagram", - "version": "3.0.0", - "size": {"width": 1200, "height": 600}, - "elements": { - "cA": {"id": "cA", "type": "NNContainer", "name": "A", "owner": None, "bounds": {"x": 0, "y": 0, "width": 400, "height": 200}}, - "cB": {"id": "cB", "type": "NNContainer", "name": "B", "owner": None, "bounds": {"x": 500, "y": 0, "width": 400, "height": 200}}, - "rA": {"id": "rA", "type": "NNReference", "name": "ref-to-B", "owner": "cA", "referencedNN": "B", "bounds": {"x": 20, "y": 60, "width": 140, "height": 40}}, - "rB": {"id": "rB", "type": "NNReference", "name": "ref-to-A", "owner": "cB", "referencedNN": "A", "bounds": {"x": 520, "y": 60, "width": 140, "height": 40}}, - }, - "relationships": {}, - "interactive": {"elements": {}, "relationships": {}}, - "assessments": {}, + "nodes": [ + {"id": "cA", "type": "NNContainer", + "position": {"x": 0, "y": 0}, "width": 400, "height": 200, + "measured": {"width": 400, "height": 200}, + "data": {"name": "A"}}, + {"id": "cB", "type": "NNContainer", + "position": {"x": 500, "y": 0}, "width": 400, "height": 200, + "measured": {"width": 400, "height": 200}, + "data": {"name": "B"}}, + {"id": "rA", "type": "NNReference", + "parentId": "cA", + "position": {"x": 20, "y": 60}, "width": 140, "height": 40, + "measured": {"width": 140, "height": 40}, + "data": {"name": "ref-to-B", "referenceTarget": "B"}}, + {"id": "rB", "type": "NNReference", + "parentId": "cB", + "position": {"x": 520, "y": 60}, "width": 140, "height": 40, + "measured": {"width": 140, "height": 40}, + "data": {"name": "ref-to-A", "referenceTarget": "A"}}, + ], + "edges": [], }, } with pytest.raises(ValueError, match="NNReference cycle"): @@ -1773,255 +1830,201 @@ def test_nnreference_cycle_is_rejected(self): def test_padding_type_valid_roundtrips_when_explicit(self): """When the user explicitly picks padding_type='valid' (the metamodel default), the sidecar ``mark_explicit`` path must make sure the JSON - output still carries the attribute. Without sidecar gating, the legacy - ``!= 'valid'`` guard silently strips it.""" + output still carries the attribute.""" payload = self._minimal_nn_json() - conv_id = 'l1' - payload['model']['elements'][conv_id]['attributes'].append('l1pt') - payload['model']['elements']['l1pt'] = { - 'id': 'l1pt', 'type': 'PaddingTypeAttributeConv2D', - 'attributeName': 'padding_type', 'value': 'valid', 'owner': conv_id, - } + # Add padding_type='valid' to the Conv2D layer's attributes dict. + for n in payload["model"]["nodes"]: + if n["id"] == "l1": + n["data"]["attributes"]["padding_type"] = "valid" out = self._roundtrip(payload) - elements = _resolve_elements(out) - conv_elts = _extract_elements_by_type(out, 'Conv2DLayer') - assert conv_elts, 'expected at least one Conv2DLayer in output' - attr_names = { - elements[aid]['attributeName']: elements[aid]['value'] - for aid in conv_elts[0]['attributes'] - } - assert attr_names.get('padding_type') == 'valid', \ - f'padding_type=valid must round-trip when set explicitly, got {attr_names}' + convs = _nodes_by_type(out, "Conv2DLayer") + assert convs + attrs = _nn_layer_attrs(convs[0]) + assert attrs.get("padding_type") == "valid" def test_flatten_start_dim_and_end_dim_defaults_roundtrip_when_explicit(self): """Flatten layer with start_dim=1 and end_dim=-1 (both metamodel defaults) must round-trip when set explicitly in the source JSON.""" base = self._minimal_nn_json() - base['model']['elements']['fl1'] = { - 'id': 'fl1', 'type': 'FlattenLayer', 'name': 'FlattenLayer', - 'owner': 'c1', - 'bounds': {'x': 300, 'y': 60, 'width': 110, 'height': 110}, - 'attributes': ['fl1n', 'fl1s', 'fl1e'], 'methods': [], - } - base['model']['elements']['fl1n'] = { - 'id': 'fl1n', 'type': 'NameAttributeFlatten', - 'attributeName': 'name', 'value': 'flat', 'owner': 'fl1', - } - base['model']['elements']['fl1s'] = { - 'id': 'fl1s', 'type': 'StartDimAttributeFlatten', - 'attributeName': 'start_dim', 'value': '1', 'owner': 'fl1', - } - base['model']['elements']['fl1e'] = { - 'id': 'fl1e', 'type': 'EndDimAttributeFlatten', - 'attributeName': 'end_dim', 'value': '-1', 'owner': 'fl1', - } - # Connect fl1 into the existing l1 -> l2 chain so the connectivity - # check sees a single entry point. - base['model']['relationships']['rfl1'] = { - 'id': 'rfl1', 'type': 'NNNext', - 'source': {'element': 'l2'}, 'target': {'element': 'fl1'}, - 'name': 'next', - } + base["model"]["nodes"].append({ + "id": "fl1", "type": "FlattenLayer", + "parentId": "c1", + "position": {"x": 300, "y": 60}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": "flat", + "attributes": {"name": "flat", "start_dim": "1", "end_dim": "-1"}}, + }) + # Connect fl1 into the existing l1 -> l2 chain. + base["model"]["edges"].append({ + "id": "rfl1", "source": "l2", "target": "fl1", + "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}, + }) out = self._roundtrip(base) - elements = _resolve_elements(out) - flat = _extract_elements_by_type(out, 'FlattenLayer') - assert flat, 'FlattenLayer missing from output' - attrs = { - elements[aid]['attributeName']: elements[aid]['value'] - for aid in flat[0]['attributes'] - } - assert 'start_dim' in attrs, f'start_dim should round-trip when explicit; got {attrs}' - assert 'end_dim' in attrs, f'end_dim should round-trip when explicit; got {attrs}' + flat = _nodes_by_type(out, "FlattenLayer") + assert flat + attrs = _nn_layer_attrs(flat[0]) + assert "start_dim" in attrs + assert "end_dim" in attrs def test_tensorop_concatenate_preserves_float_in_layers_of_tensors(self): - """TensorOp ``layers_of_tensors=[0.5, 'name']`` must preserve the 0.5 - as a float (not the string '0.5') after round-trip, so downstream - generators can distinguish numeric weights from layer-name references.""" - from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( - process_nn_diagram, - ) + """TensorOp layers_of_tensors with a leading float must preserve it as a + float (not its string repr) after parsing.""" payload = { - 'title': 'op', - 'model': { - 'type': 'NNDiagram', 'version': '3.0.0', - 'size': {'width': 1000, 'height': 400}, - 'elements': { - 'c': {'id': 'c', 'type': 'NNContainer', 'name': 'op', - 'owner': None, - 'bounds': {'x': 0, 'y': 0, 'width': 400, 'height': 200}}, - 'sup': {'id': 'sup', 'type': 'LinearLayer', 'name': 'LinearLayer', - 'owner': 'c', - 'bounds': {'x': 20, 'y': 60, 'width': 110, 'height': 110}, - 'attributes': ['supn', 'supo'], 'methods': []}, - 'supn': {'id': 'supn', 'type': 'NameAttributeLinear', - 'attributeName': 'name', 'value': 'other', 'owner': 'sup'}, - 'supo': {'id': 'supo', 'type': 'OutFeaturesAttributeLinear', - 'attributeName': 'out_features', 'value': '4', 'owner': 'sup'}, - 't': {'id': 't', 'type': 'TensorOp', 'name': 'TensorOp', - 'owner': 'c', - 'bounds': {'x': 160, 'y': 60, 'width': 110, 'height': 110}, - 'attributes': ['tn', 'tt', 'tc', 'tl'], 'methods': []}, - 'tn': {'id': 'tn', 'type': 'NameAttributeTensorOp', - 'attributeName': 'name', 'value': 'op1', 'owner': 't'}, - 'tt': {'id': 'tt', 'type': 'TnsTypeAttributeTensorOp', - 'attributeName': 'tns_type', 'value': 'concatenate', - 'owner': 't'}, - 'tc': {'id': 'tc', 'type': 'ConcatenateDimAttributeTensorOp', - 'attributeName': 'concatenate_dim', 'value': '1', 'owner': 't'}, - 'tl': {'id': 'tl', - 'type': 'LayersOfTensorsAttributeTensorOp', - 'attributeName': 'layers_of_tensors', - 'value': "[0.5, 'other']", 'owner': 't'}, - }, - 'relationships': { - 'r1': {'id': 'r1', 'type': 'NNNext', - 'source': {'element': 'sup'}, 'target': {'element': 't'}, - 'name': 'next'}, - }, - 'interactive': {'elements': {}, 'relationships': {}}, - 'assessments': {}, + "title": "op", + "model": { + "version": "4.0.0", + "type": "NNDiagram", + "nodes": [ + {"id": "c", "type": "NNContainer", + "position": {"x": 0, "y": 0}, "width": 400, "height": 200, + "measured": {"width": 400, "height": 200}, + "data": {"name": "op"}}, + {"id": "sup", "type": "LinearLayer", + "parentId": "c", + "position": {"x": 20, "y": 60}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": "other", + "attributes": {"name": "other", "out_features": "4"}}}, + {"id": "t", "type": "TensorOp", + "parentId": "c", + "position": {"x": 160, "y": 60}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": "op1", + "attributes": { + "name": "op1", + "tns_type": "concatenate", + "concatenate_dim": "1", + "layers_of_tensors": "[0.5, 'other']", + }}}, + ], + "edges": [ + {"id": "r1", "source": "sup", "target": "t", + "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}}, + ], }, } nn = process_nn_diagram(payload) - top = [m for m in nn.modules if type(m).__name__ == 'TensorOp'][0] - assert top.layers_of_tensors[0] == 0.5, \ - f"first item should be float 0.5, got {top.layers_of_tensors[0]!r}" + top = [m for m in nn.modules if type(m).__name__ == "TensorOp"][0] + assert top.layers_of_tensors[0] == 0.5 assert isinstance(top.layers_of_tensors[0], float) - assert top.layers_of_tensors[1] == 'other' + assert top.layers_of_tensors[1] == "other" def test_transitive_nnreference_cycle_detected(self): - """Three-container NNReference cycle A→B→C→A must raise with the - cycle chain in the error message.""" - from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( - process_nn_diagram, - ) cyclic = { - 'title': 'transitive', - 'model': { - 'type': 'NNDiagram', 'version': '3.0.0', - 'size': {'width': 1800, 'height': 600}, - 'elements': { - 'A': {'id': 'A', 'type': 'NNContainer', 'name': 'A', 'owner': None, - 'bounds': {'x': 0, 'y': 0, 'width': 400, 'height': 200}}, - 'B': {'id': 'B', 'type': 'NNContainer', 'name': 'B', 'owner': None, - 'bounds': {'x': 500, 'y': 0, 'width': 400, 'height': 200}}, - 'C': {'id': 'C', 'type': 'NNContainer', 'name': 'C', 'owner': None, - 'bounds': {'x': 1000, 'y': 0, 'width': 400, 'height': 200}}, - 'rA': {'id': 'rA', 'type': 'NNReference', 'name': 'A->B', 'owner': 'A', - 'referencedNN': 'B', - 'bounds': {'x': 20, 'y': 60, 'width': 140, 'height': 40}}, - 'rB': {'id': 'rB', 'type': 'NNReference', 'name': 'B->C', 'owner': 'B', - 'referencedNN': 'C', - 'bounds': {'x': 520, 'y': 60, 'width': 140, 'height': 40}}, - 'rC': {'id': 'rC', 'type': 'NNReference', 'name': 'C->A', 'owner': 'C', - 'referencedNN': 'A', - 'bounds': {'x': 1020, 'y': 60, 'width': 140, 'height': 40}}, - }, - 'relationships': {}, - 'interactive': {'elements': {}, 'relationships': {}}, - 'assessments': {}, + "title": "transitive", + "model": { + "version": "4.0.0", + "type": "NNDiagram", + "nodes": [ + {"id": "A", "type": "NNContainer", + "position": {"x": 0, "y": 0}, "width": 400, "height": 200, + "measured": {"width": 400, "height": 200}, + "data": {"name": "A"}}, + {"id": "B", "type": "NNContainer", + "position": {"x": 500, "y": 0}, "width": 400, "height": 200, + "measured": {"width": 400, "height": 200}, + "data": {"name": "B"}}, + {"id": "C", "type": "NNContainer", + "position": {"x": 1000, "y": 0}, "width": 400, "height": 200, + "measured": {"width": 400, "height": 200}, + "data": {"name": "C"}}, + {"id": "rA", "type": "NNReference", "parentId": "A", + "position": {"x": 20, "y": 60}, "width": 140, "height": 40, + "measured": {"width": 140, "height": 40}, + "data": {"name": "A->B", "referenceTarget": "B"}}, + {"id": "rB", "type": "NNReference", "parentId": "B", + "position": {"x": 520, "y": 60}, "width": 140, "height": 40, + "measured": {"width": 140, "height": 40}, + "data": {"name": "B->C", "referenceTarget": "C"}}, + {"id": "rC", "type": "NNReference", "parentId": "C", + "position": {"x": 1020, "y": 60}, "width": 140, "height": 40, + "measured": {"width": 140, "height": 40}, + "data": {"name": "C->A", "referenceTarget": "A"}}, + ], + "edges": [], }, } with pytest.raises(ValueError, match="NNReference cycle"): process_nn_diagram(cyclic) def test_conv3d_kernel_dim_wrong_length_raises_with_layer_name(self): - """Conv3D with kernel_dim=[3,3] must raise a user-facing error that - names the layer and expected dimensionality.""" - from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( - process_nn_diagram, - ) payload = { - 'title': 'conv', - 'model': { - 'type': 'NNDiagram', 'version': '3.0.0', - 'size': {'width': 800, 'height': 400}, - 'elements': { - 'c': {'id': 'c', 'type': 'NNContainer', 'name': 'net', - 'owner': None, - 'bounds': {'x': 0, 'y': 0, 'width': 400, 'height': 200}}, - 'l': {'id': 'l', 'type': 'Conv3DLayer', 'name': 'Conv3DLayer', - 'owner': 'c', - 'bounds': {'x': 20, 'y': 60, 'width': 110, 'height': 110}, - 'attributes': ['ln', 'lk', 'lo'], 'methods': []}, - 'ln': {'id': 'ln', 'type': 'NameAttributeConv3D', - 'attributeName': 'name', 'value': 'volume', 'owner': 'l'}, - 'lk': {'id': 'lk', 'type': 'KernelDimAttributeConv3D', - 'attributeName': 'kernel_dim', - 'value': '[3, 3]', 'owner': 'l'}, - 'lo': {'id': 'lo', 'type': 'OutChannelsAttributeConv3D', - 'attributeName': 'out_channels', 'value': '8', 'owner': 'l'}, - }, - 'relationships': {}, - 'interactive': {'elements': {}, 'relationships': {}}, - 'assessments': {}, + "title": "conv", + "model": { + "version": "4.0.0", + "type": "NNDiagram", + "nodes": [ + {"id": "c", "type": "NNContainer", + "position": {"x": 0, "y": 0}, "width": 400, "height": 200, + "measured": {"width": 400, "height": 200}, + "data": {"name": "net"}}, + {"id": "l", "type": "Conv3DLayer", "parentId": "c", + "position": {"x": 20, "y": 60}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": "volume", + "attributes": {"name": "volume", "kernel_dim": "[3, 3]", + "out_channels": "8"}}}, + ], + "edges": [], }, } with pytest.raises(ValueError, match=r"Conv3D.*volume.*kernel_dim.*expected 3"): process_nn_diagram(payload) @staticmethod - def _single_layer_json(layer_type: str, attrs: list, rels: dict = None): - """Build a minimal NN diagram with a single layer of the given type. + def _single_layer_json(layer_type, attrs, edges=None): + """Build a v4 NN diagram with a single layer of the given ``layer_type``. - ``attrs`` is a list of (suffix, attributeName, value) tuples. Each - becomes an attribute element owned by the layer. + ``attrs`` is a dict of attributeName -> string-value entries that + becomes the layer's ``data.attributes`` dict. """ - layer_id = 'L' - attr_elements = {} - attr_ids = [] - for idx, (suffix, aname, avalue) in enumerate(attrs): - aid = f'a{idx}' - attr_ids.append(aid) - attr_elements[aid] = { - 'id': aid, - 'type': f'{aname.title().replace("_", "")}Attribute{suffix}'.replace(' ', ''), - 'attributeName': aname, - 'value': avalue, - 'owner': layer_id, - } + nodes = [ + {"id": "c", "type": "NNContainer", + "position": {"x": 0, "y": 0}, "width": 400, "height": 200, + "measured": {"width": 400, "height": 200}, + "data": {"name": "net"}}, + {"id": "L", "type": layer_type, "parentId": "c", + "position": {"x": 20, "y": 60}, "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": attrs.get("name", layer_type), + "attributes": dict(attrs)}}, + ] return { - 'title': 'single', - 'model': { - 'type': 'NNDiagram', 'version': '3.0.0', - 'size': {'width': 800, 'height': 400}, - 'elements': { - 'c': {'id': 'c', 'type': 'NNContainer', 'name': 'net', 'owner': None, - 'bounds': {'x': 0, 'y': 0, 'width': 400, 'height': 200}}, - layer_id: {'id': layer_id, 'type': layer_type, 'name': layer_type, 'owner': 'c', - 'bounds': {'x': 20, 'y': 60, 'width': 110, 'height': 110}, - 'attributes': attr_ids, 'methods': []}, - **attr_elements, - }, - 'relationships': rels or {}, - 'interactive': {'elements': {}, 'relationships': {}}, - 'assessments': {}, + "title": "single", + "model": { + "version": "4.0.0", + "type": "NNDiagram", + "nodes": nodes, + "edges": edges or [], }, } def test_lstm_roundtrip(self): - payload = self._single_layer_json('LSTMLayer', [ - ('LSTM', 'name', 'lstm1'), - ('LSTM', 'hidden_size', '128'), - ('LSTM', 'input_size', '64'), - ('LSTM', 'return_type', 'last'), - ('LSTM', 'bias', 'false'), - ('LSTM', 'hx_source', 'encoder_h'), - ('LSTM', 'hidden_state_var', 'h_0'), - ('LSTM', 'hidden_unused', 'true'), - ('LSTM', 'hidden_subscript_source', 'h'), - ('LSTM', 'hidden_subscript_target', 'h_t'), - ('LSTM', 'cell_state_var', 'c_0'), - ('LSTM', 'cell_unused', 'false'), - ('LSTM', 'is_layer_call', 'true'), - ('LSTM', 'input_var', 'seq_in'), - ('LSTM', 'output_var', 'seq_out'), - ]) + payload = self._single_layer_json("LSTMLayer", { + "name": 'lstm1', + "hidden_size": '128', + "input_size": '64', + "return_type": 'last', + "bias": 'false', + "hx_source": 'encoder_h', + "hidden_state_var": 'h_0', + "hidden_unused": 'true', + "hidden_subscript_source": 'h', + "hidden_subscript_target": 'h_t', + "cell_state_var": 'c_0', + "cell_unused": 'false', + "is_layer_call": 'true', + "input_var": 'seq_in', + "output_var": 'seq_out', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - lstm = _extract_elements_by_type(out, 'LSTMLayer') + lstm = _nodes_by_type(out, "LSTMLayer") assert lstm, 'LSTMLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in lstm[0]['attributes']} + attrs = _nn_layer_attrs(lstm[0]) assert attrs.get('name') == 'lstm1' assert attrs.get('hidden_size') == '128' assert attrs.get('input_size') == '64' @@ -2039,24 +2042,23 @@ def test_lstm_roundtrip(self): assert attrs.get('output_var') == 'seq_out' def test_gru_roundtrip(self): - payload = self._single_layer_json('GRULayer', [ - ('GRU', 'name', 'gru1'), - ('GRU', 'hidden_size', '32'), - ('GRU', 'bias', 'false'), - ('GRU', 'hx_source', 'context'), - ('GRU', 'hidden_state_var', 'h'), - ('GRU', 'hidden_unused', 'true'), - ('GRU', 'hidden_subscript_source', 'hs'), - ('GRU', 'hidden_subscript_target', 'ht'), - ('GRU', 'is_layer_call', 'true'), - ('GRU', 'input_var', 'in'), - ('GRU', 'output_var', 'out'), - ]) + payload = self._single_layer_json("GRULayer", { + "name": 'gru1', + "hidden_size": '32', + "bias": 'false', + "hx_source": 'context', + "hidden_state_var": 'h', + "hidden_unused": 'true', + "hidden_subscript_source": 'hs', + "hidden_subscript_target": 'ht', + "is_layer_call": 'true', + "input_var": 'in', + "output_var": 'out', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - gru = _extract_elements_by_type(out, 'GRULayer') + gru = _nodes_by_type(out, "GRULayer") assert gru, 'GRULayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in gru[0]['attributes']} + attrs = _nn_layer_attrs(gru[0]) assert attrs.get('name') == 'gru1' assert attrs.get('hidden_size') == '32' assert attrs.get('bias') == 'false' @@ -2070,22 +2072,21 @@ def test_gru_roundtrip(self): assert attrs.get('output_var') == 'out' def test_embedding_roundtrip(self): - payload = self._single_layer_json('EmbeddingLayer', [ - ('Embedding', 'name', 'emb'), - ('Embedding', 'num_embeddings', '1000'), - ('Embedding', 'embedding_dim', '64'), - ('Embedding', 'padding_idx', '0'), - ('Embedding', 'permute_in', 'true'), - ('Embedding', 'permute_out', 'false'), - ('Embedding', 'is_layer_call', 'true'), - ('Embedding', 'input_var', 'tokens'), - ('Embedding', 'output_var', 'embeddings'), - ]) + payload = self._single_layer_json("EmbeddingLayer", { + "name": 'emb', + "num_embeddings": '1000', + "embedding_dim": '64', + "padding_idx": '0', + "permute_in": 'true', + "permute_out": 'false', + "is_layer_call": 'true', + "input_var": 'tokens', + "output_var": 'embeddings', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - emb = _extract_elements_by_type(out, 'EmbeddingLayer') + emb = _nodes_by_type(out, "EmbeddingLayer") assert emb, 'EmbeddingLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in emb[0]['attributes']} + attrs = _nn_layer_attrs(emb[0]) assert attrs.get('num_embeddings') == '1000' assert attrs.get('embedding_dim') == '64' assert attrs.get('padding_idx') == '0' @@ -2096,25 +2097,24 @@ def test_embedding_roundtrip(self): assert attrs.get('output_var') == 'embeddings' def test_batchnorm_roundtrip(self): - payload = self._single_layer_json('BatchNormalizationLayer', [ - ('BatchNormalization', 'name', 'bn'), - ('BatchNormalization', 'num_features', '64'), - ('BatchNormalization', 'dimension', '2D'), - ('BatchNormalization', 'eps', '0.001'), - ('BatchNormalization', 'momentum', '0.05'), - ('BatchNormalization', 'affine', 'false'), - ('BatchNormalization', 'track_running_stats', 'true'), - ('BatchNormalization', 'is_layer_call', 'true'), - ('BatchNormalization', 'input_var', 'x_bn'), - ('BatchNormalization', 'output_var', 'y_bn'), - ]) + payload = self._single_layer_json("BatchNormalizationLayer", { + "name": 'bn', + "num_features": '64', + "batch_normalization.dimension": '2D', + "eps": '0.001', + "momentum": '0.05', + "affine": 'false', + "track_running_stats": 'true', + "is_layer_call": 'true', + "input_var": 'x_bn', + "output_var": 'y_bn', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - bn = _extract_elements_by_type(out, 'BatchNormalizationLayer') + bn = _nodes_by_type(out, "BatchNormalizationLayer") assert bn, 'BatchNormalizationLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in bn[0]['attributes']} + attrs = _nn_layer_attrs(bn[0]) assert attrs.get('num_features') == '64' - assert attrs.get('dimension') == '2D' + assert attrs.get('batch_normalization.dimension') == '2D' assert attrs.get('eps') == '0.001' assert attrs.get('momentum') == '0.05' assert attrs.get('affine') == 'false' @@ -2124,20 +2124,19 @@ def test_batchnorm_roundtrip(self): assert attrs.get('output_var') == 'y_bn' def test_layernorm_roundtrip(self): - payload = self._single_layer_json('LayerNormalizationLayer', [ - ('LayerNormalization', 'name', 'ln'), - ('LayerNormalization', 'normalized_shape', '[32, 32]'), - ('LayerNormalization', 'eps', '0.0001'), - ('LayerNormalization', 'affine', 'true'), - ('LayerNormalization', 'is_layer_call', 'false'), - ('LayerNormalization', 'input_var', 'norm_in'), - ('LayerNormalization', 'output_var', 'norm_out'), - ]) + payload = self._single_layer_json("LayerNormalizationLayer", { + "name": 'ln', + "normalized_shape": '[32, 32]', + "eps": '0.0001', + "affine": 'true', + "is_layer_call": 'false', + "input_var": 'norm_in', + "output_var": 'norm_out', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - ln = _extract_elements_by_type(out, 'LayerNormalizationLayer') + ln = _nodes_by_type(out, "LayerNormalizationLayer") assert ln, 'LayerNormalizationLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ln[0]['attributes']} + attrs = _nn_layer_attrs(ln[0]) assert attrs.get('normalized_shape') == '[32, 32]' assert attrs.get('eps') == '0.0001' assert attrs.get('affine') == 'true' @@ -2146,21 +2145,20 @@ def test_layernorm_roundtrip(self): assert attrs.get('output_var') == 'norm_out' def test_dropout_roundtrip(self): - payload = self._single_layer_json('DropoutLayer', [ - ('Dropout', 'name', 'drop'), - ('Dropout', 'rate', '0.5'), - ('Dropout', 'dimension', '2D'), - ('Dropout', 'permute_in', 'false'), - ('Dropout', 'permute_out', 'true'), - ('Dropout', 'is_layer_call', 'false'), - ('Dropout', 'input_var', 'drop_in'), - ('Dropout', 'output_var', 'drop_out'), - ]) + payload = self._single_layer_json("DropoutLayer", { + "name": 'drop', + "rate": '0.5', + "dimension": '2D', + "permute_in": 'false', + "permute_out": 'true', + "is_layer_call": 'false', + "input_var": 'drop_in', + "output_var": 'drop_out', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - drop = _extract_elements_by_type(out, 'DropoutLayer') + drop = _nodes_by_type(out, "DropoutLayer") assert drop, 'DropoutLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in drop[0]['attributes']} + attrs = _nn_layer_attrs(drop[0]) assert attrs.get('rate') == '0.5' assert attrs.get('dimension') == '2D' assert attrs.get('permute_in') == 'false' @@ -2170,22 +2168,21 @@ def test_dropout_roundtrip(self): assert attrs.get('output_var') == 'drop_out' def test_conv1d_roundtrip(self): - payload = self._single_layer_json('Conv1DLayer', [ - ('Conv1D', 'name', 'c1'), - ('Conv1D', 'kernel_dim', '[3]'), - ('Conv1D', 'out_channels', '16'), - ('Conv1D', 'dilation', '[2]'), - ('Conv1D', 'groups', '2'), - ('Conv1D', 'bias', 'false'), - ('Conv1D', 'is_layer_call', 'true'), - ('Conv1D', 'input_var', 'x_in'), - ('Conv1D', 'output_var', 'x_out'), - ]) + payload = self._single_layer_json("Conv1DLayer", { + "name": 'c1', + "kernel_dim": '[3]', + "out_channels": '16', + "dilation": '[2]', + "groups": '2', + "bias": 'false', + "is_layer_call": 'true', + "input_var": 'x_in', + "output_var": 'x_out', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - c1 = _extract_elements_by_type(out, 'Conv1DLayer') + c1 = _nodes_by_type(out, "Conv1DLayer") assert c1, 'Conv1DLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in c1[0]['attributes']} + attrs = _nn_layer_attrs(c1[0]) assert attrs.get('kernel_dim') == '[3]' assert attrs.get('out_channels') == '16' assert attrs.get('dilation') == '[2]' @@ -2196,22 +2193,21 @@ def test_conv1d_roundtrip(self): assert attrs.get('output_var') == 'x_out' def test_conv2d_roundtrip(self): - payload = self._single_layer_json('Conv2DLayer', [ - ('Conv2D', 'name', 'c2'), - ('Conv2D', 'kernel_dim', '[3, 3]'), - ('Conv2D', 'out_channels', '32'), - ('Conv2D', 'dilation', '[1, 1]'), - ('Conv2D', 'groups', '1'), - ('Conv2D', 'bias', 'true'), - ('Conv2D', 'is_layer_call', 'false'), - ('Conv2D', 'input_var', 'img'), - ('Conv2D', 'output_var', 'feat'), - ]) + payload = self._single_layer_json("Conv2DLayer", { + "name": 'c2', + "kernel_dim": '[3, 3]', + "out_channels": '32', + "dilation": '[1, 1]', + "groups": '1', + "bias": 'true', + "is_layer_call": 'false', + "input_var": 'img', + "output_var": 'feat', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - c2 = _extract_elements_by_type(out, 'Conv2DLayer') + c2 = _nodes_by_type(out, "Conv2DLayer") assert c2, 'Conv2DLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in c2[0]['attributes']} + attrs = _nn_layer_attrs(c2[0]) assert attrs.get('kernel_dim') == '[3, 3]' assert attrs.get('out_channels') == '32' assert attrs.get('dilation') == '[1, 1]' @@ -2222,22 +2218,21 @@ def test_conv2d_roundtrip(self): assert attrs.get('output_var') == 'feat' def test_conv3d_roundtrip(self): - payload = self._single_layer_json('Conv3DLayer', [ - ('Conv3D', 'name', 'c3'), - ('Conv3D', 'kernel_dim', '[3, 3, 3]'), - ('Conv3D', 'out_channels', '64'), - ('Conv3D', 'dilation', '[2, 2, 2]'), - ('Conv3D', 'groups', '4'), - ('Conv3D', 'bias', 'false'), - ('Conv3D', 'is_layer_call', 'true'), - ('Conv3D', 'input_var', 'volume_in'), - ('Conv3D', 'output_var', 'volume_out'), - ]) + payload = self._single_layer_json("Conv3DLayer", { + "name": 'c3', + "kernel_dim": '[3, 3, 3]', + "out_channels": '64', + "dilation": '[2, 2, 2]', + "groups": '4', + "bias": 'false', + "is_layer_call": 'true', + "input_var": 'volume_in', + "output_var": 'volume_out', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - c3 = _extract_elements_by_type(out, 'Conv3DLayer') + c3 = _nodes_by_type(out, "Conv3DLayer") assert c3, 'Conv3DLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in c3[0]['attributes']} + attrs = _nn_layer_attrs(c3[0]) assert attrs.get('kernel_dim') == '[3, 3, 3]' assert attrs.get('out_channels') == '64' assert attrs.get('dilation') == '[2, 2, 2]' @@ -2248,19 +2243,18 @@ def test_conv3d_roundtrip(self): assert attrs.get('output_var') == 'volume_out' def test_linear_roundtrip(self): - payload = self._single_layer_json('LinearLayer', [ - ('Linear', 'name', 'fc'), - ('Linear', 'out_features', '10'), - ('Linear', 'bias', 'false'), - ('Linear', 'is_layer_call', 'true'), - ('Linear', 'input_var', 'hidden'), - ('Linear', 'output_var', 'logits'), - ]) + payload = self._single_layer_json("LinearLayer", { + "name": 'fc', + "out_features": '10', + "bias": 'false', + "is_layer_call": 'true', + "input_var": 'hidden', + "output_var": 'logits', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - fc = _extract_elements_by_type(out, 'LinearLayer') + fc = _nodes_by_type(out, "LinearLayer") assert fc, 'LinearLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in fc[0]['attributes']} + attrs = _nn_layer_attrs(fc[0]) assert attrs.get('out_features') == '10' assert attrs.get('bias') == 'false' assert attrs.get('is_layer_call') == 'true' @@ -2268,40 +2262,37 @@ def test_linear_roundtrip(self): assert attrs.get('output_var') == 'logits' def test_pooling_roundtrip(self): - payload = self._single_layer_json('PoolingLayer', [ - ('Pooling', 'name', 'pool'), - ('Pooling', 'pooling_type', 'max'), - ('Pooling', 'dimension', '2D'), - ('Pooling', 'kernel_dim', '[2, 2]'), - ]) + # `dimension` is qualified to disambiguate from BatchNormalization. + payload = self._single_layer_json("PoolingLayer", { + "name": "pool", "pooling_type": "max", + "pooling.dimension": "2D", "kernel_dim": "[2, 2]", + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - pool = _extract_elements_by_type(out, 'PoolingLayer') - assert pool, 'PoolingLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in pool[0]['attributes']} - assert attrs.get('pooling_type') == 'max' - assert attrs.get('dimension') == '2D' - assert attrs.get('kernel_dim') == '[2, 2]' + pool = _nodes_by_type(out, "PoolingLayer") + assert pool + attrs = _nn_layer_attrs(pool[0]) + assert attrs.get("pooling_type") == "max" + assert attrs.get("pooling.dimension") == "2D" + assert attrs.get("kernel_dim") == "[2, 2]" def test_simple_rnn_roundtrip(self): - payload = self._single_layer_json('RNNLayer', [ - ('RNN', 'name', 'rnn1'), - ('RNN', 'hidden_size', '64'), - ('RNN', 'bias', 'true'), - ('RNN', 'hx_source', 'prev_h'), - ('RNN', 'hidden_state_var', 'h_init'), - ('RNN', 'hidden_unused', 'false'), - ('RNN', 'hidden_subscript_source', 'h_src'), - ('RNN', 'hidden_subscript_target', 'h_tgt'), - ('RNN', 'is_layer_call', 'false'), - ('RNN', 'input_var', 'x'), - ('RNN', 'output_var', 'y'), - ]) + payload = self._single_layer_json("RNNLayer", { + "name": 'rnn1', + "hidden_size": '64', + "bias": 'true', + "hx_source": 'prev_h', + "hidden_state_var": 'h_init', + "hidden_unused": 'false', + "hidden_subscript_source": 'h_src', + "hidden_subscript_target": 'h_tgt', + "is_layer_call": 'false', + "input_var": 'x', + "output_var": 'y', + }) out = self._roundtrip(payload) - elements = _resolve_elements(out) - rnn = _extract_elements_by_type(out, 'RNNLayer') + rnn = _nodes_by_type(out, "RNNLayer") assert rnn, 'RNNLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in rnn[0]['attributes']} + attrs = _nn_layer_attrs(rnn[0]) assert attrs.get('hidden_size') == '64' assert attrs.get('bias') == 'true' assert attrs.get('hx_source') == 'prev_h' @@ -2314,54 +2305,49 @@ def test_simple_rnn_roundtrip(self): assert attrs.get('output_var') == 'y' @staticmethod - def _tensor_op_json(tns_type: str, extra_attrs: list): - """Build a minimal NN diagram containing a TensorOp preceded by two - LinearLayers named ``layer_a`` and ``layer_b``.""" - attrs = [('TensorOp', 'name', f'{tns_type}_op'), - ('TensorOp', 'tns_type', tns_type)] + extra_attrs - payload = TestNNDiagramRoundtrip._single_layer_json('TensorOp', attrs) - elements = payload['model']['elements'] - for sup_id, sup_name, sup_x in (('supA', 'layer_a', 200), ('supB', 'layer_b', 320)): - elements[sup_id] = { - 'id': sup_id, 'type': 'LinearLayer', 'name': 'LinearLayer', 'owner': 'c', - 'bounds': {'x': sup_x, 'y': 60, 'width': 110, 'height': 110}, - 'attributes': [f'{sup_id}n', f'{sup_id}o'], 'methods': [], - } - elements[f'{sup_id}n'] = { - 'id': f'{sup_id}n', 'type': 'NameAttributeLinear', - 'attributeName': 'name', 'value': sup_name, 'owner': sup_id, - } - elements[f'{sup_id}o'] = { - 'id': f'{sup_id}o', 'type': 'OutFeaturesAttributeLinear', - 'attributeName': 'out_features', 'value': '4', 'owner': sup_id, - } - rels = payload['model']['relationships'] - rels['rel_a_b'] = { - 'id': 'rel_a_b', 'type': 'NNNext', - 'source': {'element': 'supA'}, 'target': {'element': 'supB'}, - 'name': 'next', - } - rels['rel_b_op'] = { - 'id': 'rel_b_op', 'type': 'NNNext', - 'source': {'element': 'supB'}, 'target': {'element': 'L'}, - 'name': 'next', - } + def _tensor_op_json(tns_type, extra_attrs): + """Build an NN diagram with a TensorOp preceded by two LinearLayers + named ``layer_a`` and ``layer_b``.""" + attrs = {"name": f"{tns_type}_op", "tns_type": tns_type, **extra_attrs} + payload = TestNNDiagramRoundtrip._single_layer_json("TensorOp", attrs) + nodes = payload["model"]["nodes"] + edges = payload["model"]["edges"] + for sup_id, sup_name, sup_x in (("supA", "layer_a", 200), ("supB", "layer_b", 320)): + nodes.append({ + "id": sup_id, "type": "LinearLayer", "parentId": "c", + "position": {"x": sup_x, "y": 60}, + "width": 110, "height": 110, + "measured": {"width": 110, "height": 110}, + "data": {"name": sup_name, + "attributes": {"name": sup_name, "out_features": "4"}}, + }) + edges.append({ + "id": "rel_a_b", "source": "supA", "target": "supB", + "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}, + }) + edges.append({ + "id": "rel_b_op", "source": "supB", "target": "L", + "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}, + }) return payload def test_tensorop_concatenate_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('concatenate', [ - ('TensorOp', 'concatenate_dim', '1'), - ('TensorOp', 'layers_of_tensors', "['layer_a', 'layer_b']"), - ('TensorOp', 'actual_vars', "['output', 'hidden']"), - ('TensorOp', 'input_var', 'concat_in'), - ('TensorOp', 'output_var', 'concat_out'), - ('TensorOp', 'permute_in', 'true'), - ('TensorOp', 'permute_out', 'false'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') + out = self._roundtrip(self._tensor_op_json("concatenate", { + "concatenate_dim": '1', + "layers_of_tensors": "['layer_a', 'layer_b']", + "actual_vars": "['output', 'hidden']", + "input_var": 'concat_in', + "output_var": 'concat_out', + "permute_in": 'true', + "permute_out": 'false', + })) + ops = _nodes_by_type(out, "TensorOp") assert ops, 'TensorOp missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'concatenate' assert attrs.get('concatenate_dim') == '1' assert attrs.get('actual_vars') == "['output', 'hidden']" @@ -2371,98 +2357,89 @@ def test_tensorop_concatenate_roundtrip(self): assert attrs.get('permute_out') == 'false' def test_tensorop_multiply_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('multiply', [ - ('TensorOp', 'layers_of_tensors', "['layer_a', 'layer_b']"), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} - assert attrs.get('tns_type') == 'multiply' + out = self._roundtrip(self._tensor_op_json("multiply", { + "layers_of_tensors": "['layer_a', 'layer_b']", + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) + assert attrs.get("tns_type") == "multiply" def test_tensorop_matmultiply_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('matmultiply', [ - ('TensorOp', 'layers_of_tensors', "['layer_a', 'layer_b']"), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} - assert attrs.get('tns_type') == 'matmultiply' + out = self._roundtrip(self._tensor_op_json("matmultiply", { + "layers_of_tensors": "['layer_a', 'layer_b']", + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) + assert attrs.get("tns_type") == "matmultiply" def test_tensorop_reshape_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('reshape', [ - ('TensorOp', 'layers_of_tensors', "['layer_a']"), - ('TensorOp', 'reshape_dim', '[1, -1]'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("reshape", { + "layers_of_tensors": "['layer_a']", + "reshape_dim": '[1, -1]', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'reshape' assert attrs.get('reshape_dim') == '[1, -1]' def test_tensorop_transpose_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('transpose', [ - ('TensorOp', 'layers_of_tensors', "['layer_a']"), - ('TensorOp', 'transpose_dim', '[0, 2]'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("transpose", { + "layers_of_tensors": "['layer_a']", + "transpose_dim": '[0, 2]', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'transpose' assert attrs.get('transpose_dim') == '[0, 2]' def test_tensorop_permute_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('permute', [ - ('TensorOp', 'permute_dim', '[0, 3, 1, 2]'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} - assert attrs.get('tns_type') == 'permute' - assert attrs.get('permute_dim') == '[0, 3, 1, 2]' + out = self._roundtrip(self._tensor_op_json("permute", { + "permute_dim": "[0, 3, 1, 2]", + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) + assert attrs.get("tns_type") == "permute" + assert attrs.get("permute_dim") == "[0, 3, 1, 2]" def test_tensorop_binop_add_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('binop_add', [ - ('TensorOp', 'layers_of_tensors', "['layer_a', 'layer_b']"), - ('TensorOp', 'actual_vars', "['output', 'hidden']"), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("binop_add", { + "layers_of_tensors": "['layer_a', 'layer_b']", + "actual_vars": "['output', 'hidden']", + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'binop_add' assert attrs.get('actual_vars') == "['output', 'hidden']" def test_tensorop_mean_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('mean', [ - ('TensorOp', 'reduce_dim', '1'), - ('TensorOp', 'layers_of_tensors', "['layer_a']"), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("mean", { + "reduce_dim": '1', + "layers_of_tensors": "['layer_a']", + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'mean' assert attrs.get('reduce_dim') == '1' def test_tensorop_max_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('max', [ - ('TensorOp', 'reduce_dim', '0'), - ('TensorOp', 'reduce_keepdims', 'true'), - ('TensorOp', 'layers_of_tensors', "['layer_a']"), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("max", { + "reduce_dim": '0', + "reduce_keepdims": 'true', + "layers_of_tensors": "['layer_a']", + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'max' assert attrs.get('reduce_dim') == '0' assert attrs.get('reduce_keepdims') == 'true' def test_tensorop_squeeze_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('squeeze', [ - ('TensorOp', 'reduce_dim', '2'), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("squeeze", { + "reduce_dim": '2', + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'squeeze' assert attrs.get('reduce_dim') == '2' assert attrs.get('input_var') == 'x' @@ -2475,13 +2452,12 @@ def test_tensorop_subscript_roundtrip(self): {"type": "slice", "start": None, "stop": None, "step": None}, {"type": "slice", "start": 1, "stop": 3, "step": None}, ] - out = self._roundtrip(self._tensor_op_json('subscript', [ - ('TensorOp', 'subscript_indices', str(indices)), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("subscript", { + "subscript_indices": str(indices), + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'subscript' # The round-trip preserves the dict structure *and* emits it as real # JSON: a Python repr (single quotes / None) makes the frontend's @@ -2495,42 +2471,40 @@ def test_tensorop_subscript_accepts_json_payload(self): """A JSON-shaped subscript_indices value (what the converter now emits, and therefore what a re-imported diagram carries) must parse.""" indices = [{"type": "index", "value": 2}] - out = self._roundtrip(self._tensor_op_json('subscript', [ - ('TensorOp', 'subscript_indices', json.dumps(indices)), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("subscript", { + "subscript_indices": json.dumps(indices), + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert json.loads(attrs['subscript_indices']) == indices def test_tensorop_subscript_malformed_raises(self): """Malformed subscript_indices must surface a ValueError naming the field instead of silently dropping the user's value.""" with pytest.raises(ValueError, match=r"subscript_indices"): - self._roundtrip(self._tensor_op_json('subscript', [ - ('TensorOp', 'subscript_indices', '[{type: index,'), - ])) + self._roundtrip(self._tensor_op_json("subscript", { + "subscript_indices": '[{type: index,', + })) def test_tensorop_pad_amount_malformed_raises(self): """Same contract for pad_amount (was also swallowed to None).""" with pytest.raises(ValueError, match=r"pad_amount"): - self._roundtrip(self._tensor_op_json('pad', [ - ('TensorOp', 'pad_amount', '[[1, 1'), - ])) + self._roundtrip(self._tensor_op_json("pad", { + "pad_amount": '[[1, 1', + })) def test_tensorop_shape_dim_attribute_roundtrip(self): """The shape_dim *attribute* (distinct from the shape_dim tns_type, covered below) was parsed then dropped: it never reached the TensorOp constructor and neither exporter emitted it.""" - out = self._roundtrip(self._tensor_op_json('shape_dim', [ - ('TensorOp', 'reduce_dim', '0'), - ('TensorOp', 'shape_dim', '2'), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("shape_dim", { + "reduce_dim": '0', + "shape_dim": '2', + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'shape_dim' assert attrs.get('reduce_dim') == '0' assert attrs.get('shape_dim') == '2' @@ -2538,28 +2512,26 @@ def test_tensorop_shape_dim_attribute_roundtrip(self): def test_tensorop_repeat_dim_keeps_mixed_list(self): """repeat_dim is declared list[int | str]; parse_list_of_ints used to return None on the first non-int item, losing the whole value.""" - out = self._roundtrip(self._tensor_op_json('repeat', [ - ('TensorOp', 'repeat_dim', "[1, 'op_3', 1]"), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("repeat", { + "repeat_dim": "[1, 'op_3', 1]", + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('repeat_dim') == "[1, 'op_3', 1]" def test_batch_norm_permute_flags_roundtrip(self): """BatchNormLayer gained permute_in/permute_out in the metamodel; neither converter direction used to carry them.""" - out = self._roundtrip(self._single_layer_json('BatchNormalizationLayer', [ - ('BatchNorm', 'name', 'bn1'), - ('BatchNorm', 'num_features', '32'), - ('BatchNorm', 'dimension', '2D'), - ('BatchNorm', 'permute_in', 'true'), - ('BatchNorm', 'permute_out', 'true'), - ])) - elements = _resolve_elements(out) - layers = _extract_elements_by_type(out, 'BatchNormalizationLayer') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in layers[0]['attributes']} + out = self._roundtrip(self._single_layer_json("BatchNormalizationLayer", { + "name": 'bn1', + "num_features": '32', + "batch_normalization.dimension": '2D', + "permute_in": 'true', + "permute_out": 'true', + })) + layers = _nodes_by_type(out, "BatchNormalizationLayer") + attrs = _nn_layer_attrs(layers[0]) assert attrs.get('permute_in') == 'true' assert attrs.get('permute_out') == 'true' @@ -2574,10 +2546,9 @@ def test_hand_written_buml_model_keeps_explicit_attributes(self): dilation=[2, 2], groups=4, input_reused=True, )) out = nn_model_to_json(nn) - elements = _resolve_elements(out) - convs = _extract_elements_by_type(out, 'Conv2DLayer') + convs = _nodes_by_type(out, "Conv2DLayer") assert convs, 'Conv2D missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in convs[0]['attributes']} + attrs = _nn_layer_attrs(convs[0]) assert attrs.get('bias') == 'false' assert attrs.get('permute_in') == 'true' assert attrs.get('permute_out') == 'true' @@ -2602,10 +2573,9 @@ def test_buml_ast_import_keeps_explicit_attributes(self): "main_nn.add_layer(layer_0)", ]) out = nn_buml_to_json(buml) - elements = _resolve_elements(out) - convs = _extract_elements_by_type(out, 'Conv2DLayer') + convs = _nodes_by_type(out, "Conv2DLayer") assert convs, 'Conv2D missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in convs[0]['attributes']} + attrs = _nn_layer_attrs(convs[0]) assert attrs.get('bias') == 'false' assert attrs.get('permute_in') == 'true' assert attrs.get('permute_out') == 'true' @@ -2615,29 +2585,27 @@ def test_buml_ast_import_keeps_explicit_attributes(self): assert attrs.get('groups') == '4' def test_tensorop_interpolate_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('interpolate', [ - ('TensorOp', 'interpolate_size', '[256, 256]'), - ('TensorOp', 'interpolate_mode', 'bilinear'), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("interpolate", { + "interpolate_size": '[256, 256]', + "interpolate_mode": 'bilinear', + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'interpolate' assert attrs.get('interpolate_size') == '[256, 256]' assert attrs.get('interpolate_mode') == 'bilinear' assert attrs.get('input_var') == 'x' def test_tensorop_pad_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('pad', [ - ('TensorOp', 'pad_amount', '[[1, 1], [2, 2]]'), - ('TensorOp', 'pad_mode', 'constant'), - ('TensorOp', 'pad_value', '0.0'), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("pad", { + "pad_amount": '[[1, 1], [2, 2]]', + "pad_mode": 'constant', + "pad_value": '0.0', + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'pad' assert attrs.get('pad_amount') == '[[1, 1], [2, 2]]' assert attrs.get('pad_mode') == 'constant' @@ -2645,29 +2613,27 @@ def test_tensorop_pad_roundtrip(self): assert attrs.get('input_var') == 'x' def test_tensorop_dropout_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('dropout', [ - ('TensorOp', 'dropout_rate', '0.3'), - ('TensorOp', 'dropout_training_aware', 'true'), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("dropout", { + "dropout_rate": '0.3', + "dropout_training_aware": 'true', + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'dropout' assert attrs.get('dropout_rate') == '0.3' assert attrs.get('dropout_training_aware') == 'true' assert attrs.get('input_var') == 'x' def test_tensorop_split_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('split', [ - ('TensorOp', 'split_dim', '1'), - ('TensorOp', 'split_sizes', '3'), - ('TensorOp', 'output_vars', "['chunk1', 'chunk2', 'chunk3']"), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("split", { + "split_dim": '1', + "split_sizes": '3', + "output_vars": "['chunk1', 'chunk2', 'chunk3']", + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'split' assert attrs.get('split_dim') == '1' assert attrs.get('split_sizes') == '3' @@ -2675,172 +2641,132 @@ def test_tensorop_split_roundtrip(self): assert attrs.get('input_var') == 'x' def test_tensorop_identity_roundtrip(self): - out = self._roundtrip(self._tensor_op_json('identity', [ - ('TensorOp', 'layers_of_tensors', "['layer_a']"), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("identity", { + "layers_of_tensors": "['layer_a']", + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'identity' def test_tensorop_shape_dim_roundtrip(self): # shape_dim tns_type requires reduce_dim parameter - out = self._roundtrip(self._tensor_op_json('shape_dim', [ - ('TensorOp', 'reduce_dim', '2'), - ('TensorOp', 'input_var', 'x'), - ])) - elements = _resolve_elements(out) - ops = _extract_elements_by_type(out, 'TensorOp') - attrs = {elements[aid]['attributeName']: elements[aid]['value'] for aid in ops[0]['attributes']} + out = self._roundtrip(self._tensor_op_json("shape_dim", { + "reduce_dim": '2', + "input_var": 'x', + })) + ops = _nodes_by_type(out, "TensorOp") + attrs = _nn_layer_attrs(ops[0]) assert attrs.get('tns_type') == 'shape_dim' assert attrs.get('reduce_dim') == '2' def test_nn_container_vars_roundtrip(self): """NNContainer preserves input_var and return_vars.""" payload = self._minimal_nn_json() - container_elem = payload['model']['elements']['c1'] - container_elem['input_var'] = 'x_input' - container_elem['return_vars'] = ['output1', 'output2'] + container_node = next(n for n in payload["model"]["nodes"] if n["id"] == "c1") + container_node["data"]["input_var"] = "x_input" + container_node["data"]["return_vars"] = ["output1", "output2"] out = self._roundtrip(payload) - containers = _extract_elements_by_type(out, "NNContainer") + containers = _nodes_by_type(out, "NNContainer") assert len(containers) == 1 - container = containers[0] - assert container['input_var'] == 'x_input' - assert container['return_vars'] == ['output1', 'output2'] + container = _data(containers[0]) + assert container["input_var"] == "x_input" + assert container["return_vars"] == ["output1", "output2"] def test_pooling_invalid_pooling_type_lists_allowed_values(self): - """Unknown pooling_type raises with the whitelist in the message.""" - from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( - process_nn_diagram, - ) - payload = self._single_layer_json('PoolingLayer', [ - ('Pooling', 'name', 'p'), - ('Pooling', 'pooling_type', 'avg'), # legacy / typo - ('Pooling', 'dimension', '2D'), - ]) + payload = self._single_layer_json("PoolingLayer", { + "name": "p", "pooling_type": "avg", # legacy / typo + "pooling.dimension": "2D", + }) with pytest.raises(ValueError, match=r"Allowed values"): process_nn_diagram(payload) def test_conv_permute_in_true_roundtrips(self): - """permute_in=True must round-trip via the sidecar (iter-7/8). A - regression dropping the ``bool`` end-to-end path would turn - permute_in back into an int or tuple, or drop it entirely.""" from besser.utilities.buml_code_builder.nn_explicit_attrs import is_explicit - payload = self._single_layer_json('Conv2DLayer', [ - ('Conv2D', 'name', 'c1'), - ('Conv2D', 'kernel_dim', '[3, 3]'), - ('Conv2D', 'out_channels', '16'), - ('Conv2D', 'permute_in', 'true'), - ]) + payload = self._single_layer_json("Conv2DLayer", { + "name": "c1", "kernel_dim": "[3, 3]", + "out_channels": "16", "permute_in": "true", + }) nn = process_nn_diagram(payload) - convs = [m for m in nn.modules if type(m).__name__ == 'Conv2D'] + convs = [m for m in nn.modules if type(m).__name__ == "Conv2D"] assert convs and convs[0].permute_in is True - assert is_explicit(convs[0], 'permute_in') + assert is_explicit(convs[0], "permute_in") def test_rnn_bidirectional_dropout_batch_first_roundtrip(self): - """LSTM with bidirectional/dropout/batch_first set explicitly must - round-trip all three via the sidecar.""" from besser.utilities.buml_code_builder.nn_explicit_attrs import is_explicit - payload = self._single_layer_json('LSTMLayer', [ - ('LSTM', 'name', 'lstm1'), - ('LSTM', 'hidden_size', '128'), - ('LSTM', 'bidirectional', 'true'), - ('LSTM', 'dropout', '0.3'), - ('LSTM', 'batch_first', 'true'), - ]) + payload = self._single_layer_json("LSTMLayer", { + "name": "lstm1", "hidden_size": "128", + "bidirectional": "true", "dropout": "0.3", "batch_first": "true", + }) nn = process_nn_diagram(payload) - lstms = [m for m in nn.modules if type(m).__name__ == 'LSTMLayer'] + lstms = [m for m in nn.modules if type(m).__name__ == "LSTMLayer"] assert lstms lstm = lstms[0] assert lstm.bidirectional is True assert lstm.dropout == 0.3 assert lstm.batch_first is True - assert is_explicit(lstm, 'bidirectional') - assert is_explicit(lstm, 'dropout') - assert is_explicit(lstm, 'batch_first') + assert is_explicit(lstm, "bidirectional") + assert is_explicit(lstm, "dropout") + assert is_explicit(lstm, "batch_first") def test_tensorop_invalid_tns_type_raises(self): - """Unknown tns_type raises with the whitelist in the message.""" - payload = self._tensor_op_json('concatinate', [ # typo - ('TensorOp', 'concatenate_dim', '1'), - ('TensorOp', 'layers_of_tensors', "['a', 'b']"), - ]) + payload = self._tensor_op_json("concatinate", { # typo + "concatenate_dim": "1", + "layers_of_tensors": "['a', 'b']", + }) with pytest.raises(ValueError, match=r"invalid tns_type.*Allowed values"): process_nn_diagram(payload) def test_conv_permute_in_false_explicitly_marked(self): - """permute_in=False must round-trip via the sidecar too — an - explicit False is semantically different from "unset" and must - reach the generator.""" from besser.utilities.buml_code_builder.nn_explicit_attrs import is_explicit - payload = self._single_layer_json('Conv2DLayer', [ - ('Conv2D', 'name', 'c1'), - ('Conv2D', 'kernel_dim', '[3, 3]'), - ('Conv2D', 'out_channels', '16'), - ('Conv2D', 'permute_in', 'false'), - ]) + payload = self._single_layer_json("Conv2DLayer", { + "name": "c1", "kernel_dim": "[3, 3]", + "out_channels": "16", "permute_in": "false", + }) nn = process_nn_diagram(payload) - convs = [m for m in nn.modules if type(m).__name__ == 'Conv2D'] + convs = [m for m in nn.modules if type(m).__name__ == "Conv2D"] assert convs and convs[0].permute_in is False - assert is_explicit(convs[0], 'permute_in'), \ - "explicit False must be tracked via mark_explicit too" + assert is_explicit(convs[0], "permute_in") def test_sibling_sub_nn_same_name_emits_distinct_containers(self): - """Two sibling sub-NNs with identical display names must emit - distinct containers — pins the iter-17 id-keyed sub_nn_ids fix.""" from besser.BUML.metamodel.nn import NN, LinearLayer - # Build the NN directly (testing the converter side) - nn = NN(name='Parent') - block_a = NN(name='Block') - block_a.add_layer(LinearLayer(name='a_lin', out_features=4)) - block_b = NN(name='Block') - block_b.add_layer(LinearLayer(name='b_lin', out_features=8)) + nn = NN(name="Parent") + block_a = NN(name="Block") + block_a.add_layer(LinearLayer(name="a_lin", out_features=4)) + block_b = NN(name="Block") + block_b.add_layer(LinearLayer(name="b_lin", out_features=8)) nn.add_sub_nn(block_a) nn.add_sub_nn(block_b) out = nn_model_to_json(nn) - containers = _extract_elements_by_type(out, 'NNContainer') - # Parent + 2 sibling sub-NN containers = 3 + containers = _nodes_by_type(out, "NNContainer") assert len(containers) == 3, ( - f'expected 3 containers (parent + 2 same-named sub-NNs), got {len(containers)}' + f"expected 3 containers (parent + 2 same-named sub-NNs), got {len(containers)}" ) def test_conv_invalid_padding_type_lists_allowed_values(self): - """Unknown padding_type raises with the whitelist in the message - (mirrors pooling_type/optimizer/etc. pattern).""" - payload = self._single_layer_json('Conv2DLayer', [ - ('Conv2D', 'name', 'c1'), - ('Conv2D', 'kernel_dim', '[3, 3]'), - ('Conv2D', 'out_channels', '16'), - ('Conv2D', 'padding_type', 'Same'), # wrong capitalization - ]) + payload = self._single_layer_json("Conv2DLayer", { + "name": "c1", "kernel_dim": "[3, 3]", + "out_channels": "16", "padding_type": "Same", + }) with pytest.raises(ValueError, match=r"padding_type.*Allowed values"): process_nn_diagram(payload) def test_pooling_permute_in_roundtrips_via_converter(self): - """PoolingLayer permute_in/out must round-trip through the BUML→JSON - converter — before iter-19 the Pooling branch of _module_fields - silently dropped them even though processor+builder handled them.""" from besser.BUML.metamodel.nn import NN, PoolingLayer from besser.utilities.buml_code_builder.nn_explicit_attrs import mark_explicit - nn = NN(name='PoolPermute') + nn = NN(name="PoolPermute") pool = PoolingLayer( - name='p', pooling_type='max', dimension='2D', kernel_dim=[2, 2], + name="p", pooling_type="max", dimension="2D", kernel_dim=[2, 2], ) pool.permute_in = True - mark_explicit(pool, 'permute_in') + mark_explicit(pool, "permute_in") nn.add_layer(pool) out = nn_model_to_json(nn) - elements = _resolve_elements(out) - pools = _extract_elements_by_type(out, 'PoolingLayer') - assert pools, 'PoolingLayer missing from output' - attrs = {elements[aid]['attributeName']: elements[aid]['value'] - for aid in pools[0]['attributes']} - assert attrs.get('permute_in') == 'true', \ - f'permute_in must round-trip on Pooling; got attrs={attrs}' + pools = _nodes_by_type(out, "PoolingLayer") + assert pools, "PoolingLayer missing from output" + attrs = _nn_layer_attrs(pools[0]) + assert attrs.get("permute_in") == "true" def test_parse_float_rejects_european_decimal(self): - """parse_float with '0,5' (European comma) raises rather than - silently returning the default.""" from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( parse_float, ) @@ -2848,17 +2774,11 @@ def test_parse_float_rejects_european_decimal(self): parse_float("0,5") def test_configuration_invalid_optimizer_lists_allowed_values(self): - """Unknown optimizer raises with the whitelist in the message.""" - from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( - process_nn_diagram, - ) - payload = self._single_layer_json('Configuration', [ - ('Configuration', 'batch_size', '32'), - ('Configuration', 'epochs', '10'), - ('Configuration', 'learning_rate', '0.001'), - ('Configuration', 'optimizer', 'rmsprop'), # not in whitelist - ('Configuration', 'loss_function', 'crossentropy'), - ('Configuration', 'metrics', '[accuracy]'), - ]) + payload = self._single_layer_json("Configuration", { + "batch_size": "32", "epochs": "10", "learning_rate": "0.001", + "optimizer": "rmsprop", # not in whitelist + "loss_function": "crossentropy", + "metrics": "[accuracy]", + }) with pytest.raises(ValueError, match=r"optimizer.*Allowed values"): process_nn_diagram(payload) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_cross_diagram_promotion.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_cross_diagram_promotion.py index 677992c25..dd6c8afc6 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_cross_diagram_promotion.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_cross_diagram_promotion.py @@ -265,20 +265,18 @@ def test_dangling_manifest_surfaces_on_project(self): "id": "comp-diag", "title": "Component Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "ComponentDiagram", - "size": {"width": 800, "height": 600}, - "elements": { - "c1": { - "id": "c1", "name": "Frontend", - "type": "Component", "owner": None, - "bounds": { - "x": 0, "y": 0, "width": 160, "height": 100, - }, + "nodes": [{ + "id": "c1", "type": "component", + "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, + "data": { + "name": "Frontend", "stereotype": "", + "isComponentHeaderShown": True, }, - }, - "relationships": {}, - "interactive": {"elements": {}, "relationships": {}}, + }], + "edges": [], "assessments": {}, }, }], @@ -286,34 +284,29 @@ def test_dangling_manifest_surfaces_on_project(self): "id": "dep-diag", "title": "Deployment Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "DeploymentDiagram", - "size": {"width": 800, "height": 600}, - "elements": { - "a1": { - "id": "a1", - "name": "Orphan", - "type": "DeploymentArtifact", - "owner": None, - "bounds": { - "x": 0, "y": 0, "width": 160, "height": 40, + "nodes": [ + { + "id": "a1", "type": "deploymentArtifact", + "position": {"x": 0, "y": 0}, + "width": 160, "height": 40, + "data": { + "name": "Orphan", + "manifests": ["bogus-component"], }, - "manifests": ["bogus-component"], }, - "dc1": { - "id": "dc1", - "name": "Frontend", - "type": "DeploymentComponent", - "owner": None, - "bounds": { - "x": 0, "y": 80, "width": 160, "height": 100, + { + "id": "dc1", "type": "deploymentComponent", + "position": {"x": 0, "y": 80}, + "width": 160, "height": 100, + "data": { + "name": "Frontend", "stereotype": "component", + "isComponentHeaderShown": True, }, - "stereotype": "component", - "displayStereotype": True, }, - }, - "relationships": {}, - "interactive": {"elements": {}, "relationships": {}}, + ], + "edges": [], "assessments": {}, }, }], diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_deployment_converters.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_deployment_converters.py index 0a4c8a4da..af035506a 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_deployment_converters.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_deployment_converters.py @@ -1,4 +1,4 @@ -"""Tests for the Deployment diagram converters. +"""Tests for the Deployment diagram converters (v4 ``{nodes, edges}`` wire shape). Covers: * JSON -> ``DeploymentModel`` (``process_deployment_diagram``). @@ -6,7 +6,7 @@ * ``DeploymentAssociation`` discrimination (Artifact->Node vs Node<->Node). * ``DeploymentComponent`` round-trip. * Multiplicity parser / formatter. - * Owner-link dedup vs explicit ``DeploymentAssociation``. + * Parent-link dedup vs explicit ``DeploymentAssociation``. """ import pytest @@ -18,6 +18,7 @@ DeploymentComponent, DeploymentModel, DeploymentRelation, + InterfaceRequired, Node, NodeKind, ) @@ -41,174 +42,114 @@ # --------------------------------------------------------------------------- -# Fixtures (mirror the editor's real Deployment-diagram export and a -# hand-built multiplicity diagram) +# v4 fixture builders # --------------------------------------------------------------------------- -@pytest.fixture -def real_deployment_diagram(): - """Real-export style: Node holding nested Component, plus free-standing - Component / Artifact / Interface, with all four relationship types.""" +def _node(node_id, node_type, x, y, width, height, data, parent=None): + node = { + "id": node_id, "type": node_type, + "position": {"x": x, "y": y}, + "width": width, "height": height, + "measured": {"width": width, "height": height}, + "data": data, + } + if parent is not None: + node["parentId"] = parent + return node + + +def _edge(edge_id, edge_type, source, target, points, stereotype=None, + source_handle="right", target_handle="left"): + data = {"name": "", "label": "", "points": points, "isManuallyLayouted": False} + if stereotype is not None: + data["stereotype"] = stereotype return { - "title": "Deployment Diagram", + "id": edge_id, "source": source, "target": target, "type": edge_type, + "sourceHandle": source_handle, "targetHandle": target_handle, "data": data, + } + + +def _diagram(title, nodes, edges): + return { + "title": title, "model": { - "version": "3.0.0", - "type": "DeploymentDiagram", - "size": {"width": 1040, "height": 640}, - "elements": { - "n1": { - "id": "n1", "name": "ServerHost", "type": "DeploymentNode", - "owner": None, - "bounds": {"x": -500, "y": -300, "width": 440, "height": 340}, - "stereotype": "node", "displayStereotype": True, - }, - "cmp-inside": { - "id": "cmp-inside", "name": "AuthService", - "type": "DeploymentComponent", - "owner": "n1", - "bounds": {"x": -450, "y": -200, "width": 160, "height": 100}, - "displayStereotype": True, - }, - "cmp-free": { - "id": "cmp-free", "name": "Reporter", - "type": "DeploymentComponent", - "owner": None, - "bounds": {"x": 150, "y": -190, "width": 160, "height": 100}, - "displayStereotype": True, - }, - "n2": { - "id": "n2", "name": "Cache", "type": "DeploymentNode", - "owner": None, - "bounds": {"x": 230, "y": 0, "width": 160, "height": 100}, - "stereotype": "node", "displayStereotype": True, - }, - "a1": { - "id": "a1", "name": "ReportArchive", - "type": "DeploymentArtifact", - "owner": None, - "bounds": {"x": -250, "y": 120, "width": 160, "height": 40}, - }, - "i1": { - "id": "i1", "name": "MetricsApi", - "type": "DeploymentInterface", - "owner": None, - "bounds": {"x": -10, "y": 120, "width": 20, "height": 20}, - }, - }, - "relationships": { - "r-dep": { - "id": "r-dep", "name": "", "type": "DeploymentDependency", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 440, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 440, "y": 0}], - "source": {"direction": "Right", "element": "cmp-inside"}, - "target": {"direction": "Left", "element": "cmp-free"}, - "isManuallyLayouted": False, - }, - "r-assoc": { - "id": "r-assoc", "name": "", "type": "DeploymentAssociation", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 290, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 290, "y": 0}], - "source": {"direction": "Downright", "element": "n1"}, - "target": {"direction": "Left", "element": "n2"}, - "isManuallyLayouted": False, - }, - "r-prov": { - "id": "r-prov", "name": "", - "type": "DeploymentInterfaceProvided", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 280, "height": 225}, - "path": [{"x": 280, "y": 0}, {"x": 40, "y": 225}], - "source": {"direction": "Down", "element": "cmp-free"}, - "target": {"direction": "Downleft", "element": "i1"}, - "isManuallyLayouted": False, - }, - "r-req": { - "id": "r-req", "name": "", - "type": "DeploymentInterfaceRequired", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 99, "height": 63}, - "path": [{"x": 0, "y": 23}, {"x": 85, "y": 13}], - "source": {"direction": "Downright", "element": "a1"}, - "target": {"direction": "Bottomleft", "element": "i1"}, - "isManuallyLayouted": False, - }, - }, + "version": "4.0.0", "type": "DeploymentDiagram", "title": title, + "nodes": nodes, "edges": edges, "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, }, } +def _nodes_by_id(payload): + return {n["id"]: n for n in payload["nodes"]} + + +# --------------------------------------------------------------------------- +# Fixtures (mirror the editor's real Deployment-diagram export and a +# hand-built multiplicity diagram) +# --------------------------------------------------------------------------- + +@pytest.fixture +def real_deployment_diagram(): + """Real-export style: Node holding a nested Component, plus free-standing + Component / Artifact / Interface, with all four relationship types.""" + return _diagram( + "Deployment Diagram", + [ + _node("n1", "deploymentNode", -500, -300, 440, 340, + {"name": "ServerHost", "stereotype": "node", "isComponentHeaderShown": True}), + _node("cmp-inside", "deploymentComponent", 50, 100, 160, 100, + {"name": "AuthService", "stereotype": "", "isComponentHeaderShown": True}, + parent="n1"), + _node("cmp-free", "deploymentComponent", 150, -190, 160, 100, + {"name": "Reporter", "stereotype": "", "isComponentHeaderShown": True}), + _node("n2", "deploymentNode", 230, 0, 160, 100, + {"name": "Cache", "stereotype": "node", "isComponentHeaderShown": True}), + _node("a1", "deploymentArtifact", -250, 120, 160, 40, + {"name": "ReportArchive", "manifests": []}), + _node("i1", "deploymentInterface", -10, 120, 20, 20, {"name": "MetricsApi"}), + ], + [ + _edge("r-dep", "DeploymentDependency", "cmp-inside", "cmp-free", + [{"x": -290, "y": -150}, {"x": 150, "y": -150}]), + _edge("r-assoc", "DeploymentAssociation", "n1", "n2", + [{"x": -60, "y": 40}, {"x": 230, "y": 40}], + source_handle="right-bottom"), + _edge("r-prov", "DeploymentProvidedInterface", "cmp-free", "i1", + [{"x": 230, "y": -90}, {"x": 0, "y": 140}], + source_handle="bottom", target_handle="left-bottom"), + _edge("r-req", "DeploymentRequiredInterface", "a1", "i1", + [{"x": -90, "y": 160}, {"x": -10, "y": 140}], + source_handle="right-bottom", target_handle="bottom-left"), + ], + ) + + @pytest.fixture def multiplicity_deployment_diagram(): - """Hand-built style: `device` Node holding `[3]`-multiplicity artifact, + """Hand-built style: `device` Node holding a `[3]`-multiplicity artifact, plus a Node-Node DeploymentAssociation (CommunicationPath).""" - return { - "title": "Deployment Diagram", - "model": { - "version": "3.0.0", - "type": "DeploymentDiagram", - "size": {"width": 1400, "height": 740}, - "elements": { - "elem-edge-device": { - "id": "elem-edge-device", - "name": "EdgeDevice", "type": "DeploymentNode", - "owner": None, - "bounds": {"x": 100, "y": 100, "width": 320, "height": 260}, - "stereotype": "device", "displayStereotype": True, - }, - "elem-agent-runtime": { - "id": "elem-agent-runtime", - "name": "agent-runtime [3]", "type": "DeploymentArtifact", - "owner": "elem-edge-device", - "bounds": {"x": 140, "y": 180, "width": 200, "height": 60}, - }, - "elem-cloud": { - "id": "elem-cloud", - "name": "Cloud", "type": "DeploymentNode", - "owner": None, - "bounds": {"x": 620, "y": 100, "width": 280, "height": 200}, - "stereotype": "node", "displayStereotype": True, - }, - }, - "relationships": { - "rel-artifact-deploys": { - "id": "rel-artifact-deploys", - "name": "", "type": "DeploymentAssociation", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 1, "height": 120}, - "path": [{"x": 0, "y": 0}, {"x": 0, "y": 120}], - "source": { - "element": "elem-agent-runtime", "direction": "Down", - }, - "target": { - "element": "elem-edge-device", "direction": "Down", - }, - "isManuallyLayouted": False, - "stereotype": "", - }, - "rel-comm": { - "id": "rel-comm", - "name": "", "type": "DeploymentAssociation", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 200, "y": 0}], - "source": { - "element": "elem-edge-device", "direction": "Right", - }, - "target": { - "element": "elem-cloud", "direction": "Left", - }, - "isManuallyLayouted": False, - "stereotype": "", - }, - }, - "interactive": {"elements": {}, "relationships": {}}, - "assessments": {}, - }, - } + return _diagram( + "Deployment Diagram", + [ + _node("elem-edge-device", "deploymentNode", 100, 100, 320, 260, + {"name": "EdgeDevice", "stereotype": "device", "isComponentHeaderShown": True}), + _node("elem-agent-runtime", "deploymentArtifact", 40, 80, 200, 60, + {"name": "agent-runtime [3]", "manifests": []}, + parent="elem-edge-device"), + _node("elem-cloud", "deploymentNode", 620, 100, 280, 200, + {"name": "Cloud", "stereotype": "node", "isComponentHeaderShown": True}), + ], + [ + _edge("rel-artifact-deploys", "DeploymentAssociation", + "elem-agent-runtime", "elem-edge-device", + [{"x": 240, "y": 240}, {"x": 240, "y": 360}], stereotype="", + source_handle="bottom", target_handle="bottom"), + _edge("rel-comm", "DeploymentAssociation", "elem-edge-device", "elem-cloud", + [{"x": 420, "y": 200}, {"x": 620, "y": 200}], stereotype=""), + ], + ) # --------------------------------------------------------------------------- @@ -219,8 +160,8 @@ class TestProcessDeploymentDiagram: def test_real_diagram_constructs(self, real_deployment_diagram): model = process_deployment_diagram(real_deployment_diagram) assert isinstance(model, DeploymentModel) - # 2 Nodes (ServerHost, Cache); 2 Artifacts from DeploymentComponent - # synthesis + 1 native ReportArchive = 3 artifacts total; 1 Interface. + # 2 Nodes (ServerHost, Cache); 2 DeploymentComponents + 1 native + # ReportArchive = 3 artifacts total; 1 Interface. assert len(model.all_nodes()) == 2 assert len(model.all_artifacts()) == 3 assert len(model.interfaces) == 1 @@ -232,29 +173,27 @@ def test_deployment_component_becomes_deployment_component_without_manifests( components = [a for a in model.all_artifacts() if isinstance(a, DeploymentComponent)] assert sorted(c.name for c in components) == ["AuthService", "Reporter"] - # The element's own id is never fabricated into manifests. + # The node's own id is never fabricated into manifests. assert all(c.manifests == [] for c in components) - def test_artifact_manifests_are_read_from_the_element(self): - payload = {"title": "T", "model": {"elements": {"a1": { - "id": "a1", "name": "Coder", "type": "DeploymentArtifact", "owner": None, - "manifests": ["component-1"], - }}, "relationships": {}}} + def test_artifact_manifests_are_read_from_the_node(self): + payload = _diagram("T", [_node("a1", "deploymentArtifact", 0, 0, 160, 40, + {"name": "Coder", "manifests": ["component-1"]})], []) (artifact,) = process_deployment_diagram(payload).all_artifacts() assert type(artifact) is Artifact assert artifact.manifests == ["component-1"] - def test_owner_chain_nests_artifact_in_node(self, real_deployment_diagram): + def test_parent_chain_nests_artifact_in_node(self, real_deployment_diagram): model = process_deployment_diagram(real_deployment_diagram) server_host = next(n for n in model.all_nodes() if n.name == "ServerHost") - # cmp-inside is the synthetic Artifact for AuthService. + # cmp-inside is the DeploymentComponent AuthService. nested_names = [a.name for a in server_host.nested_artifacts] assert "AuthService" in nested_names def test_multiplicity_parses_from_name(self, multiplicity_deployment_diagram): model = process_deployment_diagram(multiplicity_deployment_diagram) # Artifact name parses to clean name + Multiplicity(3, 3) on the - # synthesised/explicit DeploymentRelation. + # explicit DeploymentRelation. artifact = next(a for a in model.all_artifacts()) assert artifact.name == "agent-runtime" rels = [r for r in model.relationships if isinstance(r, DeploymentRelation)] @@ -280,19 +219,35 @@ def test_node_kind_resolved_from_stereotype(self, multiplicity_deployment_diagra assert edge.kind is NodeKind.DEVICE assert cloud.kind is NodeKind.GENERIC - def test_owner_link_and_explicit_edge_dedup(self, multiplicity_deployment_diagram): - """When both owner-nesting and an explicit DeploymentAssociation + def test_parent_link_and_explicit_edge_dedup(self, multiplicity_deployment_diagram): + """When both parent nesting and an explicit DeploymentAssociation encode the same artifact-on-node, only one DeploymentRelation is - emitted (the explicit one wins; the owner-link is dedup'd).""" + emitted (the explicit one wins; the parent link is dedup'd).""" model = process_deployment_diagram(multiplicity_deployment_diagram) relations = [r for r in model.relationships if isinstance(r, DeploymentRelation)] - # The fixture has an artifact owned by a node AND an explicit edge + # The fixture has an artifact inside a node AND an explicit edge # → exactly one DeploymentRelation, not two. assert len(relations) == 1 assert relations[0].source.name == "agent-runtime" assert relations[0].target.name == "EdgeDevice" + def test_required_interface_socket_variant_reads_as_required(self): + payload = _diagram( + "Sockets", + [ + _node("a", "deploymentArtifact", 0, 0, 160, 40, {"name": "App", "manifests": []}), + _node("i", "deploymentInterface", 300, 10, 20, 20, {"name": "Port"}), + ], + [_edge("req", "DeploymentRequiredThreeQuarterInterface", "a", "i", + [{"x": 160, "y": 20}, {"x": 300, "y": 20}])], + ) + model = process_deployment_diagram(payload) + (rel,) = model.relationships + assert isinstance(rel, InterfaceRequired) + out = deployment_object_to_json(model) + assert out["edges"][0]["type"] == "DeploymentRequiredThreeQuarterInterface" + # --------------------------------------------------------------------------- # BUML -> JSON @@ -303,9 +258,10 @@ def test_envelope_shape(self): model = DeploymentModel(name="Empty") out = deployment_object_to_json(model) assert out["type"] == "DeploymentDiagram" - assert out["version"] == "3.0.0" - assert out["elements"] == {} - assert out["relationships"] == {} + assert out["version"] == "4.0.0" + assert out["title"] == "Empty" + assert out["nodes"] == [] + assert out["edges"] == [] assert out["interactive"] == {"elements": {}, "relationships": {}} assert out["assessments"] == {} @@ -313,10 +269,9 @@ def test_emits_node_with_kind_stereotype(self): node = Node(name="EdgeDevice", kind=NodeKind.DEVICE) model = DeploymentModel(name="m", nodes={node}) out = deployment_object_to_json(model) - entries = [e for e in out["elements"].values() - if e["type"] == "DeploymentNode"] + entries = [n for n in out["nodes"] if n["type"] == "deploymentNode"] assert len(entries) == 1 - assert entries[0]["stereotype"] == "device" + assert entries[0]["data"]["stereotype"] == "device" def test_artifact_emits_multiplicity_in_name(self): node = Node(name="VM") @@ -328,9 +283,8 @@ def test_artifact_emits_multiplicity_in_name(self): name="m", nodes={node}, artifacts={artifact}, relationships={rel}, ) out = deployment_object_to_json(model) - artifact_entry = [e for e in out["elements"].values() - if e["type"] == "DeploymentArtifact"][0] - assert artifact_entry["name"] == "worker [3]" + artifact_entry = [n for n in out["nodes"] if n["type"] == "deploymentArtifact"][0] + assert artifact_entry["data"]["name"] == "worker [3]" def test_artifact_default_multiplicity_no_suffix(self): node = Node(name="VM") @@ -341,9 +295,8 @@ def test_artifact_default_multiplicity_no_suffix(self): name="m", nodes={node}, artifacts={artifact}, relationships={rel}, ) out = deployment_object_to_json(model) - artifact_entry = [e for e in out["elements"].values() - if e["type"] == "DeploymentArtifact"][0] - assert artifact_entry["name"] == "worker" + artifact_entry = [n for n in out["nodes"] if n["type"] == "deploymentArtifact"][0] + assert artifact_entry["data"]["name"] == "worker" def test_deployment_relation_and_communication_path_both_emit_association(self): n1 = Node(name="N1") @@ -356,9 +309,28 @@ def test_deployment_relation_and_communication_path_both_emit_association(self): relationships={rel, comm}, ) out = deployment_object_to_json(model) - assoc_types = {r["type"] for r in out["relationships"].values()} + assoc_types = {e["type"] for e in out["edges"]} assert assoc_types == {"DeploymentAssociation"} + def test_nested_model_without_layout_places_children_inside_parents(self): + """A model built in Python has no editor layout: a nested node and its + artifact sit inside their parents, parents first.""" + host = Node(name="Host") + runtime = Node(name="Runtime") + host.add_nested_node(runtime) + artifact = Artifact(name="app") + runtime.add_artifact(artifact) + model = DeploymentModel(name="m", nodes={host}, artifacts=set()) + out = deployment_object_to_json(model) + nodes = {n["data"]["name"]: n for n in out["nodes"]} + order = [n["data"]["name"] for n in out["nodes"]] + assert order.index("Host") < order.index("Runtime") < order.index("app") + for child_name, parent_name in (("Runtime", "Host"), ("app", "Runtime")): + child, parent = nodes[child_name], nodes[parent_name] + assert child["parentId"] == parent["id"] + assert child["position"]["x"] + child["width"] <= parent["width"] + assert child["position"]["y"] + child["height"] <= parent["height"] + # --------------------------------------------------------------------------- # Round-trip identity @@ -368,33 +340,30 @@ class TestRoundTrip: def test_real_diagram_ids_survive(self, real_deployment_diagram): model = process_deployment_diagram(real_deployment_diagram) out = deployment_object_to_json(model) - in_elements = sorted(real_deployment_diagram["model"]["elements"].keys()) - out_elements = sorted(out["elements"].keys()) - assert in_elements == out_elements + assert sorted(_nodes_by_id(out)) == sorted(_nodes_by_id(real_deployment_diagram["model"])) + assert sorted(e["id"] for e in out["edges"]) == sorted( + e["id"] for e in real_deployment_diagram["model"]["edges"]) def test_real_diagram_types_survive(self, real_deployment_diagram): model = process_deployment_diagram(real_deployment_diagram) - out = deployment_object_to_json(model) - for elem_id, original in ( - real_deployment_diagram["model"]["elements"].items() - ): - assert out["elements"][elem_id]["type"] == original["type"] + out_nodes = _nodes_by_id(deployment_object_to_json(model)) + for node_id, original in _nodes_by_id(real_deployment_diagram["model"]).items(): + assert out_nodes[node_id]["type"] == original["type"] - def test_real_diagram_owner_chains_survive(self, real_deployment_diagram): + def test_real_diagram_parent_chains_survive(self, real_deployment_diagram): model = process_deployment_diagram(real_deployment_diagram) - out = deployment_object_to_json(model) - for elem_id, original in ( - real_deployment_diagram["model"]["elements"].items() - ): - assert out["elements"][elem_id].get("owner") == original.get("owner") + out_nodes = _nodes_by_id(deployment_object_to_json(model)) + for node_id, original in _nodes_by_id(real_deployment_diagram["model"]).items(): + assert out_nodes[node_id].get("parentId") == original.get("parentId") + assert out_nodes[node_id]["position"] == original["position"] def test_multiplicity_round_trip_preserves_suffix( self, multiplicity_deployment_diagram, ): model = process_deployment_diagram(multiplicity_deployment_diagram) out = deployment_object_to_json(model) - artifact = out["elements"]["elem-agent-runtime"] - assert artifact["name"] == "agent-runtime [3]" + artifact = _nodes_by_id(out)["elem-agent-runtime"] + assert artifact["data"]["name"] == "agent-runtime [3]" # --------------------------------------------------------------------------- @@ -449,9 +418,8 @@ def test_round_trips_via_builder(self, real_deployment_diagram): source = deployment_model_to_code(model) result = deployment_buml_to_json(source) assert result["type"] == "DeploymentDiagram" - in_ids = sorted(real_deployment_diagram["model"]["elements"].keys()) - out_ids = sorted(result["elements"].keys()) - assert in_ids == out_ids + assert result["version"] == "4.0.0" + assert sorted(_nodes_by_id(result)) == sorted(_nodes_by_id(real_deployment_diagram["model"])) def test_exec_failure_raises_conversion_error(self): with pytest.raises(ConversionError): @@ -480,59 +448,49 @@ def test_multiplicity_survives_full_pipeline(self, multiplicity_deployment_diagr source = deployment_model_to_code(model) result = deployment_buml_to_json(source) # Find the artifact in the result. - artifacts = [e for e in result["elements"].values() - if e["type"] == "DeploymentArtifact"] + artifacts = [n for n in result["nodes"] if n["type"] == "deploymentArtifact"] assert len(artifacts) == 1 - assert artifacts[0]["name"] == "agent-runtime [3]" + assert artifacts[0]["data"]["name"] == "agent-runtime [3]" # --------------------------------------------------------------------------- -# agentModelRef threading (processor reads WME wire key onto field) +# agentModelRef threading (processor reads the wire key onto the field) # --------------------------------------------------------------------------- class TestAgentModelRefProcessor: - def _make_payload(self, elem_type: str, agent_model_ref=None) -> dict: - elem = { - "type": elem_type, - "name": "Researcher", - } + def _make_payload(self, node_type: str, agent_model_ref=None) -> dict: + data = {"name": "Researcher"} if agent_model_ref is not None: - elem["agentModelRef"] = agent_model_ref - return { - "title": "T", - "model": { - "elements": {"elem-1": elem}, - "relationships": {}, - }, - } + data["agentModelRef"] = agent_model_ref + return _diagram("T", [_node("elem-1", node_type, 0, 0, 160, 40, data)], []) def test_deployment_artifact_with_agent_model_ref(self): - """DeploymentArtifact JSON with agentModelRef → artifact.agent_model_ref set.""" - payload = self._make_payload("DeploymentArtifact", agent_model_ref="uuid-abc") + """deploymentArtifact with agentModelRef → artifact.agent_model_ref set.""" + payload = self._make_payload("deploymentArtifact", agent_model_ref="uuid-abc") model = process_deployment_diagram(payload) artifacts = list(model.all_artifacts()) assert len(artifacts) == 1 assert artifacts[0].agent_model_ref == "uuid-abc" def test_deployment_artifact_without_agent_model_ref(self): - """DeploymentArtifact JSON with no agentModelRef → agent_model_ref is None.""" - payload = self._make_payload("DeploymentArtifact") + """deploymentArtifact with no agentModelRef → agent_model_ref is None.""" + payload = self._make_payload("deploymentArtifact") model = process_deployment_diagram(payload) artifacts = list(model.all_artifacts()) assert len(artifacts) == 1 assert artifacts[0].agent_model_ref is None def test_deployment_component_with_agent_model_ref(self): - """DeploymentComponent also threads agentModelRef.""" - payload = self._make_payload("DeploymentComponent", agent_model_ref="uuid-xyz") + """deploymentComponent also threads agentModelRef.""" + payload = self._make_payload("deploymentComponent", agent_model_ref="uuid-xyz") model = process_deployment_diagram(payload) artifacts = list(model.all_artifacts()) assert len(artifacts) == 1 assert artifacts[0].agent_model_ref == "uuid-xyz" def test_deployment_component_without_agent_model_ref(self): - """DeploymentComponent with no agentModelRef → agent_model_ref is None.""" - payload = self._make_payload("DeploymentComponent") + """deploymentComponent with no agentModelRef → agent_model_ref is None.""" + payload = self._make_payload("deploymentComponent") model = process_deployment_diagram(payload) artifacts = list(model.all_artifacts()) assert len(artifacts) == 1 diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_diagram_title_names.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_diagram_title_names.py index ed93bbdbd..dee976d4b 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_diagram_title_names.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_diagram_title_names.py @@ -12,7 +12,7 @@ process_object_diagram, ) -EMPTY = {"elements": {}, "relationships": {}} +EMPTY = {"version": "4.0.0", "nodes": [], "edges": []} @pytest.mark.parametrize("process", [ diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_duplicate_association_ends.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_duplicate_association_ends.py index 3d2cda67e..a812113af 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_duplicate_association_ends.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_duplicate_association_ends.py @@ -22,21 +22,27 @@ def _class(cid, name): - return {"id": cid, "name": name, "type": "Class", "owner": None, - "attributes": [], "methods": []} + """A v4 ``class`` node.""" + return {"id": cid, "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": name, "stereotype": None, "attributes": [], "methods": []}} def _rel(rid, src_id, src_role, tgt_id, tgt_role, mult="0..*"): + """A v4 ``ClassBidirectional`` edge (roles live on ``edge.data``).""" return { - "id": rid, "name": rid, "type": "ClassBidirectional", - "source": {"element": src_id, "multiplicity": mult, "role": src_role}, - "target": {"element": tgt_id, "multiplicity": mult, "role": tgt_role}, + "id": rid, "type": "ClassBidirectional", "source": src_id, "target": tgt_id, + "data": {"name": rid, + "sourceRole": src_role, "sourceMultiplicity": mult, + "targetRole": tgt_role, "targetMultiplicity": mult, + "points": []}, } def _diagram(elements, relationships): - return {"title": "Model", "model": {"elements": elements, - "relationships": relationships}} + return {"title": "Model", "model": {"version": "4.0.0", "type": "ClassDiagram", + "nodes": list(elements.values()), + "edges": list(relationships.values())}} def _assert_end_names_unique_per_class(domain_model): @@ -54,7 +60,7 @@ def test_two_links_same_role_on_one_class_does_not_crash(): deterministically suffixed.""" elements = {"loan": _class("loan", "Loan"), "member": _class("member", "Member")} relationships = { - # target.role is the Member end, owned by the source class (Loan). + # targetRole is the Member end, owned by the source class (Loan). "r1": _rel("r1", "loan", "borrower", "member", "member"), "r2": _rel("r2", "loan", "returner", "member", "member"), } diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_editor_element_ids.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_editor_element_ids.py index 28c5f4af7..ddcf6dae6 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_editor_element_ids.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_editor_element_ids.py @@ -60,27 +60,27 @@ def _diagram(model: dict, diagram_id: str, title: str = "Model") -> dict: QUANTUM = _diagram({"cols": [["H", 1], ["•", "X"], ["Swap", "Swap"]], "gateMetadata": {}}, "q-diagram", "Bell") -def _element(element_id, element_type, name, owner=None, **extra): - return {"id": element_id, "type": element_type, "name": name, "owner": owner, - "bounds": {"x": 0, "y": 0, "width": 100, "height": 100}, **extra} +def _node(node_id, node_type, name, parent=None, **data): + node = {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, "width": 100, "height": 100, + "data": {"name": name, **data}} + return {**node, "parentId": parent} if parent else node -def _relationship(rel_id, rel_type, source, target): - return {"id": rel_id, "type": rel_type, "name": "", "owner": None, - "bounds": {"x": 0, "y": 0, "width": 1, "height": 1}, "path": [], - "source": {"element": source, "direction": "Right"}, "target": {"element": target, "direction": "Left"}} +def _edge(edge_id, edge_type, source, target): + return {"id": edge_id, "type": edge_type, "source": source, "target": target, + "sourceHandle": "Right", "targetHandle": "Left", "data": {"name": "", "points": []}} -DEPLOYMENT = _diagram({"type": "DeploymentDiagram", "elements": { - "node-1": _element("node-1", "DeploymentNode", "server"), - "node-2": _element("node-2", "DeploymentNode", "db"), - "artifact-1": _element("artifact-1", "DeploymentArtifact", "api", "node-1"), -}, "relationships": {"path-1": _relationship("path-1", "DeploymentAssociation", "node-1", "node-2")}}, +DEPLOYMENT = _diagram({"version": "4.0.0", "type": "DeploymentDiagram", "nodes": [ + _node("node-1", "deploymentNode", "server", stereotype="node"), + _node("node-2", "deploymentNode", "db", stereotype="node"), + _node("artifact-1", "deploymentArtifact", "api", "node-1"), +], "edges": [_edge("path-1", "DeploymentAssociation", "node-1", "node-2")]}, "deployment-diagram", "Cloud") -COMPONENT = _diagram({"type": "ComponentDiagram", "elements": { - "component-1": _element("component-1", "Component", "Orders"), - "component-2": _element("component-2", "Component", "Billing"), -}, "relationships": {"dep-1": _relationship("dep-1", "ComponentDependency", "component-1", "component-2")}}, +COMPONENT = _diagram({"version": "4.0.0", "type": "ComponentDiagram", "nodes": [ + _node("component-1", "component", "Orders", stereotype=""), + _node("component-2", "component", "Billing", stereotype=""), +], "edges": [_edge("dep-1", "ComponentDependency", "component-1", "component-2")]}, "component-diagram", "Parts") @@ -108,9 +108,8 @@ def _editor_ids(model_json: dict) -> set: while pending: value = pending.pop() if isinstance(value, dict): - for key in ("elements", "relationships", "components"): - if isinstance(value.get(key), dict): - ids.update(value[key]) + if isinstance(value.get("components"), dict): # an agent diagram's intents, tools, ... + ids.update(value["components"]) if isinstance(value.get("id"), str): ids.add(value["id"]) pending.extend(value.values()) @@ -133,6 +132,10 @@ def test_the_ids_are_editor_ids_unique_in_the_model(kind): assert set(ids) <= _editor_ids(model_json) +def _ids(items) -> set: + return {item["id"] for item in items} + + def _with_id(model, metaclass_name): return {e.name: e.id for e in _own_elements(model) if type(e).__name__ == metaclass_name} @@ -140,13 +143,13 @@ def _with_id(model, metaclass_name): def test_the_elements_the_editor_traces_have_their_ids(): models = _models() agent, agent_json = models["agent"] - states = {e["name"]: e_id for e_id, e in agent_json["elements"].items() if e["type"] == "AgentState"} + states = {n["data"]["name"]: n["id"] for n in agent_json["nodes"] if n["type"] == "AgentState"} assert _with_id(agent, "AgentState") == states - intents = {e["name"]: e_id for e_id, e in {**agent_json["elements"], **agent_json.get("components", {})}.items() - if e["type"] == "AgentIntent"} + intents = {c["name"]: c_id for c_id, c in agent_json.get("components", {}).items() if c["type"] == "AgentIntent"} + intents.update({n["data"]["name"]: n["id"] for n in agent_json["nodes"] if n["type"] == "AgentIntent"}) assert _with_id(agent, "Intent") == intents transitions = [e for e in _own_elements(agent) if type(e).__name__ == "Transition"] - assert transitions and all(t.id in agent_json["relationships"] for t in transitions) + assert transitions and all(t.id in _ids(agent_json["edges"]) for t in transitions) gui, gui_json = models["gui"] pages = {page["id"] for page in gui_json["pages"]} @@ -156,12 +159,12 @@ def test_the_elements_the_editor_traces_have_their_ids(): assert not any(e.id for e in _own_elements(gui) if type(e).__name__ in ("Text", "ViewContainer")) nn, nn_json = models["nn"] - layers = {e_id for e_id, e in nn_json["elements"].items() if e["type"].endswith("Layer")} + layers = {n["id"] for n in nn_json["nodes"] if n["type"].endswith("Layer")} assert {e.id for e in _own_elements(nn) if type(e).__name__ in ("Conv2D", "PoolingLayer", "FlattenLayer", "LinearLayer")} == layers assert {e.id for e in _own_elements(nn) if type(e).__name__ == "Dataset"} == { - e_id for e_id, e in nn_json["elements"].items() if e["type"] in ("TrainingDataset", "TestDataset")} - (container,) = [e_id for e_id, e in nn_json["elements"].items() if e["type"] == "NNContainer"] + n["id"] for n in nn_json["nodes"] if n["type"] in ("TrainingDataset", "TestDataset")} + (container,) = [n["id"] for n in nn_json["nodes"] if n["type"] == "NNContainer"] assert nn.id == container quantum, _ = models["quantum"] @@ -244,5 +247,5 @@ def test_a_model_converted_back_to_json_keeps_the_editor_ids(kind): back = to_json(model) back = back.get("model", back) kept = {e.id for e in _own_elements(model) if e.id} | ({model.id} if getattr(model, "id", None) else set()) - assert kept <= set(back["elements"]) | set(back["relationships"]) + assert kept <= _ids(back["nodes"]) | _ids(back["edges"]) assert kept <= _editor_ids(model_json) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_element_id_references.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_element_id_references.py index c24fce6c6..c57a7b55f 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_element_id_references.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_element_id_references.py @@ -42,74 +42,86 @@ class ids came back, but an object link on a composition lost its json_to_buml_project, ) -_BOUNDS = {"x": 0, "y": 0, "width": 200, "height": 100} +def _node(node_id, node_type, data): + return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "measured": {"width": 200, "height": 100}, "data": data} def _class_model(): def cls(cid, name, attributes=(), methods=()): - return {"id": cid, "name": name, "type": "Class", "owner": None, "bounds": _BOUNDS, - "attributes": list(attributes), "methods": list(methods)} + return _node(cid, "class", {"name": name, "attributes": list(attributes), "methods": list(methods)}) - def attr(aid, owner, name): - return {"id": aid, "name": name, "type": "ClassAttribute", "owner": owner, "bounds": _BOUNDS, - "visibility": "public", "attributeType": "str"} + def attr(aid, name): + return {"id": aid, "name": name, "visibility": "public", "attributeType": "str"} - def end(element, role, multiplicity): - return {"element": element, "role": role, "multiplicity": multiplicity} + def association(rid, rel_type, name, source, source_end, target, target_end): + (source_role, source_multiplicity), (target_role, target_multiplicity) = source_end, target_end + return {"id": rid, "type": rel_type, "source": source, "target": target, + "sourceHandle": "right", "targetHandle": "left", + "data": {"name": name, "sourceRole": source_role, "sourceMultiplicity": source_multiplicity, + "targetRole": target_role, "targetMultiplicity": target_multiplicity, + "sourceNavigable": True, "targetNavigable": True, "points": []}} return { - "type": "ClassDiagram", - "elements": { - "c-library": cls("c-library", "Library", ["a-lib-name"]), - "a-lib-name": attr("a-lib-name", "c-library", "name"), - "c-book": cls("c-book", "Book", ["a-title"], ["m-renew"]), - "a-title": attr("a-title", "c-book", "title"), - "m-renew": {"id": "m-renew", "name": "+ renew(): str", "type": "ClassMethod", - "owner": "c-book", "bounds": _BOUNDS}, - "c-shelf": cls("c-shelf", "Shelf", ["a-code"]), - "a-code": attr("a-code", "c-shelf", "code"), - }, - "relationships": { - "r-holds": {"id": "r-holds", "name": "holds", "type": "ClassBidirectional", - "source": end("c-library", "library", "1"), "target": end("c-book", "books", "0..*")}, + "version": "4.0.0", "type": "ClassDiagram", + "nodes": [ + cls("c-library", "Library", [attr("a-lib-name", "name")]), + cls("c-book", "Book", [attr("a-title", "title")], + [{"id": "m-renew", "name": "renew", "visibility": "public", + "attributeType": "str", "returnType": "str", "parameters": []}]), + cls("c-shelf", "Shelf", [attr("a-code", "code")]), + ], + "edges": [ + association("r-holds", "ClassBidirectional", "holds", + "c-library", ("library", "1"), "c-book", ("books", "0..*")), # Composition: the source is the part, the target the whole. - "r-contains": {"id": "r-contains", "name": "contains", "type": "ClassComposition", - "source": end("c-shelf", "shelves", "0..*"), "target": end("c-library", "home", "1")}, - }, + association("r-contains", "ClassComposition", "contains", + "c-shelf", ("shelves", "0..*"), "c-library", ("home", "1")), + ], } def _object_model(class_model): def obj(oid, name, class_id, slots): - return {"id": oid, "name": name, "type": "ObjectName", "owner": None, "bounds": _BOUNDS, - "attributes": slots, "methods": [], "classId": class_id} + return _node(oid, "objectName", {"name": name, "classId": class_id, "attributes": slots, "methods": []}) - def slot(sid, owner, text, attribute_id): - return {"id": sid, "name": text, "type": "ObjectAttribute", "owner": owner, "bounds": _BOUNDS, - "attributeId": attribute_id} + def slot(sid, name, value, attribute_id): + return {"id": sid, "name": name, "attributeType": "str", "value": value, "attributeId": attribute_id} def link(lid, name, source, target, association_id): - return {"id": lid, "name": name, "type": "ObjectLink", "owner": None, "bounds": _BOUNDS, - "path": [], "source": {"element": source}, "target": {"element": target}, - "associationId": association_id} + return {"id": lid, "type": "ObjectLink", "source": source, "target": target, + "sourceHandle": "right", "targetHandle": "left", + "data": {"name": name, "associationId": association_id, "points": []}} return { - "type": "ObjectDiagram", - "elements": { - "o-lib": obj("o-lib", "city", "c-library", ["s-name"]), - "s-name": slot("s-name", "o-lib", "name = City", "a-lib-name"), - "o-book": obj("o-book", "dune", "c-book", ["s-title"]), - "s-title": slot("s-title", "o-book", "title = Dune", "a-title"), - "o-shelf": obj("o-shelf", "top", "c-shelf", []), - }, - "relationships": { - "l-holds": link("l-holds", "books", "o-lib", "o-book", "r-holds"), - "l-contains": link("l-contains", "home", "o-shelf", "o-lib", "r-contains"), - }, + "version": "4.0.0", "type": "ObjectDiagram", + "nodes": [ + obj("o-lib", "city", "c-library", [slot("s-name", "name", "City", "a-lib-name")]), + obj("o-book", "dune", "c-book", [slot("s-title", "title", "Dune", "a-title")]), + obj("o-shelf", "top", "c-shelf", []), + ], + "edges": [ + link("l-holds", "books", "o-lib", "o-book", "r-holds"), + link("l-contains", "home", "o-shelf", "o-lib", "r-contains"), + ], "referenceDiagramData": copy.deepcopy(class_model), } +def _class_names(class_model): + """Name of every class node, member row and edge of a v4 class diagram, by id.""" + names = {} + for node in class_model["nodes"]: + data = node.get("data") or {} + names[node["id"]] = data.get("name") + for key in ("attributes", "methods"): + for row in data.get(key) or []: + names[row["id"]] = row.get("name") + for edge in class_model["edges"]: + names[edge["id"]] = (edge.get("data") or {}).get("name") + return names + + def _gui_model(): table = {"type": "table", "attributes": { "id": "t-books", "chart-title": "Books", "data-source": "c-book", @@ -128,9 +140,8 @@ def _gui_model(): def _project(): class_model = _class_model() - component_model = {"type": "ComponentDiagram", "relationships": {}, "elements": { - "k-api": {"id": "k-api", "name": "Api", "type": "Component", "owner": None, - "bounds": _BOUNDS, "realizes": ["c-book"]}}} + component_model = {"version": "4.0.0", "type": "ComponentDiagram", "edges": [], "nodes": [ + _node("k-api", "component", {"name": "Api", "stereotype": "component", "realizes": ["c-book"]})]} return { "id": "p", "type": "Project", "name": "Lib", "createdAt": "2026-01-01T00:00:00Z", "diagrams": { @@ -169,13 +180,13 @@ def walk(component): def _object_refs(object_model): - elements = object_model["elements"] - names = {key: e["name"] for key, e in elements.items()} - objects = {e["name"]: e["classId"] for e in elements.values() if e["type"] == "ObjectName"} - slots = {e["name"].split("=")[0].strip(): e["attributeId"] - for e in elements.values() if e["type"] == "ObjectAttribute"} - links = {frozenset((names[r["source"]["element"]], names[r["target"]["element"]])): r["associationId"] - for r in object_model["relationships"].values() if r["type"] == "ObjectLink"} + names = {node["id"]: node["data"]["name"] for node in object_model["nodes"]} + objects = {node["data"]["name"]: node["data"].get("classId") for node in object_model["nodes"] + if node["type"] == "objectName"} + slots = {row["name"].split("=")[0].strip(): row.get("attributeId") + for node in object_model["nodes"] for row in node["data"].get("attributes") or []} + links = {frozenset((names[e["source"]], names[e["target"]])): e["data"].get("associationId") + for e in object_model["edges"] if e["type"] == "ObjectLink"} return objects, slots, links @@ -183,8 +194,7 @@ def test_project_python_round_trip_keeps_ids_and_every_reference(tmp_path): back = _round_trip(_project(), tmp_path, emit_ids=True) class_model = _model(back, "ClassDiagram") - assert set(_class_model()["elements"]) <= set(class_model["elements"]) - assert {"r-holds", "r-contains"} <= set(class_model["relationships"]) + assert set(_class_names(_class_model())) <= set(_class_names(class_model)) assert _object_refs(_model(back, "ObjectDiagram")) == _object_refs(_object_model(_class_model())) @@ -195,18 +205,31 @@ def test_project_python_round_trip_keeps_ids_and_every_reference(tmp_path): assert components["b-renew"]["data-method"] == "m-renew" assert components["b-renew"]["data-method-class"] == "c-book" - assert _model(back, "ComponentDiagram")["elements"]["k-api"]["realizes"] == ["c-book"] + api = next(n for n in _model(back, "ComponentDiagram")["nodes"] if n["id"] == "k-api") + assert api["data"]["realizes"] == ["c-book"] reimported = json_to_buml_project(ProjectInput.model_validate(back)) assert reimported._cross_diagram_errors["errors"] == [] +def test_a_knowledge_graph_keeps_its_diagram_id_and_title(tmp_path): + project = _project() + project["diagrams"]["KnowledgeGraphDiagram"] = [{"id": "d-kg", "title": "My Ontology", "model": { + "type": "KnowledgeGraphDiagram", "version": "1.0.0", "edges": [], + "nodes": [{"id": "n-person", "nodeType": "class", "label": "Person", "iri": "http://ex.org/Person"}]}}] + + (kg,) = _round_trip(project, tmp_path, emit_ids=True)["diagrams"]["KnowledgeGraphDiagram"] + + assert (kg["id"], kg["title"]) == ("d-kg", "My Ontology") + assert [n["id"] for n in kg["model"]["nodes"]] == ["n-person"] + + def test_object_links_on_compositions_keep_their_association(tmp_path): """Without ids in the .py, references still resolve to the re-imported class diagram.""" back = _round_trip(_project(), tmp_path, emit_ids=False) class_model = _model(back, "ClassDiagram") objects, slots, links = _object_refs(_model(back, "ObjectDiagram")) - names = {key: e.get("name") for key, e in {**class_model["elements"], **class_model["relationships"]}.items()} + names = _class_names(class_model) assert {name: names.get(ref) for name, ref in objects.items()} == {"city": "Library", "dune": "Book", "top": "Shelf"} assert {name: names.get(ref) for name, ref in slots.items()} == {"name": "name", "title": "title"} assert sorted(names.get(ref) for ref in links.values()) == ["contains", "holds"] @@ -216,11 +239,12 @@ def test_objects_resolve_a_renamed_class_and_attribute_by_id(): """The object keeps the old class name and the snapshot of the old class diagram; the element ids still find the renamed class and attribute.""" renamed = _class_model() - renamed["elements"]["c-book"]["name"] = "Novel" - renamed["elements"]["a-title"]["name"] = "heading" + book = next(n for n in renamed["nodes"] if n["id"] == "c-book") + book["data"]["name"] = "Novel" + book["data"]["attributes"][0]["name"] = "heading" domain = process_class_diagram({"title": "Library", "model": renamed}) objects = _object_model(_class_model()) - objects["elements"]["o-book"]["className"] = "Book" + next(n for n in objects["nodes"] if n["id"] == "o-book")["data"]["className"] = "Book" object_model = process_object_diagram({"title": "Objects", "model": objects}, domain) @@ -278,7 +302,7 @@ def test_object_model_code_links_a_composition_to_its_association(tmp_path): with open(path, encoding="utf-8") as handle: exported = object_buml_to_json(handle.read(), class_model) - associations = sorted(r["associationId"] for r in exported["relationships"].values() if r["type"] == "ObjectLink") + associations = sorted(e["data"]["associationId"] for e in exported["edges"] if e["type"] == "ObjectLink") assert associations == ["r-contains", "r-holds"] @@ -320,11 +344,11 @@ async def post(): assert response.status_code == 200, response.text model = response.json()["model"] - names = {key: e["name"] for key, e in model["elements"].items() if e["type"] in ("Class", "ClassAttribute")} + names = _class_names(model) assert {key: names.get(key) for key in ("c-library", "a-lib-name", "c-book", "a-title")} == { "c-library": "Library", "a-lib-name": "name", "c-book": "Book", "a-title": "title"} assert "Author" in names.values() - assert "r-holds" in model["relationships"] + assert "r-holds" in {edge["id"] for edge in model["edges"]} def _library(book_name="Book", title_name="title", association_name="writes", book_id=None): diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_element_id_roundtrip.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_element_id_roundtrip.py index ce603b162..13d342e1f 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_element_id_roundtrip.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_element_id_roundtrip.py @@ -31,9 +31,34 @@ RELATIONSHIP_IDS = {"holds": "ClassBidirectional", "lends": "ClassBidirectional", "inherits": "ClassInheritance"} +_NODE_KIND = {"Enumeration": "Enumeration", "Abstract": "AbstractClass", "Interface": "Interface"} + + +def _elements(model_json): + """Every element of a v4 class diagram by id: ``(kind, element, owner id)``. + + Class nodes map to Class / AbstractClass / Enumeration, their attribute and + method rows to ClassAttribute / ClassMethod, other nodes keep their type.""" + out = {} + for node in model_json["nodes"]: + data = node.get("data") or {} + if node["type"] == "class": + out[node["id"]] = (_NODE_KIND.get(data.get("stereotype"), "Class"), node, None) + for key, kind in (("attributes", "ClassAttribute"), ("methods", "ClassMethod")): + for row in data.get(key) or []: + out[row["id"]] = (kind, row, node["id"]) + else: + out[node["id"]] = (node["type"], node, None) + return out + + def _ids(model_json): - return ({key: e["type"] for key, e in model_json["elements"].items()}, - {key: r["type"] for key, r in model_json["relationships"].items()}) + return ({key: kind for key, (kind, _, _) in _elements(model_json).items()}, + {edge["id"]: edge["type"] for edge in model_json["edges"]}) + + +def _edge(model_json, edge_id): + return next(edge for edge in model_json["edges"] if edge["id"] == edge_id) def test_json_to_buml_keeps_every_editor_id(): @@ -61,17 +86,17 @@ def test_json_buml_json_reuses_every_id(): for key, rel_type in RELATIONSHIP_IDS.items(): assert relationships.get(key) == rel_type, key # References use the same ids. - assert exported["elements"]["lib-name"]["owner"] == "library" - assert exported["elements"]["library"]["attributes"] == ["lib-name"] - assert exported["relationships"]["inherits"]["source"]["element"] == "novel" - assert exported["relationships"]["inherits"]["target"]["element"] == "book" + assert _elements(exported)["lib-name"][2] == "library" + assert [row["id"] for row in _elements(exported)["library"][1]["data"]["attributes"]] == ["lib-name"] + assert _edge(exported, "inherits")["source"] == "novel" + assert _edge(exported, "inherits")["target"] == "book" def test_a_second_round_trip_gives_the_same_ids(): once = class_buml_to_json(process_class_diagram(_diagram())) twice = class_buml_to_json(process_class_diagram({"title": "Lending", "model": once})) - # OCL boxes and visual links are not model elements and are re-minted. - visual = ("ClassOCLConstraint", "ClassOCLLink", "ClassLinkRel", "Comments", "Link") + # OCL boxes, comments and visual links are not model elements and are re-minted. + visual = ("ClassOCLConstraint", "ClassOCLLink", "ClassLinkRel", "comment", "CommentLink") for side in (0, 1): assert ({k: t for k, t in _ids(once)[side].items() if t not in visual} == {k: t for k, t in _ids(twice)[side].items() if t not in visual}) @@ -81,9 +106,9 @@ def test_a_renamed_class_keeps_its_id(): model = process_class_diagram(_diagram()) model.get_class_by_name("Library").name = "Branch" exported = class_buml_to_json(model) - assert exported["elements"]["library"]["name"] == "Branch" - holds = exported["relationships"]["holds"] - assert {holds["source"]["element"], holds["target"]["element"]} == {"library", "book"} + assert _elements(exported)["library"][1]["data"]["name"] == "Branch" + holds = _edge(exported, "holds") + assert {holds["source"], holds["target"]} == {"library", "book"} def test_buml_code_has_no_ids_unless_enabled(tmp_path): @@ -114,20 +139,20 @@ def test_a_model_without_ids_gets_fresh_ones_and_unchanged_code(tmp_path): path = os.path.join(tmp_path, "model.py") domain_model_to_code(model, path) assert "id=" not in open(path, encoding="utf-8").read() - first, second = class_buml_to_json(model), class_buml_to_json(model) - for key in first["elements"]: + first, second = _elements(class_buml_to_json(model)), _elements(class_buml_to_json(model)) + for key in first: uuid.UUID(key) - assert set(first["elements"]).isdisjoint(second["elements"]) + assert set(first).isdisjoint(second) assert book.id is None # serialising does not write ids back def test_elements_sharing_an_id_are_both_kept(): a = Class(name="A", id="dup", attributes={Property(name="x", type=StringType, id="dup")}) b = Class(name="B", id="dup") - exported = class_buml_to_json(DomainModel(name="M", types={a, b})) - names = sorted((e["type"], e["name"]) for e in exported["elements"].values()) + elements = _elements(class_buml_to_json(DomainModel(name="M", types={a, b}))) + names = sorted((kind, element.get("data", element)["name"]) for kind, element, _ in elements.values()) assert names == [("Class", "A"), ("Class", "B"), ("ClassAttribute", "x")] - assert sum(1 for key in exported["elements"] if key == "dup") == 1 + assert sum(1 for key in elements if key == "dup") == 1 def test_unsafe_ids_are_replaced_with_a_warning(caplog): @@ -138,7 +163,7 @@ def test_unsafe_ids_are_replaced_with_a_warning(caplog): classes = [Class(name=f"C{i}", id=value) for i, value in enumerate(bad + good)] with caplog.at_level("WARNING"): exported = class_buml_to_json(DomainModel(name="M", types=set(classes))) - keys = set(exported["elements"]) + keys = set(_elements(exported)) assert keys.isdisjoint(bad) assert set(good) <= keys for key in keys - set(good): @@ -192,7 +217,8 @@ def pushed(workdir): def _with_ocl_box(text: str) -> dict: diagram = _diagram() - diagram["model"]["elements"]["ocl"]["constraint"] = text + ocl = next(node for node in diagram["model"]["nodes"] if node["id"] == "ocl") + ocl["data"]["expression"] = text return diagram @@ -201,14 +227,14 @@ def test_a_single_constraint_box_keeps_its_id(): model = process_class_diagram(_diagram()) (invariant,) = model.constraints assert invariant.id == "ocl" - assert class_buml_to_json(model)["elements"]["ocl"]["type"] == "ClassOCLConstraint" + assert _elements(class_buml_to_json(model))["ocl"][0] == "ClassOCLConstraint" def test_a_method_contract_box_keeps_its_id(): model = process_class_diagram(_with_ocl_box("context Library::renew(days: int) pre: days > 0")) (renew,) = model.get_class_by_name("Library").methods assert [c.id for c in renew.pre] == ["ocl"] - assert class_buml_to_json(model)["elements"]["ocl"]["type"] == "ClassOCLConstraint" + assert _elements(class_buml_to_json(model))["ocl"][0] == "ClassOCLConstraint" def test_the_constraints_of_a_box_with_several_have_no_id(): diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_gui_label_wrapped_inputs.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_gui_label_wrapped_inputs.py index cb41c9050..e514fd8eb 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_gui_label_wrapped_inputs.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_gui_label_wrapped_inputs.py @@ -38,14 +38,21 @@ def _classes(*names): class_json = None for name in names: one = class_diagram(name, [("title", "str"), ("done", "bool")]) - one["elements"][f"attr-{name}-done"]["isOptional"] = True + for row in one["nodes"][0]["data"]["attributes"]: + row["isOptional"] = row["name"] == "done" if class_json is None: class_json = one else: - class_json["elements"].update(one["elements"]) + class_json["nodes"].extend(one["nodes"]) return class_json +def _attributes(class_json, name): + """The attribute rows of the class node ``cls-``.""" + node, = [n for n in class_json["nodes"] if n["id"] == f"cls-{name}"] + return node["data"]["attributes"] + + def _form_of(gui): form, = [e for m in gui.modules for s in m.screens for e in s.view_elements if isinstance(e, Form)] return form @@ -80,8 +87,7 @@ def test_a_labelled_input_naming_an_attribute_still_chooses_the_class(): assert _bound_class(form) is None classes = _classes("Task", "Note") - del classes["elements"]["attr-Note-done"] - classes["elements"]["cls-Note"]["attributes"].remove("attr-Note-done") + _attributes(classes, "Note")[:] = [a for a in _attributes(classes, "Note") if a["name"] != "done"] form = _form_of(import_gui([_form(_label(_input(type="checkbox", name="done"), " Done"))], classes)) assert _bound_class(form) == "Task" @@ -94,12 +100,7 @@ def test_a_labelled_input_naming_nothing_does_not_pick_a_class(): def test_a_labelled_input_naming_another_class_does_not_unbind_the_form(): classes = _classes("Task", "Note") - for attr in ("title", "done"): - del classes["elements"][f"attr-Note-{attr}"] - classes["elements"]["cls-Note"]["attributes"] = [] - pinned = class_diagram("Note", [("pinned", "bool")])["elements"] - classes["elements"].update({k: v for k, v in pinned.items() if k != "cls-Note"}) - classes["elements"]["cls-Note"]["attributes"] = ["attr-Note-pinned"] + _attributes(classes, "Note")[:] = _attributes(class_diagram("Note", [("pinned", "bool")]), "Note") form = _form_of(import_gui([_form(_label(_input(type="checkbox", name="pinned"), " Pinned"))], classes)) # Read without the labelled input, as before such inputs were kept: Task diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_gui_radio_groups.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_gui_radio_groups.py index 064d39ab3..56d4dbffd 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_gui_radio_groups.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_gui_radio_groups.py @@ -25,16 +25,14 @@ def _task_classes(): """Task(title: str, status: Status [0..1], priority: str [0..1]) with Status = Open | Closed.""" class_json = class_diagram("Task", [("title", "str"), ("status", "Status"), ("priority", "str")]) - class_json["elements"]["attr-Task-status"]["isOptional"] = True - class_json["elements"]["attr-Task-priority"]["isOptional"] = True - class_json["elements"].update({ - "enum-Status": {"id": "enum-Status", "name": "Status", "type": "Enumeration", "owner": None, - "bounds": {"x": 400, "y": 0, "width": 200, "height": 100}, - "attributes": ["lit-open", "lit-closed"], "methods": []}, - "lit-open": {"id": "lit-open", "name": "Open", "type": "ClassAttribute", "owner": "enum-Status", - "bounds": {"x": 400, "y": 30, "width": 200, "height": 30}}, - "lit-closed": {"id": "lit-closed", "name": "Closed", "type": "ClassAttribute", "owner": "enum-Status", - "bounds": {"x": 400, "y": 60, "width": 200, "height": 30}}, + for row in class_json["nodes"][0]["data"]["attributes"]: + row["isOptional"] = row["name"] in ("status", "priority") + class_json["nodes"].append({ + "id": "enum-Status", "type": "class", "position": {"x": 400, "y": 0}, "width": 200, "height": 100, + "data": {"name": "Status", "stereotype": "Enumeration", "methods": [], "attributes": [ + {"id": "lit-open", "name": "Open", "visibility": "public", "attributeType": "str"}, + {"id": "lit-closed", "name": "Closed", "visibility": "public", "attributeType": "str"}, + ]}, }) return class_json diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_import_handles_and_layout.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_import_handles_and_layout.py new file mode 100644 index 000000000..aa3dae77b --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_import_handles_and_layout.py @@ -0,0 +1,223 @@ +"""Importing a ``.py`` project must produce a diagram the v4 editor can render. + +Live evidence (React Flow migration): importing a class project dropped every +association because the edges carried ``sourceHandle: "Right"`` / +``targetHandle: "Left"`` while the editor's handles are lowercase +(``right``, ``left``, ``top-right``...), so React Flow could not resolve them. +The same import gave every class a fixed size on a fixed grid, so classes with +many attributes overlapped; a BPMN ``.py`` exported by ``development`` lost its +edge routing (it stores ``bounds`` + ``path`` but no ``points``); and object +attribute rows lacked ``visibility``, which makes the frontend's v3 round-trip +fall back to name parsing and drop ``attributeType``. +""" + +import pytest + +from besser.BUML.metamodel.bpmn import ( + BPMNModel, EndEvent, Process, SequenceFlow, StartEvent, Task, TaskType, +) +from besser.utilities.buml_code_builder.bpmn_model_builder import bpmn_model_to_code +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.bpmn_diagram_converter import ( + bpmn_buml_to_json, bpmn_object_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.class_diagram_converter import ( + class_buml_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.object_diagram_converter import ( + object_buml_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.project_converter import ( + project_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.class_diagram_processor import ( + process_class_diagram, +) + +# ``HandleId`` in packages/library/lib/nodes/wrappers/DefaultNodeWrapper.tsx. +V4_HANDLE_IDS = { + "top-left", "top-mid-left", "top", "top-mid-right", "top-right", + "right-top", "right-mid-top", "right", "right-mid-bottom", "right-bottom", + "bottom-right", "bottom-mid-right", "bottom", "bottom-mid-left", "bottom-left", + "left-bottom", "left-mid-bottom", "left", "left-mid-top", "left-top", +} + +_ATTRS_AUTHOR = ", ".join(f'Property(name="a{i}", type=StringType)' for i in range(9)) +_ATTRS_BOOK = ", ".join(f'Property(name="b{i}", type=IntegerType)' for i in range(12)) + +CLASS_PROJECT_PY = f''' +from besser.BUML.metamodel.structural import * +Author = Class(name="Author") +Book = Class(name="Book") +Library = Class(name="Library") +Publisher = Class(name="Publisher") +Author.attributes = {{{_ATTRS_AUTHOR}}} +Book.attributes = {{{_ATTRS_BOOK}}} +Library.attributes = {{Property(name="name", type=StringType)}} +Publisher.attributes = {{Property(name="name", type=StringType)}} +writes = BinaryAssociation(name="writes", ends={{ + Property(name="authors", type=Author, multiplicity=Multiplicity(1, "*")), + Property(name="books", type=Book, multiplicity=Multiplicity(0, "*"))}}) +holds = BinaryAssociation(name="holds", ends={{ + Property(name="library", type=Library, multiplicity=Multiplicity(1, 1)), + Property(name="stock", type=Book, multiplicity=Multiplicity(0, "*"))}}) +domain_model = DomainModel(name="Lib", types={{Author, Book, Library, Publisher}}, + associations={{writes, holds}}) +''' + + +def _class_diagram(project: dict) -> dict: + diagrams = project["diagrams"]["ClassDiagram"] + diagram = diagrams[0] if isinstance(diagrams, list) else diagrams + return diagram["model"] + + +def _overlaps(nodes): + hits = [] + for i, a in enumerate(nodes): + for b in nodes[i + 1:]: + ax, ay, bx, by = a["position"]["x"], a["position"]["y"], b["position"]["x"], b["position"]["y"] + if ax < bx + b["width"] and bx < ax + a["width"] and ay < by + b["height"] and by < ay + a["height"]: + hits.append((a["data"].get("name"), b["data"].get("name"))) + return hits + + +def _assert_valid_handles(edges): + for edge in edges: + if edge["type"] == "ClassLinkRel": + continue # edge-anchored; canonical "Center"/"Up", never handed to React Flow + assert edge["sourceHandle"] in V4_HANDLE_IDS, edge + assert edge["targetHandle"] in V4_HANDLE_IDS, edge + + +def test_imported_class_project_keeps_associations_renderable(): + model = _class_diagram(project_to_json(CLASS_PROJECT_PY)) + associations = [e for e in model["edges"] if e["type"] == "ClassBidirectional"] + assert len(associations) == 2 + _assert_valid_handles(model["edges"]) + + +def test_imported_classes_are_sized_from_content_and_do_not_overlap(): + model = _class_diagram(project_to_json(CLASS_PROJECT_PY)) + classes = {n["data"]["name"]: n for n in model["nodes"] if n["type"] == "class"} + # Frontend calculateMinHeight: header 40 + 30 per row, snapped up to 10. + assert classes["Book"]["height"] == 40 + 30 * 12 + assert classes["Author"]["height"] == 40 + 30 * 9 + assert classes["Library"]["height"] == 40 + 30 + assert _overlaps(list(model["nodes"])) == [] + + +def test_long_member_names_widen_the_class(): + code = CLASS_PROJECT_PY.replace( + 'Library.attributes = {Property(name="name"', + 'Library.attributes = {Property(name="a_really_long_attribute_name_for_width"', 1, + ) + assert code != CLASS_PROJECT_PY + model = _class_diagram(project_to_json(code)) + library = next(n for n in model["nodes"] if n["data"].get("name") == "Library") + assert library["width"] > 300 + assert _overlaps(list(model["nodes"])) == [] + + +def _class_json_with_handles(source_handle, target_handle): + return { + "title": "Handles", + "model": { + "version": "4.0.0", "type": "ClassDiagram", + "nodes": [ + {"id": "c1", "type": "class", "position": {"x": 10, "y": 20}, "width": 160, "height": 70, + "data": {"name": "A", "attributes": [], "methods": []}}, + {"id": "c2", "type": "class", "position": {"x": 500, "y": 40}, "width": 160, "height": 70, + "data": {"name": "B", "attributes": [], "methods": []}}, + ], + "edges": [ + {"id": "e1", "type": "ClassBidirectional", "source": "c1", "target": "c2", + "sourceHandle": source_handle, "targetHandle": target_handle, + "data": {"name": "ab", "sourceRole": "a", "sourceMultiplicity": "1", + "targetRole": "b", "targetMultiplicity": "*", "points": []}}, + ], + }, + } + + +@pytest.mark.parametrize( + "stored, expected", + [(("Up", "Down"), ("top", "bottom")), # older (development) export + (("Right", "Topleft"), ("right", "top-left")), + (("right-top", "bottom"), ("right-top", "bottom"))], # already v4 +) +def test_saved_handles_are_accepted_and_emitted_as_v4_ids(stored, expected): + domain = process_class_diagram(_class_json_with_handles(*stored)) + out = class_buml_to_json(domain) + edge = next(e for e in out["edges"] if e["type"] == "ClassBidirectional") + assert (edge["sourceHandle"], edge["targetHandle"]) == expected + # Saved positions from the diagram are kept, not re-laid out. + positions = {n["data"]["name"]: n["position"] for n in out["nodes"]} + assert positions == {"A": {"x": 10, "y": 20}, "B": {"x": 500, "y": 40}} + + +@pytest.mark.parametrize( + "v3, v4", + [("Up", "top"), ("Right", "right"), ("Down", "bottom"), ("Left", "left"), + ("Upright", "right-top"), ("Downleft", "left-bottom"), + ("RightTop", "top-right"), ("LeftBottom", "bottom-left"), + ("Bottomleft", "bottom-left"), ("Topright", "top-right"), + ("left-mid-top", "left-mid-top")], +) +def test_normalize_handle_mirrors_frontend_convertV3HandleToV4(v3, v4): + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json._node_builders import ( + normalize_handle, + ) + assert normalize_handle(v3) == v4 + + +def test_object_rows_carry_visibility_and_type_and_objects_do_not_overlap(): + domain_json = class_buml_to_json(process_class_diagram({ + "title": "D", + "model": {"version": "4.0.0", "type": "ClassDiagram", "edges": [], "nodes": [ + {"id": "c1", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Book", "attributes": [ + {"id": f"a{i}", "name": f"f{i}", "attributeType": "int", "visibility": "public"} + for i in range(8)], "methods": []}}, + ]}, + })) + kwargs = ", ".join(f"f{i}={i}" for i in range(8)) + content = "\n".join( + f'b{n} = Book("b{n}").attributes({kwargs}).build()' for n in range(6) + ) + out = object_buml_to_json(content, domain_json) + objects = [n for n in out["nodes"] if n["type"] == "objectName"] + assert len(objects) == 6 + for row in objects[0]["data"]["attributes"]: + assert row["visibility"] == "public" + assert row["attributeType"] == "int" + assert _overlaps(objects) == [] + + +def _development_bpmn_model(): + """A BPMN model as a development-era ``.py`` stores it: flow layout has + ``bounds`` + relative ``path`` and no ``points``.""" + s = StartEvent(name="start") + t = Task(name="work", task_type=TaskType.USER) + e = EndEvent(name="end") + s.layout = {"id": "s1", "owner": None, "bounds": {"x": 0, "y": 0, "width": 40, "height": 40}} + t.layout = {"id": "t1", "owner": None, "bounds": {"x": 200, "y": 100, "width": 160, "height": 60}} + e.layout = {"id": "e1", "owner": None, "bounds": {"x": 500, "y": 0, "width": 40, "height": 40}} + f1 = SequenceFlow(s, t) + f1.layout = { + "id": "f1", "owner": None, + "bounds": {"x": 40, "y": 20, "width": 160, "height": 110}, + "path": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 80, "y": 110}, {"x": 160, "y": 110}], + "source_direction": "Right", "target_direction": "Left", "isManuallyLayouted": True, + } + f2 = SequenceFlow(t, e) + p = Process(name="P", flow_nodes={s, t, e}, sequence_flows={f1, f2}) + return BPMNModel(name="Dev", processes={p}) + + +def test_development_bpmn_flow_path_becomes_v4_points(): + expected = [{"x": 40, "y": 20}, {"x": 120, "y": 20}, {"x": 120, "y": 130}, {"x": 200, "y": 130}] + for out in (bpmn_object_to_json(_development_bpmn_model()), + bpmn_buml_to_json(bpmn_model_to_code(_development_bpmn_model()))): + edges = {e["id"]: e for e in out["edges"]} + assert edges["f1"]["data"]["points"] == expected + _assert_valid_handles(out["edges"]) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_layout_adoption.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_layout_adoption.py new file mode 100644 index 000000000..753eb3ee9 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_layout_adoption.py @@ -0,0 +1,271 @@ +"""adopt_layout: an imported diagram laid out like the diagram it replaces (issue #774). + +The models come from the real converters (B-UML -> v4 JSON), the way +``/get-json-model`` builds them, so the tests see the ids and grid positions an +import actually produces. +""" + +import copy + +from besser.BUML.metamodel.state_machine.agent import Agent, AgentReply +from besser.BUML.metamodel.state_machine.state_machine import Body +from besser.BUML.metamodel.structural import ( + BinaryAssociation, + Class, + DomainModel, + Multiplicity, + PrimitiveDataType, + Property, +) +from besser.utilities.buml_code_builder.agent_model_builder import agent_model_to_code +from besser.utilities.buml_code_builder.state_machine_builder import state_machine_to_code +from besser.utilities.web_modeling_editor.backend.services.converters import ( + agent_buml_to_json, + class_buml_to_json, + process_state_machine, + state_machine_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.layout_adoption import ( + adopt_existing_layout, + adopt_layout, +) + + +def agent_source(tmp_path, refined=False): + """The greeting agent; ``refined`` renames ``good`` and adds a ``farewell`` state.""" + agent = Agent("Greeter") + hello = agent.new_intent("hello_intent", ["hi", "hello"]) + bye = agent.new_intent("bye_intent", ["bye"]) + initial = agent.new_state("initial", initial=True) + greeting = agent.new_state("greeting") + good = agent.new_state("feeling_good" if refined else "good") + greeting.set_body(Body("greeting_body", actions=[AgentReply("Hello!")])) + initial.when_intent_matched(hello).go_to(greeting) + greeting.when_intent_matched(hello).go_to(good) + good.go_to(initial) + if refined: + farewell = agent.new_state("farewell") + greeting.when_intent_matched(bye).go_to(farewell) + path = tmp_path / ("refined.py" if refined else "agent.py") + agent_model_to_code(agent, str(path)) + return path.read_text() + + +def laid_out(model): + """``model`` as a user left it: every node moved off the converter's grid, every edge bent.""" + model = copy.deepcopy(model) + for index, node in enumerate(model["nodes"]): + node["position"] = {"x": 37 + 230 * index, "y": 11 - 170 * index} + for edge in model["edges"]: + edge["data"]["points"] = [{"x": 1, "y": 2}, {"x": 3, "y": 4}] + edge["data"]["isManuallyLayouted"] = True + edge["sourceHandle"], edge["targetHandle"] = "bottom", "top" + return model + + +def by_name(model): + return {node["data"]["name"]: node for node in model["nodes"]} + + +def library_model(extra_class=None, rename_author=None): + string = PrimitiveDataType("str") + book = Class("Book", attributes={Property("title", string), Property("isbn", string)}) + author = Class(rename_author or "Author", attributes={Property("name", string)}) + writes = BinaryAssociation("writes", ends={ + Property("books", book, multiplicity=Multiplicity(0, "*")), + Property("authors", author, multiplicity=Multiplicity(1, "*")), + }) + types = {book, author} + if extra_class: + types.add(Class(extra_class, attributes={Property("code", string)})) + return class_buml_to_json(DomainModel("Library", types=types, associations={writes})) + + +def _ids(model): + return {node["id"] for node in model["nodes"]}, {edge["id"] for edge in model["edges"]} + + +def test_unchanged_agent_keeps_every_position_and_id(tmp_path): + existing = laid_out(agent_buml_to_json(agent_source(tmp_path))) + imported = agent_buml_to_json(agent_source(tmp_path)) + assert _ids(imported)[0].isdisjoint(_ids(existing)[0]) # the import alone gives fresh ids + + model, report = adopt_layout(existing, imported) + + assert model["nodes"] == existing["nodes"] + assert model["edges"] == existing["edges"] + assert set(model["components"]) == set(existing["components"]) + assert report["matched"] == 3 and report["added"] == [] and report["notInImport"] == [] + assert report["edgesKept"] == 3 and report["edgesAdded"] == 0 + + +def test_unchanged_class_diagram_keeps_positions_ids_and_attribute_ids(): + existing = laid_out(library_model()) + imported = library_model() + assert _ids(imported)[0].isdisjoint(_ids(existing)[0]) + row_ids = {row["id"] for node in imported["nodes"] for row in node["data"]["attributes"]} + assert row_ids.isdisjoint({row["id"] for node in existing["nodes"] for row in node["data"]["attributes"]}) + + model, report = adopt_layout(existing, imported) + + assert model["nodes"] == existing["nodes"] # positions, sizes, ids and attribute row ids + assert model["edges"] == existing["edges"] # id, handles and bend points of the association + assert report["matched"] == 2 + + +def test_new_state_is_placed_next_to_its_neighbour_without_overlap(tmp_path): + existing = laid_out(agent_buml_to_json(agent_source(tmp_path))) + model, report = adopt_layout(existing, agent_buml_to_json(agent_source(tmp_path, refined=True))) + + old, new = by_name(existing), by_name(model) + for name in ("initial", "greeting"): + assert new[name]["id"] == old[name]["id"] + assert new[name]["position"] == old[name]["position"] + farewell = new["farewell"] + assert report["added"] == [{"id": farewell["id"], "type": "AgentState", "name": "farewell", + "placedNextTo": "greeting"}] + greeting = new["greeting"]["position"] + assert abs(farewell["position"]["x"] - greeting["x"]) + abs(farewell["position"]["y"] - greeting["y"]) < 600 + + def box(node): + return (node["position"]["x"], node["position"]["y"], + node["position"]["x"] + node["width"], node["position"]["y"] + node["height"]) + + for other in model["nodes"]: + if other is not farewell: + a, b = box(farewell), box(other) + assert a[2] <= b[0] or b[2] <= a[0] or a[3] <= b[1] or b[3] <= a[1], other["data"]["name"] + + +def test_renamed_state_keeps_its_place_when_its_connections_say_so(tmp_path): + existing = laid_out(agent_buml_to_json(agent_source(tmp_path))) + model, report = adopt_layout(existing, agent_buml_to_json(agent_source(tmp_path, refined=True))) + + old_good = by_name(existing)["good"] + renamed = by_name(model)["feeling_good"] + assert (renamed["id"], renamed["position"]) == (old_good["id"], old_good["position"]) + assert report["renamed"] == [{"id": old_good["id"], "type": "AgentState", "from": "good", "to": "feeling_good"}] + assert report["notInImport"] == [] + # The three transitions the file still has keep their id and bend points; the new one is routed afresh. + old_edges = {edge["id"]: edge for edge in existing["edges"]} + kept = [edge for edge in model["edges"] if edge["id"] in old_edges] + assert len(kept) == 3 and all(edge["data"] == old_edges[edge["id"]]["data"] for edge in kept) + assert report["edgesKept"] == 3 and report["edgesAdded"] == 1 + + +def test_unconnected_renamed_class_reads_as_removed_and_added(): + existing = laid_out(library_model(extra_class="Shelf")) + model, report = adopt_layout(existing, library_model(extra_class="Rack")) + + old_shelf = by_name(existing)["Shelf"] + assert by_name(model)["Rack"]["id"] != old_shelf["id"] + assert report["renamed"] == [] + assert [item["name"] for item in report["added"]] == ["Rack"] + assert report["notInImport"] == [{"id": old_shelf["id"], "type": "class", "name": "Shelf"}] + + +def test_removed_state_is_reported_and_its_edges_dropped(tmp_path): + existing = laid_out(agent_buml_to_json(agent_source(tmp_path, refined=True))) + model, report = adopt_layout(existing, agent_buml_to_json(agent_source(tmp_path))) + + old_farewell = by_name(existing)["farewell"] + assert report["notInImport"] == [{"id": old_farewell["id"], "type": "AgentState", "name": "farewell"}] + assert old_farewell["id"] not in {e["source"] for e in model["edges"]} | {e["target"] for e in model["edges"]} + + +def test_same_named_nodes_pair_in_order_and_no_id_is_used_twice(): + existing = laid_out(library_model()) + duplicate = copy.deepcopy(existing["nodes"][0]) + duplicate["id"] = "dup-old" + duplicate["position"] = {"x": 900, "y": 900} + existing["nodes"].append(duplicate) + imported = library_model() + extra = copy.deepcopy(imported["nodes"][0]) + extra["id"] = "dup-new" + imported["nodes"].append(extra) + second = copy.deepcopy(imported["nodes"][0]) + second["id"] = "dup-third" + imported["nodes"].append(second) + + model, _ = adopt_layout(existing, imported) + + ids = [node["id"] for node in model["nodes"]] + assert len(ids) == len(set(ids)) + name = existing["nodes"][0]["data"]["name"] + same_name = [node for node in model["nodes"] if node["data"]["name"] == name] + assert [node["id"] for node in same_name[:2]] == [existing["nodes"][0]["id"], "dup-old"] + assert same_name[1]["position"] == {"x": 900, "y": 900} + + +def test_edge_drops_its_bend_points_when_an_end_grew(): + existing = laid_out(library_model()) + imported = library_model() + book = by_name(imported)["Book"] + book["height"] += 200 + book["measured"]["height"] += 200 + + model, report = adopt_layout(existing, imported) + + old_edge = existing["edges"][0] + edge = model["edges"][0] + assert edge["id"] == old_edge["id"] + assert (edge["sourceHandle"], edge["targetHandle"]) == ("bottom", "top") + assert edge["data"]["points"] == [] and "isManuallyLayouted" not in edge["data"] + assert report["edgesRerouted"] == 1 + assert by_name(model)["Book"]["position"] == by_name(existing)["Book"]["position"] + + +def test_state_machine_round_trip_keeps_positions_and_ids(): + def state(node_id, name, x, y): + return {"id": node_id, "type": "State", "position": {"x": x, "y": y}, "width": 160, "height": 40, + "data": {"name": name, "bodies": [], "fallbackBodies": []}} + + existing = { + "version": "4.0.0", "type": "StateMachineDiagram", "title": "Door", + "nodes": [ + {"id": "i", "type": "StateInitialNode", "position": {"x": -300, "y": 5}, "width": 45, "height": 45, + "data": {"name": ""}}, + state("a", "Closed", -120, 0), state("b", "Open", 260, 140), + ], + "edges": [ + {"id": "t0", "source": "i", "target": "a", "type": "StateTransition", + "sourceHandle": "right", "targetHandle": "left", "data": {"name": "", "points": []}}, + {"id": "t1", "source": "a", "target": "b", "type": "StateTransition", + "sourceHandle": "bottom", "targetHandle": "left", "data": {"name": "push", "points": []}}, + ], + } + imported = state_machine_to_json(state_machine_to_code(process_state_machine({"title": "Door", + "model": existing}))) + + model, report = adopt_layout(existing, imported) + + states = {n["data"]["name"]: n for n in model["nodes"] if n["type"] == "State"} + assert {name: (n["id"], n["position"]) for name, n in states.items()} == { + "Closed": ("a", {"x": -120, "y": 0}), "Open": ("b", {"x": 260, "y": 140}), + } + push = next(e for e in model["edges"] if e["data"].get("name") == "push") + assert (push["id"], push["sourceHandle"]) == ("t1", "bottom") + assert report["notInImport"] == [] + + +def test_unusable_existing_model_leaves_the_import_as_is(tmp_path): + imported = agent_buml_to_json(agent_source(tmp_path)) + for text, reason in [ + ("not json {", "not valid JSON"), + ('{"elements": {}, "relationships": {}}', "not a diagram model with nodes"), + ('{"type": "ClassDiagram", "nodes": []}', "the existing diagram is a ClassDiagram"), + ]: + model, warnings = adopt_existing_layout(text, imported, "AgentDiagram") + assert model is imported + assert [w["code"] for w in warnings] == ["layout-not-adopted"] and reason in warnings[0]["message"] + + _, warnings = adopt_existing_layout('{"nodes": []}', imported, "BPMNDiagram") + assert [w["code"] for w in warnings] == ["layout-not-adopted"] + + +def test_empty_existing_diagram_keeps_the_imported_layout(tmp_path): + imported = agent_buml_to_json(agent_source(tmp_path)) + model, warnings = adopt_existing_layout('{"type": "AgentDiagram", "nodes": [], "edges": []}', + imported, "AgentDiagram") + assert [n["position"] for n in model["nodes"]] == [n["position"] for n in imported["nodes"]] + assert [w["code"] for w in warnings] == ["layout-adopted"] + ["element-added"] * 3 diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_map_converter_roundtrip.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_map_converter_roundtrip.py index 885c963d8..aad2a08a6 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_map_converter_roundtrip.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_map_converter_roundtrip.py @@ -59,10 +59,11 @@ def canton_domain(): def _build_class_model(*classes_and_props): """ - Build a minimal GrapesJS class-model dict from (class, prop...) tuples. + Build a minimal v4 class diagram model (``{nodes}``; attributes are rows on + the class node's ``data.attributes``) from (class, prop...) tuples. Returns the model dict and a mapping of object → UUID. """ - elements: dict = {} + nodes: list = [] id_map: dict = {} counter = [0] @@ -72,14 +73,18 @@ def new_id(prefix: str): for cls, *props in classes_and_props: cls_id = new_id("cls") - elements[cls_id] = {"id": cls_id, "type": "Class", "name": cls.name} + rows = [] id_map[cls] = cls_id for p in props: attr_id = new_id("attr") - elements[attr_id] = {"id": attr_id, "type": "ClassAttribute", "name": p.name} + rows.append({"id": attr_id, "name": p.name, "attributeType": "str", "visibility": "public"}) id_map[p] = attr_id + nodes.append({ + "id": cls_id, "type": "class", "position": {"x": 0, "y": 0}, + "data": {"name": cls.name, "attributes": rows, "methods": []}, + }) - return {"elements": elements}, id_map + return {"version": "4.0.0", "type": "ClassDiagram", "nodes": nodes, "edges": []}, id_map def _collect_attrs(comp: dict, out: list) -> None: diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_multiplicity_label.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_multiplicity_label.py index 63bf79e5e..fb8d714bc 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_multiplicity_label.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_multiplicity_label.py @@ -48,11 +48,11 @@ def test_exact_multiplicity_collapses_in_converter(): model = DomainModel(name="M", types={a, b}, associations={assoc}) result = class_buml_to_json(model) - relationships = result.get("relationships") or (result.get("model") or {}).get("relationships", {}) - rels = list(relationships.values()) - assert len(rels) == 1 + edges = [e for e in result["edges"] if e.get("type") == "ClassBidirectional"] + assert len(edges) == 1 - mults = {rels[0]["source"]["multiplicity"], rels[0]["target"]["multiplicity"]} + data = edges[0]["data"] + mults = {data["sourceMultiplicity"], data["targetMultiplicity"]} assert "1" in mults # 1..1 collapsed (issue #3) assert "1..1" not in mults assert "1..*" in mults # unbounded range untouched diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_nn_buml_to_json_safety.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_nn_buml_to_json_safety.py index 988671887..782443a7d 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_nn_buml_to_json_safety.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_nn_buml_to_json_safety.py @@ -37,11 +37,11 @@ def test_legitimate_nn_buml_parses(): out = nn_buml_to_json(LEGITIMATE_BUML) assert out['type'] == 'NNDiagram' - # Each layer plus the main container emits one element; count >=4 - layer_types = {el['type'] for el in out['elements'].values()} - assert 'Conv2DLayer' in layer_types - assert 'LinearLayer' in layer_types - assert 'FlattenLayer' in layer_types + # Each layer plus the main container emits one node in v4. + node_types = {n['type'] for n in out['nodes']} + assert 'Conv2DLayer' in node_types + assert 'LinearLayer' in node_types + assert 'FlattenLayer' in node_types def test_import_system_call_rejected(): @@ -172,7 +172,7 @@ def test_transitively_referenced_sub_nn_not_counted_as_top_level(): out = nn_buml_to_json(buml) assert out['type'] == 'NNDiagram' # Three containers emitted (root + 2 sub-NNs) - containers = [e for e in out['elements'].values() if e.get('type') == 'NNContainer'] + containers = [n for n in out['nodes'] if n.get('type') == 'NNContainer'] assert len(containers) == 3 @@ -205,8 +205,18 @@ def test_builder_output_roundtrips_through_ast_parser(tmp_path): out = nn_buml_to_json(code) assert out["type"] == "NNDiagram" - element_types = {el["type"] for el in out["elements"].values()} - assert "Conv2DLayer" in element_types - assert "LinearLayer" in element_types - assert "FlattenLayer" in element_types - assert "Configuration" in element_types + node_types = {n["type"] for n in out["nodes"]} + assert "Conv2DLayer" in node_types + assert "LinearLayer" in node_types + assert "FlattenLayer" in node_types + assert "Configuration" in node_types + + +@pytest.mark.parametrize("call, hint", [ + ("LinearLayer(*a)", "pass arguments explicitly"), + ("LinearLayer(**a)", "pass keyword arguments explicitly"), +]) +def test_unpacking_in_a_constructor_says_how_to_fix_it(call, hint): + source = f"from besser.BUML.metamodel.nn import NN, LinearLayer\na = []\nlayer_0 = {call}\n" + with pytest.raises(ValueError, match=hint): + nn_buml_to_json(source) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_ocl_pre_post.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_ocl_pre_post.py index 86636c361..1fc1ebd86 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_ocl_pre_post.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_ocl_pre_post.py @@ -2,11 +2,27 @@ Tests for OCL invariant / precondition / postcondition handling in the WME class diagram converter pipeline. -The canonical wire shape is full OCL text in each ``ClassOCLConstraint`` -element's ``constraint`` field — e.g. +On ingest the processor accepts two shapes: rows inlined in a class +node's ``data.oclConstraints`` array (the v3->v4 migrator's +collapse-onto-owner output) — e.g. + + { + "id": "n-account", + "type": "class", + "data": { + "name": "Account", + "oclConstraints": [ + {"id": "ocl-inv", "name": "positive", + "expression": "context Account inv positive: self.balance >= 0"}, + ... + ] + } + } - context Book inv pages_positive: self.pages > 0 - context Book::decrease_stock(qty: int) pre: qty > 0 +— and free-standing ``ClassOCLConstraint`` nodes (the sticky-note shape +the frontend authors), tethered to their class by a ``ClassOCLLink`` +edge. On emit the converter always produces the free-standing node +shape (develop parity: constraints stay visible, editable boxes). Tests cover: * ``parse_constraint_text`` returning the right routing kind plus the @@ -15,8 +31,8 @@ ``domain_model.constraints`` (invariants) or to ``Method.pre`` / ``Method.post`` lists (pre/post) via Class::method name lookup. * Skip-with-warning behaviour on malformed OCL or unresolved methods. - * Back-compat ingest for body-only JSON files produced by an earlier - intermediate iteration (kind / targetMethodId / constraintName). + * Back-compat ingest for body-only constraint rows (kind / + targetMethodId / constraintName) still produced by older clients. * Round-trip stability of the canonical full-text shape. """ @@ -39,6 +55,55 @@ ) +# --------------------------------------------------------------------------- +# v4 helpers (local — keep this module self-contained) +# --------------------------------------------------------------------------- + +def _class_node_by_name(model_payload, class_name): + """Return the v4 class node matching ``class_name``.""" + for n in model_payload.get("nodes") or []: + if n.get("type") == "class" and (n.get("data") or {}).get("name") == class_name: + return n + return None + + +def _all_ocl_rows(payload): + """Return every OCL constraint in ``payload`` as (anchor-class, row) pairs. + + Covers both wire shapes: rows inlined on a class node's + ``data.oclConstraints`` (anchor = the owning class) and free-standing + ``ClassOCLConstraint`` nodes (anchor = the class reached via the + ``ClassOCLLink`` edge, ``None`` when unlinked). + """ + model = payload.get("model") if "model" in payload else payload + nodes = model.get("nodes") or [] + nodes_by_id = {n.get("id"): n for n in nodes} + + def _linked_class_name(constraint_node_id): + for e in model.get("edges") or []: + if e.get("type") != "ClassOCLLink": + continue + if e.get("source") == constraint_node_id: + other = nodes_by_id.get(e.get("target")) + elif e.get("target") == constraint_node_id: + other = nodes_by_id.get(e.get("source")) + else: + continue + if other is not None and other.get("type") == "class": + return (other.get("data") or {}).get("name") + return None + + out = [] + for n in nodes: + data = n.get("data") or {} + if n.get("type") == "class": + for row in data.get("oclConstraints") or []: + out.append((data.get("name"), row)) + elif n.get("type") == "ClassOCLConstraint": + out.append((_linked_class_name(n.get("id")), data)) + return out + + # --------------------------------------------------------------------------- # Fixtures # --------------------------------------------------------------------------- @@ -61,58 +126,61 @@ def banking_model(): @pytest.fixture def account_diagram_json(): - """A class-diagram JSON whose OCL boxes carry full-text constraints.""" + """A v4 class diagram whose Account node carries inlined OCL rows. + + Three constraint rows: an invariant, a precondition and a postcondition, + all anchored on the same ``Account`` class node. + """ return { "id": "banking-diagram", "title": "BankingTest", "model": { - "elements": { - "cls-Account": { - "id": "cls-Account", "name": "Account", "type": "Class", - "attributes": ["attr-balance", "attr-active"], - "methods": ["m-deposit"], - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - }, - "attr-balance": { - "id": "attr-balance", "name": "balance", - "visibility": "public", "attributeType": "int", + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-account", + "type": "class", + "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Account", + "stereotype": None, + "attributes": [ + {"id": "a-balance", "name": "balance", + "attributeType": "int", "visibility": "public"}, + {"id": "a-active", "name": "is_active", + "attributeType": "bool", "visibility": "public"}, + ], + "methods": [ + {"id": "m-deposit", "name": "+ deposit(amount: int): int"}, + ], + "oclConstraints": [ + {"id": "ocl-inv", "name": "positive", + "expression": "context Account inv positive: self.balance >= 0"}, + {"id": "ocl-pre", "name": "amt_pos", + "expression": "context Account::deposit(amount: int) pre: amount > 0"}, + {"id": "ocl-post", "name": "balance_nn", + "expression": "context Account::deposit(amount: int) post: self.balance >= 0"}, + ], + }, }, - "attr-active": { - "id": "attr-active", "name": "is_active", - "visibility": "public", "attributeType": "bool", - }, - "m-deposit": { - "id": "m-deposit", "name": "+ deposit(amount: int): int", - "type": "ClassMethod", "owner": "cls-Account", - }, - "ocl-inv": { - "id": "ocl-inv", "type": "ClassOCLConstraint", - "constraint": "context Account inv positive: self.balance >= 0", - }, - "ocl-pre": { - "id": "ocl-pre", "type": "ClassOCLConstraint", - "constraint": "context Account::deposit(amount: int) pre: amount > 0", - }, - "ocl-post": { - "id": "ocl-post", "type": "ClassOCLConstraint", - "constraint": "context Account::deposit(amount: int) post: self.balance >= 0", - }, - }, - "relationships": { - "r-inv": {"id": "r-inv", "type": "ClassOCLLink", - "source": {"element": "ocl-inv"}, - "target": {"element": "cls-Account"}}, - "r-pre": {"id": "r-pre", "type": "ClassOCLLink", - "source": {"element": "ocl-pre"}, - "target": {"element": "cls-Account"}}, - "r-post": {"id": "r-post", "type": "ClassOCLLink", - "source": {"element": "ocl-post"}, - "target": {"element": "cls-Account"}}, - }, + ], + "edges": [], }, } +def _ocl_row_by_id(diagram_json, ocl_id): + """Return the inlined OCL row with the given id (for in-place mutation).""" + for n in diagram_json["model"]["nodes"]: + for row in (n.get("data") or {}).get("oclConstraints") or []: + if row.get("id") == ocl_id: + return row + raise KeyError(ocl_id) + + # --------------------------------------------------------------------------- # parse_constraint_text — header inspection + AST attachment # --------------------------------------------------------------------------- @@ -124,10 +192,7 @@ def test_parse_constraint_text_invariant_extracts_name(banking_model): ) assert kind == "invariant" assert isinstance(c, OCLConstraint) - assert c.name == "positive" # user-typed name preserved - # ``expression`` carries the full canonical OCL text (set by - # ``parse_constraint_text``) so downstream consumers — validator, - # BUML emitter, BOCL evaluator — don't need to reconstruct it. + assert c.name == "positive" assert c.expression == "context Account inv positive: self.balance >= 0" assert c.context is account assert class_name == "Account" @@ -184,7 +249,6 @@ def test_invariant_routed_to_domain_model_constraints(account_diagram_json): assert invariants == ["positive"] inv = next(iter(dm.constraints)) assert isinstance(inv, OCLConstraint) - # ``expression`` carries the full canonical text post-consolidation. assert inv.expression == "context Account inv positive: self.balance >= 0" @@ -210,8 +274,9 @@ def test_postcondition_routed_to_method_post(account_diagram_json): def test_unknown_method_in_pre_skipped_with_warning(account_diagram_json): """Pre/post pointing at a method the class doesn't have → warning + skip.""" - elems = account_diagram_json["model"]["elements"] - elems["ocl-pre"]["constraint"] = "context Account::missing(amount: int) pre: amount > 0" + _ocl_row_by_id(account_diagram_json, "ocl-pre")["expression"] = ( + "context Account::missing(amount: int) pre: amount > 0" + ) dm = process_class_diagram(account_diagram_json) account = next(c for c in dm.types if c.name == "Account") deposit = next(m for m in account.methods if m.name == "deposit") @@ -220,14 +285,15 @@ def test_unknown_method_in_pre_skipped_with_warning(account_diagram_json): issue, = dm.conversion_issues assert issue["code"] == "unknown_method" assert (issue["context"], issue["method"], issue["kind"]) == ("Account", "missing", "precondition") - assert issue["expression"] == elems["ocl-pre"]["constraint"] + assert issue["expression"] == _ocl_row_by_id(account_diagram_json, "ocl-pre")["expression"] assert issue["source"]["element_id"] == "ocl-pre" def test_invalid_ocl_skipped_with_warning(account_diagram_json): """Malformed OCL must not abort the conversion — other constraints must still load.""" - elems = account_diagram_json["model"]["elements"] - elems["ocl-inv"]["constraint"] = "context Account inv broken: self." + _ocl_row_by_id(account_diagram_json, "ocl-inv")["expression"] = ( + "context Account inv broken: self." + ) dm = process_class_diagram(account_diagram_json) # Invariant got dropped; pre/post still parse. assert all(c.name != "positive" for c in dm.constraints) @@ -240,7 +306,9 @@ def test_invalid_ocl_skipped_with_warning(account_diagram_json): issue, = dm.conversion_issues assert issue["code"] == "parse_error" assert issue["name"] == "broken" - assert issue["expression"] == issue["original_text"] == elems["ocl-inv"]["constraint"] + assert issue["expression"] == issue["original_text"] == ( + _ocl_row_by_id(account_diagram_json, "ocl-inv")["expression"] + ) assert issue["source"] == { "diagram_id": "banking-diagram", "diagram_title": "BankingTest", "element_id": "ocl-inv", "block_index": 1, @@ -249,19 +317,21 @@ def test_invalid_ocl_skipped_with_warning(account_diagram_json): def test_multi_block_textarea_parses_each_block_independently(banking_model, account_diagram_json): - """A single OCL box may hold multiple constraints separated by `context` boundaries.""" - elems = account_diagram_json["model"]["elements"] - # Drop the per-kind boxes; replace with one box that holds everything. - for k in ("ocl-pre", "ocl-post"): - del elems[k] - rels = account_diagram_json["model"]["relationships"] - for k in ("r-pre", "r-post"): - del rels[k] - elems["ocl-inv"]["constraint"] = ( - "context Account inv positive: self.balance >= 0\n" - "context Account inv active: self.is_active\n" - "context Account inv missingRole: self.guests->size() > 0" - ) + """A single OCL row may hold multiple constraints separated by `context` boundaries.""" + # Replace the three constraint rows with a single invariant box that + # holds two ``context`` blocks back-to-back. + account_node = _class_node_by_name(account_diagram_json["model"], "Account") + account_node["data"]["oclConstraints"] = [ + { + "id": "ocl-multi", + "name": "multi", + "expression": ( + "context Account inv positive: self.balance >= 0\n" + "context Account inv active: self.is_active\n" + "context Account inv missingRole: self.guests->size() > 0" + ), + }, + ] dm = process_class_diagram(account_diagram_json) invariants = sorted(c.name for c in dm.constraints) @@ -270,49 +340,52 @@ def test_multi_block_textarea_parses_each_block_independently(banking_model, acc assert issue["source"]["block_index"] == 3 assert issue["name"] == "missingRole" assert issue["expression"] == "context Account inv missingRole: self.guests->size() > 0" - assert issue["original_text"] == elems["ocl-inv"]["constraint"] + assert issue["original_text"] == _ocl_row_by_id(account_diagram_json, "ocl-multi")["expression"] assert "guests" in issue["reason"] # --------------------------------------------------------------------------- -# Back-compat shim — body-only legacy JSON files +# Back-compat shim — body-only legacy rows # --------------------------------------------------------------------------- def test_body_only_legacy_files_still_load(): - """Body-only ``ClassOCLConstraint`` boxes (kind + constraintName + targetMethodId) + """Body-only inlined OCL rows (kind + constraintName + targetMethodId) are lifted to full text by the back-compat shim before parsing. """ legacy = { "title": "Legacy", "model": { - "elements": { - "cls-Account": {"id": "cls-Account", "name": "Account", "type": "Class", - "attributes": ["a-balance"], "methods": ["m-deposit"]}, - "a-balance": {"id": "a-balance", "name": "balance", - "visibility": "public", "attributeType": "int"}, - "m-deposit": {"id": "m-deposit", "name": "+ deposit(amount: int): int", - "type": "ClassMethod", "owner": "cls-Account"}, - "ocl-inv": { - "id": "ocl-inv", "type": "ClassOCLConstraint", - "constraint": "self.balance >= 0", - "kind": "invariant", "constraintName": "positive", + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-account", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Account", "stereotype": None, + "attributes": [ + {"id": "a-balance", "name": "balance", + "attributeType": "int", "visibility": "public"}, + ], + "methods": [ + {"id": "m-deposit", "name": "+ deposit(amount: int): int"}, + ], + "oclConstraints": [ + {"id": "ocl-inv", + "expression": "self.balance >= 0", + "kind": "invariant", + "constraintName": "positive"}, + {"id": "ocl-pre", + "expression": "amount > 0", + "kind": "precondition", + "targetMethodId": "m-deposit", + "constraintName": "amt_pos"}, + ], + }, }, - "ocl-pre": { - "id": "ocl-pre", "type": "ClassOCLConstraint", - "constraint": "amount > 0", - "kind": "precondition", - "targetMethodId": "m-deposit", - "constraintName": "amt_pos", - }, - }, - "relationships": { - "r-inv": {"id": "r-inv", "type": "ClassOCLLink", - "source": {"element": "ocl-inv"}, - "target": {"element": "cls-Account"}}, - "r-pre": {"id": "r-pre", "type": "ClassOCLLink", - "source": {"element": "ocl-pre"}, - "target": {"element": "cls-Account"}}, - }, + ], + "edges": [], }, } dm = process_class_diagram(legacy) @@ -329,29 +402,102 @@ def test_body_only_legacy_files_still_load(): assert dm.conversion_issues == [] +@pytest.mark.parametrize("link_from_class", [False, True]) +def test_body_only_free_standing_nodes_use_migrated_metadata(link_from_class): + """The v3->v4 migrator keeps a body-only constraint's v3 metadata on the + free-standing ``ClassOCLConstraint`` node's ``data`` (``constraintName``, + and ``targetMethodId`` for pre/post). The processor must use it: the + invariant keeps its name and pre/post conditions attach to the method the + id names. The ``ClassOCLLink`` edge supplies the owner class in either + direction. + """ + def ocl_node(node_id, body, kind, name, target=None): + data = {"expression": body, "kind": kind, "constraintName": name} + if target: + data["targetMethodId"] = target + return {"id": node_id, "type": "ClassOCLConstraint", + "position": {"x": 0, "y": 0}, "width": 200, "height": 80, "data": data} + + def link(ocl_id): + ends = ("n-account", ocl_id) if link_from_class else (ocl_id, "n-account") + return {"id": f"l-{ocl_id}", "type": "ClassOCLLink", "source": ends[0], "target": ends[1], "data": {}} + + diagram = { + "title": "Migrated", + "model": { + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-account", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": { + "name": "Account", "stereotype": None, + "attributes": [ + {"id": "a-balance", "name": "balance", + "attributeType": "int", "visibility": "public"}, + ], + "methods": [ + {"id": "m-deposit", "name": "deposit", "visibility": "public", + "parameters": [{"id": "p1", "name": "amount", "parameterType": "int"}], + "returnType": "any", "attributeType": "any"}, + {"id": "m-close", "name": "close", "visibility": "public", + "returnType": "any", "attributeType": "any"}, + ], + }, + }, + ocl_node("o-inv", "self.balance >= 0", "invariant", "non_negative"), + ocl_node("o-pre", "amount > 0", "precondition", "positive_amount", "m-deposit"), + ocl_node("o-post", "self.balance = 0", "postcondition", "emptied", "m-close"), + ], + "edges": [link("o-inv"), link("o-pre"), link("o-post")], + }, + } + dm = process_class_diagram(diagram) + + assert [c.name for c in dm.constraints] == ["non_negative"] + account = next(c for c in dm.types if c.name == "Account") + methods = {m.name: m for m in account.methods} + assert [c.expression for c in methods["deposit"].pre] == [ + "context Account::deposit(amount: int) pre: amount > 0" + ] + assert methods["deposit"].post == [] + assert [c.expression for c in methods["close"].post] == [ + "context Account::close() post: self.balance = 0" + ] + assert methods["close"].pre == [] + assert dm.conversion_issues == [] + + def test_body_only_legacy_orphan_method_skipped_with_warning(): """Body-only pre/post with a missing targetMethodId is dropped with a warning.""" legacy = { "title": "Legacy", "model": { - "elements": { - "cls-Account": {"id": "cls-Account", "name": "Account", "type": "Class", - "attributes": [], "methods": ["m-deposit"]}, - "m-deposit": {"id": "m-deposit", "name": "+ deposit(amount: int): int", - "type": "ClassMethod", "owner": "cls-Account"}, - "ocl-pre": { - "id": "ocl-pre", "type": "ClassOCLConstraint", - "constraint": "amount > 0", - "kind": "precondition", - "targetMethodId": "missing", # not a real method element - "constraintName": "amt_pos", + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-account", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Account", "stereotype": None, + "attributes": [], + "methods": [ + {"id": "m-deposit", "name": "+ deposit(amount: int): int"}, + ], + "oclConstraints": [ + {"id": "ocl-pre", + "expression": "amount > 0", + "kind": "precondition", + "targetMethodId": "missing", # not a real method + "constraintName": "amt_pos"}, + ], + }, }, - }, - "relationships": { - "r-pre": {"id": "r-pre", "type": "ClassOCLLink", - "source": {"element": "ocl-pre"}, - "target": {"element": "cls-Account"}}, - }, + ], + "edges": [], }, } dm = process_class_diagram(legacy) @@ -368,11 +514,21 @@ def test_body_only_legacy_orphan_method_skipped_with_warning(): @pytest.mark.parametrize("kind,code", [("invariant", "detached"), (None, "unsupported_shape")]) def test_unusable_body_only_rule_is_preserved_not_executed(account_diagram_json, kind, code): - element = account_diagram_json["model"]["elements"]["ocl-inv"] - element["constraint"] = "self.balance >= 0" + """A body-only rule with no owner (a free-standing ``ClassOCLConstraint`` + node with no ``ClassOCLLink``) or no kind is kept as a conversion issue.""" + model = account_diagram_json["model"] + account = _class_node_by_name(model, "Account") + account["data"]["oclConstraints"] = [ + row for row in account["data"]["oclConstraints"] if row["id"] != "ocl-inv" + ] + data = {"expression": "self.balance >= 0"} if kind: - element["kind"] = kind - del account_diagram_json["model"]["relationships"]["r-inv"] + data["kind"] = kind + model["nodes"].append({ + "id": "ocl-inv", "type": "ClassOCLConstraint", + "position": {"x": 0, "y": 200}, "width": 210, "height": 90, + "data": data, + }) dm = process_class_diagram(account_diagram_json) assert not dm.constraints issue, = dm.conversion_issues @@ -385,68 +541,59 @@ def test_unusable_body_only_rule_is_preserved_not_executed(account_diagram_json, # Round-trip stability — full-text canonical # --------------------------------------------------------------------------- -def _summarize_ocl(json_out): - elements = json_out.get("elements") or json_out["model"]["elements"] - boxes = sorted( - (e for e in elements.values() if e.get("type") == "ClassOCLConstraint"), - key=lambda e: e.get("constraint", ""), +def _summarize_ocl(payload): + """Sorted (expression, description) pairs for every OCL row in the payload.""" + rows = _all_ocl_rows(payload) + return sorted( + (row.get("expression"), row.get("description")) + for _cls, row in rows ) - return [(e.get("constraint"), e.get("description")) for e in boxes] - -def _summarize_links(json_out): - """Aggregate ClassOCLLink wiring (which class each box anchors to). - Element/relationship ids are minted fresh on every emit, so we can't - compare them directly; instead we resolve each link to the *names* of - its endpoints' types (constraint text + class name) which are stable. - """ - elements = json_out.get("elements") or json_out["model"]["elements"] - relationships = json_out.get("relationships") or json_out["model"]["relationships"] - pairs = [] - for rel in relationships.values(): - if rel.get("type") != "ClassOCLLink": - continue - src = elements.get(rel["source"]["element"], {}) - tgt = elements.get(rel["target"]["element"], {}) - # The OCL box can be on either end; normalize. - if src.get("type") == "ClassOCLConstraint": - pairs.append((src.get("constraint", ""), tgt.get("name", ""))) - else: - pairs.append((tgt.get("constraint", ""), src.get("name", ""))) - return sorted(pairs) +def _summarize_anchors(payload): + """Sorted (expression, anchoring-class-name) pairs for every OCL row.""" + rows = _all_ocl_rows(payload) + return sorted( + (row.get("expression"), cls_name) + for cls_name, row in rows + ) def test_round_trip_full_mix_is_byte_stable(account_diagram_json): - """JSON -> BUML -> JSON -> BUML -> JSON: OCL boxes + their wiring survive.""" + """JSON -> BUML -> JSON -> BUML -> JSON: OCL rows + their anchoring survive.""" dm1 = process_class_diagram(account_diagram_json) out1 = class_buml_to_json(dm1) dm2 = process_class_diagram({"title": "BankingTest", "model": out1}) out2 = class_buml_to_json(dm2) - # Constraint text + description per box is stable (catches name-churn - # on auto-generated invariant names and box-splitting on description). + # All three constraints (inv + pre + post) survive as visible, + # Account-anchored ``ClassOCLConstraint`` nodes. + assert len(_all_ocl_rows(out1)) == 3 + assert _summarize_anchors(out1) == [ + ("context Account inv positive: self.balance >= 0", "Account"), + ("context Account::deposit(amount: int) post: self.balance >= 0", "Account"), + ("context Account::deposit(amount: int) pre: amount > 0", "Account"), + ] + # Constraint text + description per row is stable. assert _summarize_ocl(out1) == _summarize_ocl(out2) - # Box → class anchoring is stable (catches a missing pre/post emit - # path that would silently drop the link on the second cycle). - assert _summarize_links(out1) == _summarize_links(out2) - # Same number of OCL elements and links on both cycles. - assert sum(1 for e in out1["elements"].values() if e.get("type") == "ClassOCLConstraint") \ - == sum(1 for e in out2["elements"].values() if e.get("type") == "ClassOCLConstraint") + # Row -> class anchoring is stable. + assert _summarize_anchors(out1) == _summarize_anchors(out2) + # Same number of OCL rows on both cycles. + assert len(_all_ocl_rows(out1)) == len(_all_ocl_rows(out2)) def test_emitted_ocl_boxes_carry_no_legacy_metadata(account_diagram_json): """The new shape strips kind / targetMethodId / constraintName on emit.""" dm = process_class_diagram(account_diagram_json) out = class_buml_to_json(dm) - for e in out["elements"].values(): - if e.get("type") != "ClassOCLConstraint": - continue - assert "kind" not in e - assert "targetMethodId" not in e - assert "constraintName" not in e - assert e["constraint"].lstrip().lower().startswith("context") + rows = _all_ocl_rows(out) + assert rows, "expected emitted OCL constraint nodes" + for _cls, row in rows: + assert "kind" not in row + assert "targetMethodId" not in row + assert "constraintName" not in row + assert (row.get("expression") or "").lstrip().lower().startswith("context") def test_legacy_body_only_normalized_to_full_text_on_emit(): @@ -454,74 +601,79 @@ def test_legacy_body_only_normalized_to_full_text_on_emit(): legacy = { "title": "Legacy", "model": { - "elements": { - "cls-Account": {"id": "cls-Account", "name": "Account", "type": "Class", - "attributes": ["a-balance"], "methods": []}, - "a-balance": {"id": "a-balance", "name": "balance", - "visibility": "public", "attributeType": "int"}, - "ocl-inv": { - "id": "ocl-inv", "type": "ClassOCLConstraint", - "constraint": "self.balance >= 0", - "kind": "invariant", "constraintName": "positive", + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-account", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Account", "stereotype": None, + "attributes": [ + {"id": "a-balance", "name": "balance", + "attributeType": "int", "visibility": "public"}, + ], + "methods": [], + "oclConstraints": [ + {"id": "ocl-inv", + "expression": "self.balance >= 0", + "kind": "invariant", + "constraintName": "positive"}, + ], + }, }, - }, - "relationships": { - "r-inv": {"id": "r-inv", "type": "ClassOCLLink", - "source": {"element": "ocl-inv"}, - "target": {"element": "cls-Account"}}, - }, + ], + "edges": [], }, } dm = process_class_diagram(legacy) out = class_buml_to_json(dm) - ocl = next(e for e in out["elements"].values() if e.get("type") == "ClassOCLConstraint") - assert ocl["constraint"] == "context Account inv positive: self.balance >= 0" + rows = _all_ocl_rows(out) + assert len(rows) == 1 + assert rows[0][1]["expression"] == "context Account inv positive: self.balance >= 0" # --------------------------------------------------------------------------- -# Duplicate constraint names across boxes +# Duplicate constraint names across rows # --------------------------------------------------------------------------- def test_duplicate_constraint_name_across_boxes_does_not_crash(): - """Two ``ClassOCLConstraint`` boxes that parse to the same constraint - name must not crash the conversion. + """Two ``oclConstraints`` rows that parse to the same constraint name + must not crash the conversion. ``DomainModel.constraints`` rejects duplicate names with a ``ValueError``; ``_process_constraints`` de-dups by name before assigning, keeping the first occurrence and emitting a warning for each subsequent collision rather than letting the setter raise. - - Discovered by the 2000-constraint stress test (PR #529 review). """ diagram = { "title": "DupNames", "model": { - "elements": { - "cls-Account": { - "id": "cls-Account", "name": "Account", "type": "Class", - "attributes": ["a-balance"], "methods": [], - }, - "a-balance": { - "id": "a-balance", "name": "balance", - "visibility": "public", "attributeType": "int", - }, - "ocl-1": { - "id": "ocl-1", "type": "ClassOCLConstraint", - "constraint": "context Account inv dup: self.balance > 0", - }, - "ocl-2": { - "id": "ocl-2", "type": "ClassOCLConstraint", - "constraint": "context Account inv dup: self.balance >= 0", + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "n-account", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Account", "stereotype": None, + "attributes": [ + {"id": "a-balance", "name": "balance", + "attributeType": "int", "visibility": "public"}, + ], + "methods": [], + "oclConstraints": [ + {"id": "ocl-1", "name": "dup", + "expression": "context Account inv dup: self.balance > 0"}, + {"id": "ocl-2", "name": "dup", + "expression": "context Account inv dup: self.balance >= 0"}, + ], + }, }, - }, - "relationships": { - "r1": {"id": "r1", "type": "ClassOCLLink", - "source": {"element": "ocl-1"}, - "target": {"element": "cls-Account"}}, - "r2": {"id": "r2", "type": "ClassOCLLink", - "source": {"element": "ocl-2"}, - "target": {"element": "cls-Account"}}, - }, + ], + "edges": [], }, } dm = process_class_diagram(diagram) # must not raise diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_ocl_property_suggestion.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_ocl_property_suggestion.py index b39702398..ea51eda59 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_ocl_property_suggestion.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_ocl_property_suggestion.py @@ -109,36 +109,46 @@ def test_no_suggestion_for_unrelated_error_text(): # End-to-end: process_class_diagram -> conversion_issues["reason"] # --------------------------------------------------------------------------- +def _hotel_class(node_id, name, x): + return {"id": node_id, "type": "class", + "position": {"x": x, "y": 0}, "width": 160, "height": 100, + "data": {"name": name, "stereotype": None, "attributes": [], "methods": []}} + + def _hotel_diagram_json(booking_inv: str, room_inv: str): + """v4 hotel diagram: free-standing ``ClassOCLConstraint`` nodes carry the + invariants' full text (the context comes from the text itself).""" return { "id": "hotel-diagram", "title": "HotelTest", "model": { - "elements": { - "cls-Booking": {"id": "cls-Booking", "name": "Booking", "type": "Class"}, - "cls-Guest": {"id": "cls-Guest", "name": "Guest", "type": "Class"}, - "cls-Room": {"id": "cls-Room", "name": "Room", "type": "Class"}, - "ocl-guests": { - "id": "ocl-guests", "type": "ClassOCLConstraint", - "constraint": booking_inv, - }, - "ocl-bookings": { - "id": "ocl-bookings", "type": "ClassOCLConstraint", - "constraint": room_inv, - }, - }, - "relationships": { - "rel-guests": { - "id": "rel-guests", "type": "ClassBidirectional", "name": "guests", - "source": {"element": "cls-Guest", "role": "", "multiplicity": "1..*"}, - "target": {"element": "cls-Booking", "role": "guests", "multiplicity": "0..*"}, - }, - "rel-rooms": { - "id": "rel-rooms", "type": "ClassBidirectional", "name": "rooms", - "source": {"element": "cls-Booking", "role": "", "multiplicity": "0..*"}, - "target": {"element": "cls-Room", "role": "rooms", "multiplicity": "1..*"}, - }, - }, + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + _hotel_class("cls-Booking", "Booking", 0), + _hotel_class("cls-Guest", "Guest", 300), + _hotel_class("cls-Room", "Room", 600), + {"id": "ocl-guests", "type": "ClassOCLConstraint", + "position": {"x": 0, "y": 200}, "width": 210, "height": 90, + "data": {"expression": booking_inv}}, + {"id": "ocl-bookings", "type": "ClassOCLConstraint", + "position": {"x": 300, "y": 200}, "width": 210, "height": 90, + "data": {"expression": room_inv}}, + ], + "edges": [ + {"id": "rel-guests", "type": "ClassBidirectional", + "source": "cls-Guest", "target": "cls-Booking", + "data": {"name": "guests", + "sourceRole": "", "sourceMultiplicity": "1..*", + "targetRole": "guests", "targetMultiplicity": "0..*", + "points": []}}, + {"id": "rel-rooms", "type": "ClassBidirectional", + "source": "cls-Booking", "target": "cls-Room", + "data": {"name": "rooms", + "sourceRole": "", "sourceMultiplicity": "0..*", + "targetRole": "rooms", "targetMultiplicity": "1..*", + "points": []}}, + ], }, } diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_placeholder_class_diagram.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_placeholder_class_diagram.py index c1cb26f33..fd8ce68bd 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_placeholder_class_diagram.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_placeholder_class_diagram.py @@ -12,7 +12,7 @@ class_buml_to_json, process_class_diagram, ) from tests.utilities.web_modeling_editor.backend.services.converters.placeholder_diagram import ( - _bounds, placeholder_diagram, + class_node, edge, placeholder_diagram, ) @@ -54,17 +54,17 @@ def test_the_diagram_round_trips_with_its_placeholders(diagram): result = class_buml_to_json(model) - elements = result["elements"] - names = sorted(e["name"] for e in elements.values() if e["type"] in ("Class", "AbstractClass", "Enumeration")) + nodes = {node["id"]: node for node in result["nodes"]} + names = sorted(node["data"]["name"] for node in nodes.values() if node["type"] == "class") assert names == ["...", "...", "Animal", "Dog", "Kind"] - # Each "..." class comes back as its own element, where the diagram had it. - assert {(i, elements[i]["bounds"]["x"]) for i in ("hidden-1", "hidden-2")} == {("hidden-1", 400), ("hidden-2", 600)} - kind = elements["kind"] - assert sorted(elements[i]["name"] for i in kind["attributes"]) == ["...", "GREEN", "RED"] - relationships = result["relationships"] - assert {(r["source"]["element"], r["target"]["element"]) for r in relationships.values() - if r["type"] == "ClassInheritance"} == {("dog", "animal"), ("hidden-1", "dog"), ("hidden-2", "animal")} - assert {r["type"] for r in relationships.values()} == {"ClassInheritance", "ClassBidirectional"} + # Each "..." class comes back as its own node, where the diagram had it. + assert {(i, nodes[i]["position"]["x"]) for i in ("hidden-1", "hidden-2")} == {("hidden-1", 400), ("hidden-2", 600)} + kind = nodes["kind"] + assert sorted(row["name"] for row in kind["data"]["attributes"]) == ["...", "GREEN", "RED"] + edges = result["edges"] + assert {(e["source"], e["target"]) for e in edges + if e["type"] == "ClassInheritance"} == {("dog", "animal"), ("hidden-1", "dog"), ("hidden-2", "animal")} + assert {e["type"] for e in edges} == {"ClassInheritance", "ClassBidirectional"} def test_the_converted_diagram_converts_to_the_same_model_again(diagram): @@ -81,11 +81,8 @@ def shape(model): def test_a_placeholder_association_class_is_resolved_by_id(): diagram = placeholder_diagram() - diagram["model"]["elements"]["link"] = { - "type": "Class", "name": PLACEHOLDER_NAME, "attributes": [], "methods": [], "bounds": _bounds(1000, 0)} - diagram["model"]["relationships"]["link-rel"] = { - "id": "link-rel", "type": "ClassLinkRel", - "source": {"element": "link"}, "target": {"element": "animal-hidden-1"}} + diagram["model"]["nodes"].append(class_node("link", PLACEHOLDER_NAME, 1000)) + diagram["model"]["edges"].append(edge("link-rel", "ClassLinkRel", "link", "animal-hidden-1")) model = process_class_diagram(copy.deepcopy(diagram)) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_diagram_defaults.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_diagram_defaults.py index 837eeb86b..43dddbd59 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_diagram_defaults.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_diagram_defaults.py @@ -73,8 +73,8 @@ def test_project_with_component_and_deployment_round_trips(tmp_path): assert len(component) == 1 assert component[0]["model"]["type"] == "ComponentDiagram" component_names = { - el["name"] for el in component[0]["model"]["elements"].values() - if el.get("type") == "Component" + node["data"]["name"] for node in component[0]["model"]["nodes"] + if node["type"] == "component" } assert component_names == {"Api", "Worker"} @@ -82,12 +82,12 @@ def test_project_with_component_and_deployment_round_trips(tmp_path): assert len(deployment) == 1 assert deployment[0]["model"]["type"] == "DeploymentDiagram" assert any( - el.get("name") == "Server" for el in deployment[0]["model"]["elements"].values() + node["data"].get("name") == "Server" for node in deployment[0]["model"]["nodes"] ) class_names = { - el["name"] for el in diagrams["ClassDiagram"][0]["model"]["elements"].values() - if el.get("type") == "Class" + node["data"]["name"] for node in diagrams["ClassDiagram"][0]["model"]["nodes"] + if node["type"] == "class" } assert class_names == {"Book"} @@ -104,7 +104,7 @@ def test_project_without_component_or_deployment_gets_placeholders(tmp_path): placeholder = imported["diagrams"][diagram_type][0] assert placeholder["title"] == DIAGRAM_DEFAULT_TITLES[diagram_type] assert placeholder["model"]["type"] == diagram_type - assert placeholder["model"]["elements"] == {} + assert placeholder["model"]["nodes"] == [] def test_single_diagram_fallback_uses_same_slots(tmp_path): diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_object_class_reference.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_object_class_reference.py new file mode 100644 index 000000000..22676eb10 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_object_class_reference.py @@ -0,0 +1,130 @@ +"""Object diagrams in a project resolve their objects' classes by ``classId``. + +Projects migrated from the develop editor keep only ``classId`` on each +object (develop resolved it through an embedded ``referenceDiagramData`` +snapshot, which the v4 migration drops), and object names such as +``author1`` do not match any class. ``json_to_buml_project`` must resolve +``classId`` against the project's class diagram instead. +""" + +from besser.BUML.metamodel.object import ObjectModel +from besser.utilities.web_modeling_editor.backend.models import ProjectInput +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.project_converter import ( + json_to_buml_project, +) + + +def _class_node(node_id, name, attr_id, attr_name): + return { + "id": node_id, + "type": "class", + "position": {"x": 0, "y": 0}, + "data": { + "name": name, + "methods": [], + "attributes": [ + {"id": attr_id, "name": attr_name, "visibility": "public", "attributeType": "str"}, + ], + }, + } + + +CLASS_MODEL = { + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + _class_node("cls-author", "Author", "attr-alias", "alias"), + _class_node("cls-book", "Book", "attr-title", "title"), + ], + "edges": [ + { + "id": "assoc-1", + "source": "cls-book", + "target": "cls-author", + "type": "ClassBidirectional", + "data": { + "name": "authors", + "sourceRole": "books", + "sourceMultiplicity": "*", + "targetRole": "writers", + "targetMultiplicity": "1..*", + }, + } + ], +} + + +def _object_node(node_id, name, class_id, attr_name, value, class_name=None): + data = { + "name": name, + "classId": class_id, + "attributes": [{"id": f"{node_id}-a", "name": attr_name, "value": value}], + } + if class_name is not None: + data["className"] = class_name + return {"id": node_id, "type": "objectName", "position": {"x": 0, "y": 0}, "data": data} + + +def _project(object_nodes): + object_model = { + "version": "4.0.0", + "type": "ObjectDiagram", + "nodes": object_nodes, + "edges": [ + { + "id": "link-1", + "source": "o-book", + "target": "o-author", + "type": "ObjectLink", + "data": {"name": "authors", "associationId": "assoc-1"}, + } + ], + } + return ProjectInput(**{ + "id": "p1", + "type": "Project", + "name": "Library", + "createdAt": "2025-01-01T00:00:00Z", + "currentDiagramType": "ObjectDiagram", + "currentDiagramIndices": {"ClassDiagram": 0, "ObjectDiagram": 0}, + "diagrams": { + "ClassDiagram": [{"id": "cd-1", "title": "Classes", "model": CLASS_MODEL}], + "ObjectDiagram": [ + { + "id": "od-1", + "title": "Objects", + "model": object_model, + "references": {"ClassDiagram": "cd-1"}, + } + ], + }, + }) + + +def _objects(project): + object_models = [m for m in json_to_buml_project(project).models if isinstance(m, ObjectModel)] + assert len(object_models) == 1 + return {o.name: o for o in object_models[0].objects} + + +def test_objects_with_only_class_id_resolve_their_class(): + objects = _objects(_project([ + _object_node("o-author", "author1", "cls-author", "alias", "Ann"), + _object_node("o-book", "book1", "cls-book", "title", "Dune"), + ])) + + assert objects["author1"].classifier.name == "Author" + assert objects["book1"].classifier.name == "Book" + assert {s.attribute.name: s.value.value for s in objects["author1"].slots} == {"alias": "Ann"} + assert len(objects["book1"].links) == 1 + + +def test_class_id_wins_over_stale_class_name(): + # The class was renamed after the object was drawn: className is stale. + objects = _objects(_project([ + _object_node("o-author", "author1", "cls-author", "alias", "Ann", class_name="Writer"), + _object_node("o-book", "book1", "cls-book", "title", "Dune", class_name="Novel"), + ])) + + assert objects["author1"].classifier.name == "Author" + assert objects["book1"].classifier.name == "Book" diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_section_titles.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_section_titles.py index 0de79e7b0..1f67c7efa 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_section_titles.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_section_titles.py @@ -31,7 +31,7 @@ def test_each_structural_model_comes_back_once_with_its_title_and_classes(tmp_pa diagrams = project_to_json(path.read_text(encoding="utf-8"))["diagrams"]["ClassDiagram"] assert [ - (d["title"], sorted(e["name"] for e in d["model"]["elements"].values() if e["type"] == "Class")) + (d["title"], sorted(n["data"]["name"] for n in d["model"]["nodes"] if n["type"] == "class")) for d in diagrams ] == [("Library", ["Book"]), ("Shop", ["Item"])] @@ -66,4 +66,5 @@ def test_an_owner_holding_the_definition_header_words_still_imports(tmp_path): assert imported["owner"] == "Ada # PROJECT DEFINITION #" (diagram,) = imported["diagrams"]["ClassDiagram"] - assert [e["name"] for e in diagram["model"]["elements"].values() if e["type"] == "Class"] == ["Book"] + assert [n["data"]["name"] for n in diagram["model"]["nodes"] + if n["type"] == "class" and not n["data"].get("stereotype")] == ["Book"] diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_single_diagram_fallback.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_single_diagram_fallback.py index e80bd4481..05fd969bf 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_single_diagram_fallback.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_single_diagram_fallback.py @@ -6,6 +6,10 @@ ``models=[...]`` declaration should still be importable through the Project Import flow — the converter wraps it into a one-diagram project rather than failing with ``No models defined in 'models=[...]'``. + +The diagram models inside the project envelope follow the v4 wire shape +(``{version: "4.0.0", nodes, edges}``); GUI models keep their bespoke +``{pages}`` shape. """ from pathlib import Path @@ -44,6 +48,14 @@ ''' +def _class_names(model: dict) -> set: + return { + node["data"]["name"] + for node in model["nodes"] + if node.get("type") == "class" + } + + def test_detects_class_diagram_from_plain_domain_model(): assert _detect_single_diagram_type(SUPPLEMENT_CLASS_MODEL) == "ClassDiagram" @@ -73,20 +85,20 @@ def test_project_to_json_wraps_single_class_diagram(): assert isinstance(diagrams[diagram_type], list) assert len(diagrams[diagram_type]) == 1 - # The class diagram is actually populated with the User and Item classes. - class_entry = diagrams["ClassDiagram"][0] - elements = class_entry["model"]["elements"] - class_names = {el["name"] for el in elements.values() if el.get("type") == "Class"} - assert class_names == {"User", "Item"} + # The class diagram is actually populated with the User and Item classes, + # emitted in the canonical v4 wire shape. + class_model = diagrams["ClassDiagram"][0]["model"] + assert class_model["version"] == "4.0.0" + assert _class_names(class_model) == {"User", "Item"} - # The other diagrams are empty placeholders (no elements / no pages). + # The other diagrams are empty v4 placeholders (no nodes / no edges). for other_type in ( "ObjectDiagram", "AgentDiagram", "StateMachineDiagram", "QuantumCircuitDiagram", "NNDiagram", ): other_model = diagrams[other_type][0]["model"] - assert other_model.get("elements") == {} - assert other_model.get("relationships") == {} + assert other_model.get("nodes") == [] + assert other_model.get("edges") == [] gui_model = diagrams["GUINoCodeDiagram"][0]["model"] assert gui_model.get("pages") == [] @@ -150,14 +162,11 @@ def test_project_to_json_handles_missing_section_headers(): assert project["owner"] == "Tester" assert project["description"] == "A small library project." - class_entry = project["diagrams"]["ClassDiagram"][0] - elements = class_entry["model"]["elements"] - relationships = class_entry["model"]["relationships"] - - class_names = {el["name"] for el in elements.values() if el.get("type") == "Class"} - assert class_names == {"Book", "Author"} - # The BinaryAssociation should round-trip into the relationships map. - assert len(relationships) == 1 + class_model = project["diagrams"]["ClassDiagram"][0]["model"] + assert class_model["version"] == "4.0.0" + assert _class_names(class_model) == {"Book", "Author"} + # The BinaryAssociation should round-trip into the v4 edges list. + assert len(class_model["edges"]) == 1 ECORE_PROJECT = (Path(__file__).parent / "data" / "ecore_algorithme_project.py").read_text(encoding="utf-8") @@ -190,8 +199,11 @@ def _edit(content, *replacements): def _class_diagram(project): model = project["diagrams"]["ClassDiagram"][0]["model"] - names = {el["name"] for el in model["elements"].values() if el.get("type") in ("Class", "AbstractClass")} - return names, model["relationships"] + names = { + node["data"]["name"] for node in model["nodes"] + if node.get("type") == "class" and (node["data"].get("stereotype") or "").lower() != "enumeration" + } + return names, model["edges"] def test_an_ecore_converter_project_imports_with_its_compositions_repaired(): @@ -204,7 +216,7 @@ def test_an_ecore_converter_project_imports_with_its_compositions_repaired(): names, relationships = _class_diagram(project) assert names == {"PortSortie", "Port", "Documentation", "AlgorithmeElement", "Algorithme", "PortEntree", "Ressource"} - assert sorted(r["type"] for r in relationships.values()) == [ + assert sorted(r["type"] for r in relationships) == [ "ClassBidirectional", "ClassComposition", "ClassComposition", "ClassInheritance", "ClassInheritance", "ClassInheritance", "ClassInheritance", ] @@ -237,7 +249,7 @@ def test_a_composition_with_a_non_navigable_owner_end_is_repaired_and_reported() names, relationships = _class_diagram(project_to_json(NON_NAVIGABLE_OWNER, warnings)) assert names == {"Book", "Author"} - [relationship] = relationships.values() + [relationship] = relationships assert relationship["type"] == "ClassComposition" assert warnings == [ "Association 'book_author': the non-composite end 'book' (Book) of a composition must be " @@ -290,6 +302,5 @@ def test_project_to_json_handles_main_guard(): project = project_to_json(content_with_main_guard) assert project["currentDiagramType"] == "ClassDiagram" - elements = project["diagrams"]["ClassDiagram"][0]["model"]["elements"] - class_names = {el["name"] for el in elements.values() if el.get("type") == "Class"} - assert class_names == {"User", "Item"} + class_model = project["diagrams"]["ClassDiagram"][0]["model"] + assert _class_names(class_model) == {"User", "Item"} diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_user_diagram_roundtrip.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_user_diagram_roundtrip.py index abae5801c..96ae2729c 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_user_diagram_roundtrip.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_user_diagram_roundtrip.py @@ -3,8 +3,8 @@ A project export writes a UserDiagram as the user reference domain model (``user_model``) plus an object section (``user_object_model``). ``project_to_json`` has to read those back as a ``UserDiagram`` built from the -elements ``json_to_buml``'s object processor reads (``UserModelName``, -``UserModelAttribute`` with ``attributeOperator``), and must not import the +nodes ``json_to_buml``'s object processor reads (``UserModelName`` nodes whose +attribute rows carry ``attributeOperator``), and must not import the reference model as a class diagram. A class diagram that merely has a class named ``User`` stays a class diagram. """ @@ -24,94 +24,68 @@ ) -def _box(x=0, y=0): - return {"x": x, "y": y, "width": 200, "height": 100} +def _node(node_id, node_type, data): + return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, + "width": 200, "height": 100, "data": data} -def _user_object(eid, name, class_name, criteria=()): - """A UserModelName plus one UserModelAttribute per (name, value) criterion.""" - elements = { - eid: { - "id": eid, "name": name, "type": "UserModelName", "owner": None, - "bounds": _box(), "attributes": [f"{eid}-{attr}" for attr, _ in criteria], - "methods": [], "className": class_name, - }, - } - for attr, value in criteria: - elements[f"{eid}-{attr}"] = { - "id": f"{eid}-{attr}", "name": f"{attr} = {value}", - "type": "UserModelAttribute", "owner": eid, "attributeOperator": "==", - "bounds": _box(), - } - return elements +def _user_object(node_id, name, class_name, criteria=()): + """A UserModelName node with one equality-criterion row per (name, value).""" + rows = [ + {"id": f"{node_id}-{attr}", "name": attr, "value": value, "attributeOperator": "=="} + for attr, value in criteria + ] + return _node(node_id, "UserModelName", + {"name": name, "className": class_name, "attributes": rows, "methods": []}) -def _object_link(rid, source, target): - return { - "id": rid, "name": "", "type": "ObjectLink", "owner": None, "bounds": _box(), - "path": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], - "source": {"element": source, "direction": "Right"}, - "target": {"element": target, "direction": "Left"}, - } +def _object_link(edge_id, source, target, edge_type="UserModelLink"): + return {"id": edge_id, "type": edge_type, "source": source, "target": target, + "data": {"name": "", "points": [{"x": 0, "y": 0}, {"x": 10, "y": 0}]}} def _user_diagram(title="Alice"): - elements = {} - elements.update(_user_object("u-user", "user_1", "User")) - elements.update(_user_object( - "u-info", "personal_Information_1", "Personal_Information", - [("firstName", "Alice"), ("age", "30"), ("gender", "Female")], - )) - elements.update(_user_object("u-comp", "competence_1", "Competence")) - elements.update(_user_object("u-eng", "language_1", "Language", [("iso693_3", "eng")])) - elements.update(_user_object("u-fra", "language_2", "Language", [("iso693_3", "fra")])) - relationships = { - "l-info": _object_link("l-info", "u-user", "u-info"), - "l-comp": _object_link("l-comp", "u-user", "u-comp"), - "l-eng": _object_link("l-eng", "u-comp", "u-eng"), - "l-fra": _object_link("l-fra", "u-comp", "u-fra"), - } + nodes = [ + _user_object("u-user", "user_1", "User"), + _user_object("u-info", "personal_Information_1", "Personal_Information", + [("firstName", "Alice"), ("age", "30"), ("gender", "Female")]), + _user_object("u-comp", "competence_1", "Competence"), + _user_object("u-eng", "language_1", "Language", [("iso693_3", "eng")]), + _user_object("u-fra", "language_2", "Language", [("iso693_3", "fra")]), + ] + edges = [ + _object_link("l-info", "u-user", "u-info"), + _object_link("l-comp", "u-user", "u-comp"), + _object_link("l-eng", "u-comp", "u-eng"), + _object_link("l-fra", "u-comp", "u-fra"), + ] return { "id": f"user-diagram-{title}", "title": title, - "model": { - "version": "3.0.0", "type": "UserDiagram", "size": {"width": 1400, "height": 740}, - "elements": elements, "relationships": relationships, - "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, - }, + "model": {"version": "4.0.0", "type": "UserDiagram", "nodes": nodes, "edges": edges, + "assessments": {}}, } def _class_diagram(): """An ordinary class diagram that happens to have a class named ``User``.""" - def cls(eid, name, attr_ids): - return {"id": eid, "name": name, "type": "Class", "owner": None, "bounds": _box(), - "attributes": attr_ids, "methods": []} - - def attr(eid, owner, name): - return {"id": eid, "name": name, "type": "ClassAttribute", "owner": owner, - "visibility": "public", "attributeType": "str", "bounds": _box()} + def cls(node_id, name, attr_id, attr_name): + return _node(node_id, "class", {"name": name, "methods": [], "attributes": [ + {"id": attr_id, "name": attr_name, "visibility": "public", "attributeType": "str"}, + ]}) return { "id": "class-diagram", "title": "Library", "model": { - "version": "3.0.0", "type": "ClassDiagram", "size": {"width": 1400, "height": 740}, - "elements": { - "c-user": cls("c-user", "User", ["a-uname"]), - "a-uname": attr("a-uname", "c-user", "username"), - "c-book": cls("c-book", "Book", ["a-title"]), - "a-title": attr("a-title", "c-book", "title"), - }, - "relationships": { - "r-borrows": { - "id": "r-borrows", "name": "borrows", "type": "ClassBidirectional", - "owner": None, "bounds": _box(), - "source": {"element": "c-user", "multiplicity": "0..*", "role": "borrower"}, - "target": {"element": "c-book", "multiplicity": "0..*", "role": "loans"}, - }, - }, - "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, + "version": "4.0.0", "type": "ClassDiagram", "assessments": {}, + "nodes": [cls("c-user", "User", "a-uname", "username"), + cls("c-book", "Book", "a-title", "title")], + "edges": [{ + "id": "r-borrows", "type": "ClassBidirectional", "source": "c-user", "target": "c-book", + "data": {"name": "borrows", "sourceMultiplicity": "0..*", "sourceRole": "borrower", + "targetMultiplicity": "0..*", "targetRole": "loans", "points": []}, + }], }, } @@ -122,16 +96,11 @@ def _object_diagram(): "title": "Loans", "references": {"ClassDiagram": "class-diagram"}, "model": { - "version": "3.0.0", "type": "ObjectDiagram", "size": {"width": 1400, "height": 740}, - "elements": { - "o-bob": {"id": "o-bob", "name": "bob", "type": "ObjectName", "owner": None, - "bounds": _box(), "attributes": ["o-bob-name"], "methods": [], - "className": "User"}, - "o-bob-name": {"id": "o-bob-name", "name": "username = bob", - "type": "ObjectAttribute", "owner": "o-bob", "bounds": _box()}, - }, - "relationships": {}, - "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, + "version": "4.0.0", "type": "ObjectDiagram", "assessments": {}, "edges": [], + "nodes": [_node("o-bob", "objectName", { + "name": "bob", "className": "User", "methods": [], + "attributes": [{"id": "o-bob-name", "name": "username", "value": "bob"}], + })], }, } @@ -187,31 +156,25 @@ def test_user_diagram_round_trips(tmp_path): assert "user_object_model" in source diagrams = imported["diagrams"] # The reference model is context, not a class diagram. - assert diagrams["ClassDiagram"][0]["model"]["elements"] == {} + assert diagrams["ClassDiagram"][0]["model"]["nodes"] == [] assert imported["currentDiagramIndices"]["UserDiagram"] == 0 [user_diagram] = diagrams["UserDiagram"] assert user_diagram["title"] == "Alice" model = user_diagram["model"] assert model["type"] == "UserDiagram" - element_types = {el["type"] for el in model["elements"].values()} - assert element_types == {"UserModelName", "UserModelAttribute"} - criteria = { - el["name"] for el in model["elements"].values() if el["type"] == "UserModelAttribute" - } - assert criteria == { - "firstName = Alice", "age = 30", "gender = Female", "iso693_3 = eng", "iso693_3 = fra", - } - assert all( - el["attributeOperator"] == "==" for el in model["elements"].values() - if el["type"] == "UserModelAttribute" - ) - class_names = { - el["name"]: el["className"] for el in model["elements"].values() - if el["type"] == "UserModelName" + assert "referenceDiagramData" not in model + assert {node["type"] for node in model["nodes"]} == {"UserModelName"} + rows = [row for node in model["nodes"] for row in node["data"]["attributes"]] + assert {(row["name"], row["value"]) for row in rows} == { + ("firstName", "Alice"), ("age", "30"), ("gender", "Female"), + ("iso693_3", "eng"), ("iso693_3", "fra"), } + assert all(row["attributeOperator"] == "==" for row in rows) + class_names = {node["data"]["name"]: node["data"]["className"] for node in model["nodes"]} assert class_names["personal_Information_1"] == "Personal_Information" - assert len(model["relationships"]) == 4 + assert {edge["type"] for edge in model["edges"]} == {"UserModelLink"} + assert len(model["edges"]) == 4 # JSON -> B-UML again yields the same user model. reimported = json_to_buml_project(ProjectInput(**imported)) @@ -247,16 +210,17 @@ def test_user_diagram_beside_class_diagram_with_user_class(tmp_path): assert "domain_model" in source [class_diagram] = diagrams["ClassDiagram"] class_names = { - el["name"] for el in class_diagram["model"]["elements"].values() if el["type"] == "Class" + node["data"]["name"] for node in class_diagram["model"]["nodes"] if node["type"] == "class" } assert class_names == {"User", "Book"} [object_diagram] = diagrams["ObjectDiagram"] assert object_diagram["model"]["type"] == "ObjectDiagram" assert { - el["name"] for el in object_diagram["model"]["elements"].values() - if el["type"] == "ObjectAttribute" - } == {"username = bob"} + (row["name"], row["value"]) + for node in object_diagram["model"]["nodes"] if node["type"] == "objectName" + for row in node["data"]["attributes"] + } == {("username", "bob")} [user_diagram] = diagrams["UserDiagram"] reimported = json_to_buml_project(ProjectInput(**imported)) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_project_valid_diagrams.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_valid_diagrams.py new file mode 100644 index 000000000..135c3f41d --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_project_valid_diagrams.py @@ -0,0 +1,59 @@ +"""Which project diagrams ``json_to_buml_project`` keeps. + +An agent diagram whose only content is off-canvas ``components`` (intents, +LLMs, ...) and no canvas ``nodes`` is still a model and must not be dropped. +""" + +from besser.BUML.metamodel.state_machine.agent import Agent +from besser.utilities.web_modeling_editor.backend.models import ProjectInput +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.project_converter import ( + _is_valid_diagram, + json_to_buml_project, +) + + +def _agent_model(nodes=None, components=None): + model = {"version": "4.0.0", "type": "AgentDiagram", "title": "Bot", "nodes": nodes or [], "edges": []} + if components is not None: + model["components"] = components + return model + + +INTENT_COMPONENTS = { + "i1": {"id": "i1", "type": "AgentIntent", "name": "Greeting", "intent_description": "", "bodies": ["b1"]}, + "b1": {"id": "b1", "type": "AgentIntentBody", "name": "hello", "owner": "i1"}, +} + + +def _project(agent_model): + return ProjectInput(**{ + "id": "p1", + "type": "Project", + "name": "ComponentsOnly", + "createdAt": "2025-01-01T00:00:00Z", + "currentDiagramType": "AgentDiagram", + "currentDiagramIndices": {"AgentDiagram": 0}, + "diagrams": {"AgentDiagram": [{"id": "a1", "title": "Bot", "model": agent_model}]}, + }) + + +def test_agent_diagram_with_only_components_is_valid(): + project = _project(_agent_model(components=INTENT_COMPONENTS)) + assert _is_valid_diagram(project.diagrams["AgentDiagram"][0], "AgentDiagram") + + +def test_empty_agent_diagram_is_still_dropped(): + project = _project(_agent_model(components={})) + assert not _is_valid_diagram(project.diagrams["AgentDiagram"][0], "AgentDiagram") + + +def test_components_do_not_validate_other_diagram_types(): + project = _project(_agent_model(components=INTENT_COMPONENTS)) + assert not _is_valid_diagram(project.diagrams["AgentDiagram"][0], "StateMachineDiagram") + + +def test_components_only_agent_is_kept_in_project(): + buml_project = json_to_buml_project(_project(_agent_model(components=INTENT_COMPONENTS))) + agents = [m for m in buml_project.models if isinstance(m, Agent)] + assert len(agents) == 1 + assert [intent.name for intent in agents[0].intents] == ["Greeting"] diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_role_name_warnings.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_role_name_warnings.py index cfd6d8a42..89ffa9d37 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_role_name_warnings.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_role_name_warnings.py @@ -34,33 +34,30 @@ def _two_class_diagram(src_name, tgt_name, src_role, tgt_role, src_mult="0..*", tgt_mult="0..*"): """A minimal bidirectional association ``src -> tgt`` with the given role - names/multiplicities, in the JSON shape the visual editor POSTs.""" + names/multiplicities, in the v4 JSON shape the visual editor POSTs.""" return { "title": "Model", "model": { - "elements": { - "cls-src": { - "id": "cls-src", "name": src_name, "type": "Class", - "owner": None, "attributes": [], "methods": [], - }, - "cls-tgt": { - "id": "cls-tgt", "name": tgt_name, "type": "Class", - "owner": None, "attributes": [], "methods": [], - }, - }, - "relationships": { - "rel": { - "id": "rel", "name": "assoc", "type": "ClassBidirectional", - "source": { - "element": "cls-src", "multiplicity": src_mult, - "role": src_role, - }, - "target": { - "element": "cls-tgt", "multiplicity": tgt_mult, - "role": tgt_role, - }, - }, - }, + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + {"id": "cls-src", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": src_name, "stereotype": None, + "attributes": [], "methods": []}}, + {"id": "cls-tgt", "type": "class", + "position": {"x": 300, "y": 0}, "width": 160, "height": 100, + "data": {"name": tgt_name, "stereotype": None, + "attributes": [], "methods": []}}, + ], + "edges": [ + {"id": "rel", "type": "ClassBidirectional", + "source": "cls-src", "target": "cls-tgt", + "data": {"name": "assoc", + "sourceRole": src_role, "sourceMultiplicity": src_mult, + "targetRole": tgt_role, "targetMultiplicity": tgt_mult, + "points": []}}, + ], }, } diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_timestamp_roundtrip.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_timestamp_roundtrip.py index 13fde9eef..842ffb7d0 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_timestamp_roundtrip.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_timestamp_roundtrip.py @@ -1,10 +1,15 @@ """Element timestamps survive the class-diagram converters (GitHub issue #152). -``class_buml_to_json`` writes an optional ISO 8601 ``timestamp`` on every -element, relationship, association end and on the diagram model itself, when -that timestamp is explicit; ``process_class_diagram`` reads it back, and falls -back to the creation time when it is absent or malformed. Defaulted -timestamps are never written, so timestamp-less input converts identically. +``class_buml_to_json`` writes an optional ISO 8601 timestamp on every element, +relationship, association end and on the diagram model itself, when that +timestamp is explicit; ``process_class_diagram`` reads it back, and falls back +to the creation time when it is absent or malformed. Defaulted timestamps are +never written, so timestamp-less input converts identically. + +v4 locations: ``model.timestamp``, ``node.data.timestamp`` (classes, +enumerations, OCL constraint nodes), ``timestamp`` on attribute / method / +literal rows, ``edge.data.timestamp`` (associations, generalizations) and +``edge.data.sourceTimestamp`` / ``targetTimestamp`` (association ends). """ import copy from datetime import datetime, timedelta, timezone @@ -27,90 +32,90 @@ _timestamps, ) -_BOUNDS = {"x": 0, "y": 0, "width": 160, "height": 100} - - def _iso(second: int) -> str: return f"2024-05-06T07:08:{second:02d}.000042" +def _node(node_id, name, second, stereotype=None, attributes=(), methods=()): + return {"id": node_id, "type": "class", "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, + "data": {"name": name, "stereotype": stereotype, "attributes": list(attributes), + "methods": list(methods), "timestamp": _iso(second)}} + + +def _row(row_id, name, second, attribute_type="str"): + return {"id": row_id, "name": name, "visibility": "public", + "attributeType": attribute_type, "timestamp": _iso(second)} + + +def _association(edge_id, name, source, target, ends, second): + (source_role, source_mult, source_second), (target_role, target_mult, target_second) = ends + return {"id": edge_id, "type": "ClassBidirectional", "source": source, "target": target, + "data": {"name": name, "timestamp": _iso(second), + "sourceRole": source_role, "sourceMultiplicity": source_mult, + "sourceTimestamp": _iso(source_second), + "targetRole": target_role, "targetMultiplicity": target_mult, + "targetTimestamp": _iso(target_second), "points": []}} + + def _diagram() -> dict: - """A class diagram whose every element carries a distinct timestamp.""" - def member(member_id, owner, name, second, **extra): - return {"id": member_id, "name": name, "type": extra.pop("type", "ClassAttribute"), - "owner": owner, "bounds": _BOUNDS, "timestamp": _iso(second), **extra} - - attr = {"visibility": "public", "attributeType": "str"} - elements = { - "status": {"id": "status", "name": "Status", "type": "Enumeration", "owner": None, - "bounds": _BOUNDS, "attributes": ["open", "closed"], "methods": [], - "timestamp": _iso(1)}, - "open": member("open", "status", "OPEN", 2), - "closed": member("closed", "status", "CLOSED", 3), - "library": {"id": "library", "name": "Library", "type": "Class", "owner": None, - "bounds": _BOUNDS, "attributes": ["lib-name"], "methods": ["renew"], - "timestamp": _iso(4)}, - "lib-name": member("lib-name", "library", "name", 5, **attr), - "renew": member("renew", "library", "+ renew(days: int): str", 6, type="ClassMethod"), - "book": {"id": "book", "name": "Book", "type": "AbstractClass", "owner": None, - "bounds": _BOUNDS, "attributes": ["book-status"], "methods": [], - "timestamp": _iso(7)}, - "book-status": member("book-status", "book", "status", 8, - visibility="public", attributeType="Status"), - "novel": {"id": "novel", "name": "Novel", "type": "Class", "owner": None, - "bounds": _BOUNDS, "attributes": [], "methods": [], "timestamp": _iso(9)}, - "loan": {"id": "loan", "name": "Loan", "type": "Class", "owner": None, - "bounds": _BOUNDS, "attributes": [], "methods": [], "timestamp": _iso(10)}, - "ocl": {"id": "ocl", "name": "", "type": "ClassOCLConstraint", "owner": None, - "bounds": _BOUNDS, "timestamp": _iso(11), - "constraint": "context Library inv named: self.name <> ''"}, - } - - def end(element, role, multiplicity, second): - return {"element": element, "role": role, "multiplicity": multiplicity, - "timestamp": _iso(second)} - - relationships = { - "holds": {"id": "holds", "name": "Library_Book", "type": "ClassBidirectional", - "timestamp": _iso(12), - "source": end("library", "library", "1", 13), - "target": end("book", "books", "0..*", 14)}, - "lends": {"id": "lends", "name": "Library_Novel", "type": "ClassBidirectional", - "timestamp": _iso(15), - "source": end("library", "lender", "1", 16), - "target": end("novel", "novels", "0..*", 17)}, - "inherits": {"id": "inherits", "type": "ClassInheritance", "timestamp": _iso(18), - "source": {"element": "novel"}, "target": {"element": "book"}}, - "loan-link": {"id": "loan-link", "type": "ClassLinkRel", - "source": {"element": "lends"}, "target": {"element": "loan"}}, - } + """A v4 class diagram whose every element carries a distinct timestamp.""" + renew = {"id": "renew", "name": "renew", "visibility": "public", "returnType": "str", + "attributeType": "str", "timestamp": _iso(6), + "parameters": [{"id": "renew-days", "name": "days", "parameterType": "int"}]} + nodes = [ + _node("status", "Status", 1, "Enumeration", + attributes=[_row("open", "OPEN", 2), _row("closed", "CLOSED", 3)]), + _node("library", "Library", 4, attributes=[_row("lib-name", "name", 5)], methods=[renew]), + _node("book", "Book", 7, "Abstract", attributes=[_row("book-status", "status", 8, "Status")]), + _node("novel", "Novel", 9), + _node("loan", "Loan", 10), + {"id": "ocl", "type": "ClassOCLConstraint", "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, + "data": {"name": "", "timestamp": _iso(11), + "expression": "context Library inv named: self.name <> ''"}}, + ] + edges = [ + _association("holds", "Library_Book", "library", "book", + (("library", "1", 13), ("books", "0..*", 14)), 12), + _association("lends", "Library_Novel", "library", "novel", + (("lender", "1", 16), ("novels", "0..*", 17)), 15), + {"id": "inherits", "type": "ClassInheritance", "source": "novel", "target": "book", + "data": {"timestamp": _iso(18), "points": []}}, + {"id": "loan-link", "type": "ClassLinkRel", "source": "lends", "target": "loan", + "data": {"points": []}}, + ] return {"title": "Lending", "model": { - "type": "ClassDiagram", "timestamp": _iso(19), - "elements": elements, "relationships": relationships, + "version": "4.0.0", "type": "ClassDiagram", "timestamp": _iso(19), + "nodes": nodes, "edges": edges, }} +def _node_by_id(diagram: dict, node_id: str) -> dict: + return next(n for n in diagram["model"]["nodes"] if n["id"] == node_id) + + def _json_timestamps(model_json: dict) -> dict: - """Map a name-based key (element ids are regenerated) to each JSON timestamp.""" - elements = model_json["elements"] + """Map a name-based key (node and row ids are regenerated) to each JSON timestamp.""" + names = {n["id"]: n["data"].get("name") for n in model_json["nodes"]} found = {("model",): model_json.get("timestamp")} - for element in elements.values(): - if element["type"] in ("ClassAttribute", "ClassMethod"): - owner = elements[element["owner"]]["name"] - key = (element["type"], owner, element["name"]) - elif element["type"] == "ClassOCLConstraint": - key = (element["type"], element["constraint"]) - else: - key = (element["type"], element["name"]) - found[key] = element.get("timestamp") - for rel in model_json["relationships"].values(): - if rel["type"] == "ClassInheritance": - specific = elements[rel["source"]["element"]]["name"] - found[(rel["type"], specific)] = rel.get("timestamp") - elif rel.get("name"): - found[(rel["type"], rel["name"])] = rel.get("timestamp") + for node in model_json["nodes"]: + data = node["data"] + if node["type"] == "ClassOCLConstraint": + found[(node["type"], data["expression"])] = data.get("timestamp") + continue + found[(node["type"], data["name"])] = data.get("timestamp") + for kind in ("attributes", "methods"): + for row in data.get(kind) or []: + found[(kind, data["name"], row["name"])] = row.get("timestamp") + for edge in model_json["edges"]: + data = edge["data"] + if edge["type"] == "ClassInheritance": + found[(edge["type"], names[edge["source"]])] = data.get("timestamp") + elif data.get("name"): + found[(edge["type"], data["name"])] = data.get("timestamp") for side in ("source", "target"): - found[("end", rel["name"], rel[side]["role"])] = rel[side].get("timestamp") + found[("end", data["name"], data[f"{side}Role"])] = data.get(f"{side}Timestamp") return found @@ -138,8 +143,8 @@ def test_json_buml_json_preserves_timestamps(): exported = class_buml_to_json(process_class_diagram(diagram)) stamps = _json_timestamps(exported) expected = _json_timestamps(diagram["model"]) - # The fixture uses the export's own naming (bare attribute names, full - # method signatures), so every key lines up. + # The fixture uses the export's own naming (bare attribute and method + # names), so every key lines up. assert stamps == expected assert all(value is not None for value in stamps.values()) @@ -156,12 +161,7 @@ def test_buml_json_buml_preserves_timestamps(): def test_missing_timestamps_fall_back_to_creation_time(): - diagram = _diagram() - for item in [diagram["model"], *diagram["model"]["elements"].values()]: - item.pop("timestamp", None) - for rel in diagram["model"]["relationships"].values(): - for item in (rel, rel["source"], rel["target"]): - item.pop("timestamp", None) + diagram = _without_timestamps(_diagram()) before = datetime.now() model = process_class_diagram(diagram) assert all(stamp >= before for stamp in _timestamps(model).values()) @@ -170,7 +170,7 @@ def test_missing_timestamps_fall_back_to_creation_time(): @pytest.mark.parametrize("bad", ["not a date", "", "2024-13-45T99:99:99", 12345, None, ["x"]]) def test_malformed_timestamp_falls_back_to_creation_time(bad): diagram = copy.deepcopy(_diagram()) - diagram["model"]["elements"]["library"]["timestamp"] = bad + _node_by_id(diagram, "library")["data"]["timestamp"] = bad before = datetime.now() model = process_class_diagram(diagram) assert model.get_class_by_name("Library").timestamp >= before @@ -183,7 +183,7 @@ def test_timezone_aware_timestamp_becomes_naive_utc(): It is normalised to UTC, never to the server's local time.""" diagram = _diagram() aware = datetime(2024, 5, 6, 7, 8, 9, tzinfo=timezone(timedelta(hours=2))) - diagram["model"]["elements"]["library"]["timestamp"] = aware.isoformat() + _node_by_id(diagram, "library")["data"]["timestamp"] = aware.isoformat() model = process_class_diagram(diagram) stamp = model.get_class_by_name("Library").timestamp assert stamp.tzinfo is None @@ -234,19 +234,23 @@ def test_timestamp_helpers(): def test_exported_model_and_elements_carry_iso_strings(): exported = class_buml_to_json(_build_model()) assert exported["timestamp"] == "2024-03-01T09:30:21.123456" - classes = [e for e in exported["elements"].values() if e["type"] in ("Class", "AbstractClass")] - assert classes and all(isinstance(e["timestamp"], str) for e in classes) - constraint_boxes = [e for e in exported["elements"].values() if e["type"] == "ClassOCLConstraint"] - assert [e["timestamp"] for e in constraint_boxes] == ["2024-03-01T09:30:20.123456"] + classes = [n["data"] for n in exported["nodes"] + if n["type"] == "class" and n["data"].get("stereotype") != "Enumeration"] + assert classes and all(isinstance(c["timestamp"], str) for c in classes) + constraint_boxes = [n["data"] for n in exported["nodes"] if n["type"] == "ClassOCLConstraint"] + assert [c["timestamp"] for c in constraint_boxes] == ["2024-03-01T09:30:20.123456"] def _without_timestamps(diagram: dict) -> dict: diagram = copy.deepcopy(diagram) - for item in [diagram["model"], *diagram["model"]["elements"].values()]: - item.pop("timestamp", None) - for rel in diagram["model"]["relationships"].values(): - for item in (rel, rel["source"], rel["target"]): - item.pop("timestamp", None) + diagram["model"].pop("timestamp", None) + for node in diagram["model"]["nodes"]: + node["data"].pop("timestamp", None) + for row in node["data"].get("attributes", []) + node["data"].get("methods", []): + row.pop("timestamp", None) + for edge in diagram["model"]["edges"]: + for key in ("timestamp", "sourceTimestamp", "targetTimestamp"): + edge["data"].pop(key, None) return diagram diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_user_diagram_comment_isolation.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_user_diagram_comment_isolation.py index 40b598e07..f418269cf 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_user_diagram_comment_isolation.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_user_diagram_comment_isolation.py @@ -15,32 +15,26 @@ ) -def _box(): - return {"x": 0, "y": 0, "width": 200, "height": 100} +def _node(node_id, node_type, data): + return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, + "width": 200, "height": 100, "data": data} def _user_diagram(title, comment_text): return { "title": title, "model": { + "version": "4.0.0", "type": "UserDiagram", - "elements": { - "u-user": { - "id": "u-user", "name": "user_1", "type": "UserModelName", "owner": None, - "bounds": _box(), "attributes": [], "methods": [], "className": "User", - }, - "c-1": { - "id": "c-1", "name": comment_text, "type": "Comments", "owner": None, - "bounds": _box(), - }, - }, - "relationships": { - "l-1": { - "id": "l-1", "name": "", "type": "Link", "owner": None, "bounds": _box(), - "source": {"element": "c-1", "direction": "Right"}, - "target": {"element": "u-user", "direction": "Left"}, - }, - }, + "nodes": [ + _node("u-user", "UserModelName", + {"name": "user_1", "attributes": [], "methods": [], "className": "User"}), + _node("c-1", "comment", {"name": comment_text}), + ], + "edges": [ + {"id": "l-1", "type": "CommentLink", "source": "c-1", "target": "u-user", + "data": {"points": []}}, + ], }, } @@ -92,8 +86,9 @@ def test_object_diagram_comments_still_annotate_per_request_classes(): book = Class(name="Book", metadata=Metadata(description="A book")) model = DomainModel(name="Library", types={book}) payload = _user_diagram("Objects", "linked comment") - element = payload["model"]["elements"]["u-user"] - element.update({"type": "ObjectName", "name": "book_1", "className": "Book"}) + node = payload["model"]["nodes"][0] + node["type"] = "objectName" + node["data"].update({"name": "book_1", "className": "Book"}) object_model = process_object_diagram(payload, model) diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_user_profile_name_slot.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_user_profile_name_slot.py index 255b1b5e2..ddc6b6d3f 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/test_user_profile_name_slot.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_user_profile_name_slot.py @@ -8,26 +8,22 @@ ) -def _box(): - return {"x": 0, "y": 0, "width": 200, "height": 100} - def test_user_name_attribute_becomes_a_slot(): payload = { "title": "Profiles", "model": { + "version": "4.0.0", "type": "UserDiagram", - "elements": { - "u-user": { - "id": "u-user", "name": "user_1", "type": "UserModelName", "owner": None, - "bounds": _box(), "attributes": ["a-name"], "methods": [], "className": "User", - }, - "a-name": { - "id": "a-name", "name": "name = Alice", "type": "UserModelAttribute", - "owner": "u-user", "bounds": _box(), "attributeOperator": "==", + "nodes": [{ + "id": "u-user", "type": "UserModelName", "position": {"x": 0, "y": 0}, + "width": 200, "height": 100, + "data": { + "name": "user_1", "className": "User", "methods": [], + "attributes": [{"id": "a-name", "name": "name = Alice", "attributeOperator": "=="}], }, - }, - "relationships": {}, + }], + "edges": [], }, } diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_v4_roundtrip_fidelity.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_v4_roundtrip_fidelity.py new file mode 100644 index 000000000..b7d5ab64d --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_v4_roundtrip_fidelity.py @@ -0,0 +1,310 @@ +"""Round trips through the v4 converters keep what the editor saved. + +Each test records a loss or duplication found by round-tripping editor +templates and fixtures: JSON -> B-UML -> JSON, and project JSON -> project +``.py`` -> project JSON. +""" + +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.class_diagram_converter import ( + class_buml_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.class_diagram_processor import ( + process_class_diagram, +) + + +def _node(node_id, node_type, data): + return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, "data": data} + + +def _class_diagram(nodes, edges=()): + return {"title": "Library", "model": {"version": "4.0.0", "type": "ClassDiagram", + "nodes": list(nodes), "edges": list(edges)}} + + +def test_class_description_is_not_doubled_by_a_round_trip(): + diagram = _class_diagram([_node("book", "class", { + "name": "Book", "description": "A printed work", "attributes": [], "methods": [], + })]) + for _ in range(2): + exported = class_buml_to_json(process_class_diagram(diagram)) + diagram = {"title": "Library", "model": exported} + # Where the class inspector reads it, and nowhere else. + [book] = [n for n in exported["nodes"] if n["type"] == "class"] + assert book["data"].get("description") == "A printed work" + assert not [n for n in exported["nodes"] if n["type"] == "comment"] + model = process_class_diagram(diagram) + assert model.get_class_by_name("Book").metadata.description == "A printed work" + + +def test_method_contracts_are_not_duplicated_by_a_buml_file_round_trip(tmp_path): + from besser.utilities.buml_code_builder.domain_model_builder import domain_model_to_code + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.class_diagram_converter import ( + parse_buml_content, + ) + + renew = {"id": "renew", "name": "renew", "visibility": "public", "returnType": "any", + "parameters": [{"id": "p", "name": "days", "parameterType": "int"}]} + diagram = _class_diagram([ + _node("book", "class", {"name": "Book", "attributes": [], "methods": [renew]}), + _node("pre", "ClassOCLConstraint", + {"expression": "context Book::renew(days: int) pre: days > 0"}), + _node("inv", "ClassOCLConstraint", + {"expression": "context Book inv named: true"}), + ]) + model = process_class_diagram(diagram) + [method] = model.get_class_by_name("Book").methods + assert len(method.pre) == 1 and len(model.constraints) == 1 + + path = tmp_path / "model.py" + domain_model_to_code(model, str(path)) + reloaded = parse_buml_content(path.read_text(encoding="utf-8")) + assert {c.name for c in reloaded.constraints} == {"named"} + exported = class_buml_to_json(reloaded) + boxes = [n for n in exported["nodes"] if n["type"] == "ClassOCLConstraint"] + assert len(boxes) == 2 + + +def _fixture_model(name): + import json + from pathlib import Path + path = Path(__file__).resolve().parents[5] / "fixtures" / "v4" / f"{name}.json" + return json.loads(path.read_text(encoding="utf-8"))["model"] + + +def _project_round_trip(diagrams, tmp_path, description="Round trip", name="RoundTrip"): + import copy + from besser.utilities.buml_code_builder.project_builder import project_to_code + from besser.utilities.web_modeling_editor.backend.models.project import ProjectInput + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.project_converter import ( + project_to_json, + ) + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.project_converter import ( + json_to_buml_project, + ) + project = {"id": "p", "type": "Project", "name": name, "description": description, + "owner": "tester", "createdAt": "2026-01-01T00:00:00Z", + "diagrams": copy.deepcopy(diagrams)} + out = tmp_path / "project.py" + project_to_code(json_to_buml_project(ProjectInput(**project)), str(out)) + code = out.read_text(encoding="utf-8") + return code, project_to_json(code) + + +def test_several_diagrams_of_one_type_import_once_each(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + agent, sm, cd = (_fixture_model(n) for n in + ("agent_diagram_basic", "state_machine_basic", "class_diagram_basic")) + diagrams = { + "AgentDiagram": [{"id": "a1", "title": "AgentOne", "model": agent}, + {"id": "a2", "title": "AgentTwo", "model": agent}], + "StateMachineDiagram": [{"id": "s1", "title": "SmOne", "model": sm}, + {"id": "s2", "title": "SmTwo", "model": sm}], + "ClassDiagram": [{"id": "c1", "title": "LibA", "model": cd}, + {"id": "c2", "title": "LibB", "model": cd}], + } + _, imported = _project_round_trip(diagrams, tmp_path) + for diagram_type in diagrams: + entries = imported["diagrams"][diagram_type] + assert len(entries) == 2, (diagram_type, [e["title"] for e in entries]) + assert all(e["model"]["nodes"] for e in entries), diagram_type + + +def _cross_reference_project(): + """A component realizes a class and joins a BPMN process; an object + instantiates the same class by its node id.""" + bpmn = {"version": "4.0.0", "type": "BPMNDiagram", "edges": [ + {"id": "f1", "type": "BPMNSequenceFlow", "source": "s", "target": "e", + "data": {"name": "", "points": []}}, + ], "nodes": [ + _node("s", "bpmnStartEvent", {"name": "start", "eventType": "default"}), + _node("e", "bpmnEndEvent", {"name": "end", "eventType": "default"}), + ]} + component = {"version": "4.0.0", "type": "ComponentDiagram", "edges": [], "nodes": [ + _node("cmp", "component", {"name": "Catalogue", "isComponentHeaderShown": True, + "realizes": ["n-book"], "processModelRefs": ["bp-1"]}), + ]} + objects = {"version": "4.0.0", "type": "ObjectDiagram", "edges": [], "nodes": [ + _node("o1", "objectName", {"name": "dune", "classId": "n-book", "methods": [], + "attributes": []}), + ]} + return { + "ClassDiagram": [{"id": "cd-1", "title": "Library", + "model": _fixture_model("class_diagram_basic")}], + "ObjectDiagram": [{"id": "od-1", "title": "Shelf", "model": objects, + "references": {"ClassDiagram": "cd-1"}}], + "BPMN": [{"id": "bp-1", "title": "Lending", "model": bpmn}], + "ComponentDiagram": [{"id": "cmp-1", "title": "Services", "model": component}], + } + + +def test_project_import_keeps_diagram_and_class_ids(tmp_path, monkeypatch): + from besser.utilities.web_modeling_editor.backend.models.project import ProjectInput + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.project_converter import ( + json_to_buml_project, + ) + monkeypatch.chdir(tmp_path) + diagrams = _cross_reference_project() + _, imported = _project_round_trip(diagrams, tmp_path) + + for diagram_type, expected in (("ClassDiagram", "cd-1"), ("ObjectDiagram", "od-1"), + ("BPMN", "bp-1"), ("ComponentDiagram", "cmp-1")): + assert [d["id"] for d in imported["diagrams"][diagram_type]] == [expected], diagram_type + class_ids = {n["data"]["name"]: n["id"] + for n in imported["diagrams"]["ClassDiagram"][0]["model"]["nodes"] + if n["type"] == "class"} + assert class_ids["Book"] == "n-book" + [obj] = imported["diagrams"]["ObjectDiagram"][0]["model"]["nodes"] + assert obj["data"]["classId"] == "n-book" + + # The imported project exports again: its cross-diagram references resolve. + project = dict(imported, name="RoundTrip") + reexported = json_to_buml_project(ProjectInput(**project)) + assert reexported._cross_diagram_errors["errors"] == [] + + +def test_agent_default_llm_survives_a_project_round_trip(tmp_path, monkeypatch): + from besser.utilities.web_modeling_editor.backend.models.project import ProjectInput + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.project_converter import ( + json_to_buml_project, + ) + from tests.utilities.web_modeling_editor.backend.services.converters.test_agent_converter_multi_llm import ( + _multi_llm_payload, + ) + monkeypatch.chdir(tmp_path) + payload = _multi_llm_payload() + diagrams = {"AgentDiagram": [{"id": "ag-1", "title": "Helper", "model": payload["model"], + "config": payload["config"]}]} + _, imported = _project_round_trip(diagrams, tmp_path) + + [agent_entry] = imported["diagrams"]["AgentDiagram"] + # The editor reads the default LLM from the diagram's config envelope. + assert (agent_entry.get("config") or {}).get("default_llm_name") == "big" + agent = next(m for m in json_to_buml_project(ProjectInput(**dict(imported, name="RT"))).models + if type(m).__name__ == "Agent") + assert agent.default_llm_name == "big" + + +def test_agent_default_llm_is_read_from_the_model_config_too(): + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.agent_diagram_processor import ( + process_agent_diagram, + ) + from tests.utilities.web_modeling_editor.backend.services.converters.test_agent_converter_multi_llm import ( + _multi_llm_payload, + ) + payload = _multi_llm_payload() + payload["model"]["config"] = payload.pop("config") + assert process_agent_diagram(payload).default_llm_name == "big" + + +def test_nn_metrics_and_sub_nn_reference_use_the_editor_formats(): + from besser.BUML.metamodel.nn import NN, Configuration, LinearLayer + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.nn_diagram_converter import ( + nn_model_to_json, + ) + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( + process_nn_diagram, + ) + classifier = NN(name="classifier") + classifier.add_layer(LinearLayer(name="head", in_features=8, out_features=2)) + net = NN(name="net") + net.add_layer(LinearLayer(name="body", in_features=4, out_features=8)) + net.add_sub_nn(classifier) + net.add_configuration(Configuration( + batch_size=8, epochs=1, learning_rate=0.01, optimizer="adam", + loss_function="crossentropy", metrics=["f1-score", "accuracy"], + )) + + out = nn_model_to_json(net) + [config] = [n for n in out["nodes"] if n["type"] == "Configuration"] + # The editor's metrics multiselect parses the bare bracketed form. + assert config["data"]["attributes"]["metrics"] == "[f1-score, accuracy]" + [ref] = [n for n in out["nodes"] if n["type"] == "NNReference"] + container_ids = {n["data"]["name"]: n["id"] for n in out["nodes"] if n["type"] == "NNContainer"} + # referenceTarget is the referenced container's node id, as the editor stores it. + assert ref["data"]["referenceTarget"] == container_ids["classifier"] + + rebuilt = process_nn_diagram({"title": "net", "model": out}) + assert rebuilt.configuration.metrics == ["f1-score", "accuracy"] + assert [m.name for m in rebuilt.modules if isinstance(m, NN)] == ["classifier"] + + +def test_project_description_comes_from_the_project_definition(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + classes = _class_diagram([ + _node("book", "class", {"name": "Book", "attributes": [], "methods": []}), + _node("note", "comment", {"name": "A printed work"}), + ], [{"id": "l", "type": "CommentLink", "source": "note", "target": "book", "data": {"points": []}}]) + diagrams = {"ClassDiagram": [{"id": "cd-1", "title": "Library", "model": classes["model"]}]} + _, imported = _project_round_trip(diagrams, tmp_path, description='Lending "desk" app') + assert imported["description"] == 'Lending "desk" app' + + +def test_a_class_named_project_survives_a_buml_file_round_trip(tmp_path): + from besser.utilities.buml_code_builder.domain_model_builder import domain_model_to_code + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.class_diagram_converter import ( + parse_buml_content, + ) + diagram = _class_diagram([_node("p", "class", {"name": "Project", "methods": [], "attributes": [ + {"id": "a", "name": "title", "attributeType": "str", "visibility": "public"}, + ]})]) + path = tmp_path / "model.py" + domain_model_to_code(process_class_diagram(diagram), str(path)) + reloaded = parse_buml_content(path.read_text(encoding="utf-8")) + assert [a.name for a in reloaded.get_class_by_name("Project").attributes] == ["title"] + + +def test_a_project_name_with_spaces_exports_and_comes_back(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + classes = _class_diagram([_node("book", "class", {"name": "Book", "attributes": [], "methods": []})]) + diagrams = {"ClassDiagram": [{"id": "cd-1", "title": "Library", "model": classes["model"]}]} + code, imported = _project_round_trip(diagrams, tmp_path, name="My Library-App") + # B-UML names cannot hold spaces or hyphens; the editor's name rides alongside. + assert 'name="My_Library_App"' in code + assert imported["name"] == "My Library-App" + + +def test_diagram_titles_survive_a_project_round_trip(tmp_path, monkeypatch): + import copy + monkeypatch.chdir(tmp_path) + bpmn = _cross_reference_project()["BPMN"][0]["model"] + diagrams = { + "AgentDiagram": [{"id": "ag-1", "title": "Front desk bot", + "model": _fixture_model("agent_diagram_basic")}], + "BPMN": [{"id": "bp-1", "title": "Lending", "model": bpmn}, + {"id": "bp-2", "title": "Returns \u2014 late", "model": copy.deepcopy(bpmn)}], + } + _, imported = _project_round_trip(diagrams, tmp_path) + assert [d["title"] for d in imported["diagrams"]["AgentDiagram"]] == ["Front desk bot"] + assert [d["title"] for d in imported["diagrams"]["BPMN"]] == ["Lending", "Returns \u2014 late"] + + +def test_object_diagrams_import_against_their_referenced_class_diagram(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + + def classes(node_id, name, attr): + return _class_diagram([_node(node_id, "class", {"name": name, "methods": [], "attributes": [ + {"id": f"{node_id}-{attr}", "name": attr, "attributeType": "str", "visibility": "public"}]})])["model"] + + def objects(class_id, class_name, attr): + return {"version": "4.0.0", "type": "ObjectDiagram", "edges": [], "nodes": [ + _node(f"o-{class_id}", "objectName", { + "name": f"{class_name.lower()}1", "className": class_name, "classId": class_id, + "methods": [], "attributes": [ + {"id": "r", "name": attr, "attributeId": f"{class_id}-{attr}", "value": "v"}]})]} + + diagrams = { + "ClassDiagram": [{"id": "cd-a", "title": "Books", "model": classes("ca", "Book", "title")}, + {"id": "cd-b", "title": "Cars", "model": classes("cb", "Car", "plate")}], + # Listed in the opposite order, so neither can rely on the first class diagram. + "ObjectDiagram": [{"id": "od-b", "title": "Fleet", "model": objects("cb", "Car", "plate"), + "references": {"ClassDiagram": "cd-b"}}, + {"id": "od-a", "title": "Shelf", "model": objects("ca", "Book", "title"), + "references": {"ClassDiagram": "cd-a"}}], + } + _, imported = _project_round_trip(diagrams, tmp_path) + by_id = {d["id"]: d for d in imported["diagrams"]["ObjectDiagram"]} + for od_id, cd_id, class_id in (("od-b", "cd-b", "cb"), ("od-a", "cd-a", "ca")): + assert by_id[od_id].get("references") == {"ClassDiagram": cd_id} + assert [n["data"]["classId"] for n in by_id[od_id]["model"]["nodes"]] == [class_id] diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/utils_buml_to_json_tests.py b/tests/utilities/web_modeling_editor/backend/services/converters/utils_buml_to_json_tests.py index 39130f847..28f00bf4e 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/utils_buml_to_json_tests.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/utils_buml_to_json_tests.py @@ -1,17 +1,17 @@ -"""Helpers that read the editor JSON produced by the ``buml_to_json`` object converter.""" +"""Helpers that read the v4 editor JSON produced by the ``buml_to_json`` object converter.""" def object_names(result): - """Object names in the editor JSON, keyed by element id.""" - return {i: e["name"] for i, e in result["elements"].items() if e["type"] == "ObjectName"} + """Object names in the editor JSON, keyed by node id.""" + return {n["id"]: n["data"]["name"] for n in result["nodes"] if n["type"] == "objectName"} def object_attributes(result): """Attribute values in the editor JSON, as ``"object.attribute = value"`` strings.""" - names = object_names(result) return { - f"{names[e['owner']]}.{e['name']}" - for e in result["elements"].values() if e["type"] == "ObjectAttribute" + f"{n['data']['name']}.{row['name']} = {row['value']}" + for n in result["nodes"] if n["type"] == "objectName" + for row in n["data"]["attributes"] } @@ -19,6 +19,6 @@ def object_links(result): """Links in the editor JSON, as ``"source -role-> target"`` strings.""" names = object_names(result) return { - f"{names[r['source']['element']]} -{r['name']}-> {names[r['target']['element']]}" - for r in result["relationships"].values() if r["type"] == "ObjectLink" + f"{names[e['source']]} -{e['data']['name']}-> {names[e['target']]}" + for e in result["edges"] if e["type"] == "ObjectLink" } diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/utils_gui_binding_tests.py b/tests/utilities/web_modeling_editor/backend/services/converters/utils_gui_binding_tests.py index feb1d28e9..7cf9c57fd 100644 --- a/tests/utilities/web_modeling_editor/backend/services/converters/utils_gui_binding_tests.py +++ b/tests/utilities/web_modeling_editor/backend/services/converters/utils_gui_binding_tests.py @@ -6,27 +6,20 @@ def class_diagram(class_name, attributes): - """Apollon class diagram with one class (id ``cls-``) and its ``(name, type)`` - attributes (ids ``attr--``).""" - class_id = f"cls-{class_name}" - elements = {} - attribute_ids = [] - for attr_name, attr_type in attributes: - attr_id = f"attr-{class_name}-{attr_name}" - attribute_ids.append(attr_id) - elements[attr_id] = { - "id": attr_id, "name": attr_name, "type": "ClassAttribute", "owner": class_id, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 30}, "visibility": "public", - "attributeType": attr_type, "isOptional": False, "isDerived": False, "isId": False, - } - elements[class_id] = { - "id": class_id, "name": class_name, "type": "Class", "owner": None, - "bounds": {"x": 0, "y": 0, "width": 220, "height": 200}, - "attributes": attribute_ids, "methods": [], + """v4 class diagram with one class (node id ``cls-``) and its ``(name, type)`` + attributes (row ids ``attr--``).""" + rows = [ + {"id": f"attr-{class_name}-{attr_name}", "name": attr_name, "visibility": "public", + "attributeType": attr_type, "isOptional": False, "isDerived": False, "isId": False} + for attr_name, attr_type in attributes + ] + node = { + "id": f"cls-{class_name}", "type": "class", "position": {"x": 0, "y": 0}, + "width": 220, "height": 200, "measured": {"width": 220, "height": 200}, + "data": {"name": class_name, "attributes": rows, "methods": []}, } - return {"version": "3.0.0", "type": "ClassDiagram", "size": {"width": 2000, "height": 1000}, - "interactive": {"elements": {}, "relationships": {}}, "elements": elements, - "relationships": {}, "assessments": {}} + return {"version": "4.0.0", "type": "ClassDiagram", "title": "Domain", + "nodes": [node], "edges": [], "assessments": {}} def import_gui(components, class_json): diff --git a/tests/utilities/web_modeling_editor/backend/services/generation/test_dispatch.py b/tests/utilities/web_modeling_editor/backend/services/generation/test_dispatch.py index 019fce40a..61ab057b3 100644 --- a/tests/utilities/web_modeling_editor/backend/services/generation/test_dispatch.py +++ b/tests/utilities/web_modeling_editor/backend/services/generation/test_dispatch.py @@ -29,12 +29,17 @@ ) CLASS_MODEL = { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": {"type": "Class", "name": "Book", "attributes": ["attr-1"], "methods": []}, - "attr-1": {"type": "Attribute", "name": "+ title: str"}, - }, - "relationships": {}, + "nodes": [{ + "id": "class-1", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": { + "name": "Book", + "attributes": [{"id": "attr-1", "name": "title", "attributeType": "str", "visibility": "public"}], + "methods": [], + }, + }], + "edges": [], } diff --git a/tests/utilities/web_modeling_editor/backend/services/governance/test_swarm_bindings.py b/tests/utilities/web_modeling_editor/backend/services/governance/test_swarm_bindings.py index 5c2dffad9..29d5a3fda 100644 --- a/tests/utilities/web_modeling_editor/backend/services/governance/test_swarm_bindings.py +++ b/tests/utilities/web_modeling_editor/backend/services/governance/test_swarm_bindings.py @@ -53,34 +53,51 @@ def __init__(self, name): GW = "gw1" +def _node(node_id, node_type, parent_id, **data): + """A v4 BPMN node; ``parent_id`` is the containing pool / lane.""" + node = {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, + "width": 100, "height": 60, "data": {"name": node_id, **data}} + if parent_id is not None: + node["parentId"] = parent_id + return node + + def _lane(lane_id, ref=None): - lane = {"id": lane_id, "name": lane_id, "type": "BPMNSwimlane", "owner": "pool"} + data = {} if ref is not None: - lane.update(isAgentic=True, role="solution", agentDiagramRef=ref) - return lane + data.update(isAgentic=True, role="solution", agentDiagramRef=ref) + return _node(lane_id, "bpmnSwimlane", "pool", **data) def _task(task_id, owner): - return {"id": task_id, "name": task_id, "type": "BPMNTask", "owner": owner} + return _node(task_id, "bpmnTask", owner) + + +def _start(start_id, owner): + return _node(start_id, "bpmnStartEvent", owner, name="") def _gateway(gateway_id, owner, governance=GOV): - return {"id": gateway_id, "name": gateway_id, "type": "BPMNGateway", "owner": owner, - "gatewayType": "parallel", "isAgentic": True, "gatewayRole": "merging", - "governanceDsl": governance} + return _node(gateway_id, "bpmnGateway", owner, gatewayType="parallel", isAgentic=True, + gatewayRole="merging", governanceDsl=governance) + + +_FLOW_EDGE_TYPES = {"sequence": "BPMNSequenceFlow", "message": "BPMNMessageFlow"} def _flow(flow_id, source, target, flow_type="sequence"): - return {"id": flow_id, "name": "", "type": "BPMNFlow", "flowType": flow_type, - "source": {"element": source}, "target": {"element": target}} + return {"id": flow_id, "type": _FLOW_EDGE_TYPES[flow_type], "source": source, + "target": target, "sourceHandle": "right", "targetHandle": "left", + "data": {"name": "", "points": []}} def _model(elements: list, flows: list): - pool = {"id": "pool", "name": "Swarm", "type": "BPMNPool", "owner": None} + pool = _node("pool", "bpmnPool", None, name="Swarm") payload = {"title": "Swarm", "model": { + "version": "4.0.0", "type": "BPMNDiagram", - "elements": {e["id"]: e for e in [pool] + elements}, - "relationships": {f["id"]: f for f in flows}, + "nodes": [pool] + elements, + "edges": flows, }} return process_bpmn_diagram(payload) @@ -206,7 +223,7 @@ def test_producer_edge_into_a_governed_gateway_is_tagged(): def test_start_event_lane_is_human_facing_even_when_it_owns_a_merge(): model = _model( [_lane("laneC", "refC"), _lane("laneR", "refR"), _task("taskC", "laneC"), - {"id": "start", "name": "", "type": "BPMNStartEvent", "owner": "laneR"}, + _start("start", "laneR"), _gateway(GW, "laneR")], [_flow("f1", "taskC", GW)], ) @@ -219,7 +236,7 @@ def test_start_event_lane_is_human_facing_even_when_it_owns_a_merge(): def test_start_event_outside_lanes_marks_the_lane_it_starts(): model = _model( [_lane("laneR", "refR"), _task("taskR", "laneR"), - {"id": "start", "name": "", "type": "BPMNStartEvent", "owner": "pool"}], + _start("start", "pool")], [_flow("f1", "start", "taskR")], ) agents = _agents() diff --git a/tests/utilities/web_modeling_editor/backend/services/utils/test_gui_personalization.py b/tests/utilities/web_modeling_editor/backend/services/utils/test_gui_personalization.py index 975aee5fb..ce3ea3086 100644 --- a/tests/utilities/web_modeling_editor/backend/services/utils/test_gui_personalization.py +++ b/tests/utilities/web_modeling_editor/backend/services/utils/test_gui_personalization.py @@ -22,7 +22,7 @@ MODULE = "besser.utilities.web_modeling_editor.backend.services.utils.gui_personalization_utils" _PAGE = {"components": [{"type": "text", "content": "Hello"}], "css": []} -_PROFILE = {"type": "UserDiagram", "elements": {}, "relationships": {}} +_PROFILE = {"version": "4.0.0", "type": "UserDiagram", "nodes": [], "edges": []} def _mock_llm(return_value=None, side_effect=None): diff --git a/tests/utilities/web_modeling_editor/backend/services/utils/test_reinject_hidden_containers.py b/tests/utilities/web_modeling_editor/backend/services/utils/test_reinject_hidden_containers.py index e411b01e4..ffc24ef76 100644 --- a/tests/utilities/web_modeling_editor/backend/services/utils/test_reinject_hidden_containers.py +++ b/tests/utilities/web_modeling_editor/backend/services/utils/test_reinject_hidden_containers.py @@ -10,28 +10,25 @@ ) -def _box(): - return {"x": 0, "y": 0, "width": 200, "height": 100} - - def _name_box(box_id, name, class_name): - return {"id": box_id, "name": name, "type": "UserModelName", "owner": None, "bounds": _box(), - "attributes": [], "methods": [], "className": class_name} + return {"id": box_id, "type": "UserModelName", "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": {"name": name, "attributes": [], "methods": [], "className": class_name}} def _link(link_id, source, target): - return {"id": link_id, "name": "", "type": "ObjectLink", "owner": None, "bounds": _box(), - "source": {"element": source, "direction": "Right"}, "target": {"element": target, "direction": "Left"}} + return {"id": link_id, "type": "UserModelLink", "source": source, "target": target, + "sourceHandle": "right", "targetHandle": "left", "data": {"name": "", "points": []}} def _two_profiles(): return {"model": { + "version": "4.0.0", "type": "UserDiagram", - "elements": { - "u1": _name_box("u1", "user_1", "User"), "u2": _name_box("u2", "user_2", "User"), - "d1": _name_box("d1", "blind", "Disability"), "d2": _name_box("d2", "deaf", "Disability"), - }, - "relationships": {"l1": _link("l1", "u1", "d1"), "l2": _link("l2", "u2", "d2")}, + "nodes": [ + _name_box("u1", "user_1", "User"), _name_box("u2", "user_2", "User"), + _name_box("d1", "blind", "Disability"), _name_box("d2", "deaf", "Disability"), + ], + "edges": [_link("l1", "u1", "d1"), _link("l2", "u2", "d2")], }} @@ -45,27 +42,27 @@ def test_routes_come_from_the_reference_metamodel(): def test_each_profile_gets_its_own_container_with_a_unique_name(): model = reinject_hidden_containers(_two_profiles())["model"] - containers = [el for el in model["elements"].values() if el["className"] == "Accessibility"] - assert sorted(el["name"] for el in containers) == ["accessibility_1", "accessibility_2"] + containers = [node["data"] for node in model["nodes"] if node["data"]["className"] == "Accessibility"] + assert sorted(data["name"] for data in containers) == ["accessibility_1", "accessibility_2"] def test_container_names_skip_names_already_in_use(): payload = _two_profiles() - payload["model"]["elements"]["x"] = _name_box("x", "accessibility_1", "Accessibility") + payload["model"]["nodes"].append(_name_box("x", "accessibility_1", "Accessibility")) model = reinject_hidden_containers(payload)["model"] - injected = [el["name"] for eid, el in model["elements"].items() if eid.startswith("reinject_")] + injected = [node["data"]["name"] for node in model["nodes"] if node["id"].startswith("reinject_")] assert sorted(injected) == ["accessibility_2", "accessibility_3"] def test_profiles_do_not_leak_into_each_other(): reinjected = reinject_hidden_containers(_two_profiles()) model = reinjected["model"] - class_of = {eid: el["className"] for eid, el in model["elements"].items()} + data_of = {node["id"]: node["data"] for node in model["nodes"]} children_of: dict[str, set[str]] = {} - for rel in model["relationships"].values(): - source, target = rel["source"]["element"], rel["target"]["element"] - if class_of.get(source) == "Accessibility": - children_of.setdefault(source, set()).add(model["elements"][target]["name"]) + for edge in model["edges"]: + source, target = edge["source"], edge["target"] + if data_of[source]["className"] == "Accessibility": + children_of.setdefault(source, set()).add(data_of[target]["name"]) assert sorted(map(sorted, children_of.values())) == [["blind"], ["deaf"]] # The object model keeps one object per name, so nothing is merged across profiles. diff --git a/tests/utilities/web_modeling_editor/backend/services/utils/test_user_profile_comparators.py b/tests/utilities/web_modeling_editor/backend/services/utils/test_user_profile_comparators.py index bfe467b4f..727994131 100644 --- a/tests/utilities/web_modeling_editor/backend/services/utils/test_user_profile_comparators.py +++ b/tests/utilities/web_modeling_editor/backend/services/utils/test_user_profile_comparators.py @@ -17,17 +17,22 @@ ) -def _senior_diagram(criterion: str, operator: str) -> dict: - """A User linked to a Personal_Information box carrying one criterion, as the editor saves it.""" - return {"id": "d", "title": "Senior", "type": "UserDiagram", "model": {"type": "UserDiagram", "elements": { - "u": {"id": "u", "name": "user", "type": "UserModelName", "className": "User", "attributes": [], - "bounds": {"x": 0, "y": 0, "width": 200, "height": 60}}, - "p": {"id": "p", "name": "info", "type": "UserModelName", "className": "Personal_Information", - "attributes": ["a"], "bounds": {"x": 300, "y": 0, "width": 200, "height": 60}}, - "a": {"id": "a", "name": criterion, "type": "UserModelAttribute", "owner": "p", - "attributeOperator": operator, "bounds": {"x": 300, "y": 30, "width": 200, "height": 30}}, - }, "relationships": {"l": {"id": "l", "type": "ObjectLink", "name": "", - "source": {"element": "u"}, "target": {"element": "p"}}}}} +def _senior_diagram(criterion: str, operator: str, value=None) -> dict: + """A User linked to a Personal_Information box carrying one criterion, as the editor saves it. + + ``value=None`` keeps the comparator embedded in the row name ("age > 65", as + migrated projects and templates carry it); otherwise the row has a bare name + plus a separate ``value``, as the v4 editor writes it. + """ + row = {"id": "a", "name": criterion, "attributeOperator": operator} + if value is not None: + row["value"] = value + return {"id": "d", "title": "Senior", "type": "UserDiagram", "model": {"type": "UserDiagram", "nodes": [ + {"id": "u", "type": "UserModelName", "position": {"x": 0, "y": 0}, "width": 200, "height": 60, + "data": {"name": "user", "className": "User", "attributes": []}}, + {"id": "p", "type": "UserModelName", "position": {"x": 300, "y": 0}, "width": 200, "height": 60, + "data": {"name": "info", "className": "Personal_Information", "attributes": [row]}}, + ], "edges": [{"id": "l", "type": "UserModelLink", "source": "u", "target": "p", "data": {"name": ""}}]}} @pytest.mark.parametrize("criterion, operator, expected", [ @@ -43,6 +48,25 @@ def test_profile_document_keeps_the_comparator(criterion, operator, expected): assert document["model"]["Personal_Information"]["age"] == expected +@pytest.mark.parametrize("operator, value, expected", [ + (">", "65", "> 65"), + ("<", "18", "< 18"), + ("==", "30", 30), +]) +def test_profile_document_keeps_the_comparator_of_a_split_row(operator, value, expected): + document = generate_user_profile_document(_senior_diagram("age", operator, value)) + assert document["model"]["Personal_Information"]["age"] == expected + + +def test_bare_v4_model_as_the_editor_sends_it(): + """The editor sends the profile's bare model, which in v4 carries its own + hyphenated ``id`` and an empty ``title``; neither may become the object model name.""" + model = {**_senior_diagram("age < 18", "<")["model"], "id": "converted-diagram-1781220606361", "title": ""} + document = generate_user_profile_document(model) + assert document["name"] == "UserProfile" + assert document["model"]["Personal_Information"]["age"] == "< 18" + + def test_generated_agent_shows_the_comparator(tmp_path): profile = generate_user_profile_document(_senior_diagram("age > 65", ">")) config = {"personalizationMapping": [{"name": "Senior", "configuration": {}, "user_profile": profile}]} diff --git a/tests/utilities/web_modeling_editor/backend/services/utils/test_user_profile_utils.py b/tests/utilities/web_modeling_editor/backend/services/utils/test_user_profile_utils.py index 073e4b011..b1b14137a 100644 --- a/tests/utilities/web_modeling_editor/backend/services/utils/test_user_profile_utils.py +++ b/tests/utilities/web_modeling_editor/backend/services/utils/test_user_profile_utils.py @@ -148,17 +148,20 @@ def _sample_object_document(): def test_profile_rules_are_scoped_per_user_and_include_shared_boxes(): def box(identifier, class_name, rules): - return {'id': identifier, 'name': identifier, 'type': 'UserModelName', 'className': class_name, - 'attributes': [], 'personalization': rules} - - model = {'elements': { - 'alice': box('alice', 'User', {'presentation': {'language': 'english'}}), - 'bob': box('bob', 'User', {'presentation': {'language': 'french'}}), - 'shared': box('shared', 'Culture', {'gui': {'modality': {'readAloud': True}}}), - }, 'relationships': { - 'a': {'source': {'element': 'alice'}, 'target': {'element': 'shared'}}, - 'b': {'source': {'element': 'bob'}, 'target': {'element': 'shared'}}, - }} + return {'id': identifier, 'type': 'UserModelName', 'position': {'x': 0, 'y': 0}, + 'width': 200, 'height': 100, + 'data': {'name': identifier, 'className': class_name, 'attributes': [], + 'personalization': rules}} + + def link(identifier, source, target): + return {'id': identifier, 'type': 'UserModelLink', 'source': source, 'target': target, + 'data': {'points': []}} + + model = {'version': '4.0.0', 'type': 'UserDiagram', 'nodes': [ + box('alice', 'User', {'presentation': {'language': 'english'}}), + box('bob', 'User', {'presentation': {'language': 'french'}}), + box('shared', 'Culture', {'gui': {'modality': {'readAloud': True}}}), + ], 'edges': [link('a', 'alice', 'shared'), link('b', 'bob', 'shared')]} result = user_profile_utils.extract_profile_personalization_rules({'model': model}) assert {entry['elementId'] for entry in result['alice']} == {'alice', 'shared'} assert {entry['elementId'] for entry in result['bob']} == {'bob', 'shared'} diff --git a/tests/utilities/web_modeling_editor/backend/services/validators/alloy/test_semantic_consistency.py b/tests/utilities/web_modeling_editor/backend/services/validators/alloy/test_semantic_consistency.py index 5becef3ac..8fe65c2cc 100644 --- a/tests/utilities/web_modeling_editor/backend/services/validators/alloy/test_semantic_consistency.py +++ b/tests/utilities/web_modeling_editor/backend/services/validators/alloy/test_semantic_consistency.py @@ -23,21 +23,21 @@ def _book_diagram(invariant: str) -> DiagramInput: """A class diagram with ``Book(title: str, pages: int)`` and the OCL invariant *invariant* on ``Book``.""" return DiagramInput(title="Books", model={ + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "cls-book": {"id": "cls-book", "type": "Class", "name": "Book", "attributes": ["attr-title", "attr-pages"], - "methods": []}, - "attr-title": {"id": "attr-title", "type": "ClassAttribute", "name": "title", "visibility": "public", - "attributeType": "str"}, - "attr-pages": {"id": "attr-pages", "type": "ClassAttribute", "name": "pages", "visibility": "public", - "attributeType": "int"}, - "ocl-pages": {"id": "ocl-pages", "type": "ClassOCLConstraint", - "constraint": f"context Book inv pages: {invariant}"}, - }, - "relationships": { - "r-pages": {"id": "r-pages", "type": "ClassOCLLink", - "source": {"element": "ocl-pages"}, "target": {"element": "cls-book"}}, - }, + "nodes": [ + {"id": "cls-book", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Book", "methods": [], "attributes": [ + {"id": "attr-title", "name": "title", "visibility": "public", "attributeType": "str"}, + {"id": "attr-pages", "name": "pages", "visibility": "public", "attributeType": "int"}, + ]}}, + {"id": "ocl-pages", "type": "ClassOCLConstraint", "position": {"x": 200, "y": 0}, "width": 200, + "height": 80, "data": {"name": "", "expression": f"context Book inv pages: {invariant}"}}, + ], + "edges": [ + {"id": "r-pages", "type": "ClassOCLLink", "source": "ocl-pages", "target": "cls-book", + "data": {"points": []}}, + ], }) @@ -70,7 +70,7 @@ def invalid_ocl_diagram() -> DiagramInput: @pytest.fixture def state_machine_diagram() -> DiagramInput: - return DiagramInput(title="Machine", model={"type": "StateMachineDiagram", "elements": {}, "relationships": {}}) + return DiagramInput(title="Machine", model={"version": "4.0.0", "type": "StateMachineDiagram", "nodes": [], "edges": []}) @pytest.fixture @@ -172,7 +172,7 @@ def test_heartbeats_while_the_analyzer_runs(monkeypatch, contradictory_diagram, def test_object_diagram_of_a_consistent_diagram(consistent_diagram, slots): events = _events(generate_object_diagram(consistent_diagram, slots=slots)) object_diagram = events[-1]["object_model"] - names = [element["name"] for element in object_diagram["elements"].values() if element["type"] == "ObjectName"] + names = [node["data"]["name"] for node in object_diagram["nodes"] if node["type"] == "objectName"] assert events[-1]["isValid"] is True assert "Book_0" in names # Alloy numbers the atoms of a signature from 0 @@ -180,12 +180,13 @@ def test_object_diagram_of_a_consistent_diagram(consistent_diagram, slots): @needs_alloy def test_object_diagram_of_a_class_named_class(consistent_diagram, slots): """Class is the editor's default class name; its objects used to be dropped silently.""" - consistent_diagram.model["elements"]["cls-book"]["name"] = "Class" - consistent_diagram.model["elements"]["ocl-pages"]["constraint"] = "context Class inv pages: self.pages > 0" + book, constraint = consistent_diagram.model["nodes"] + book["data"]["name"] = "Class" + constraint["data"]["expression"] = "context Class inv pages: self.pages > 0" events = _events(generate_object_diagram(consistent_diagram, slots=slots)) - elements = events[-1]["object_model"]["elements"].values() + nodes = events[-1]["object_model"]["nodes"] assert events[-1]["isValid"] is True - assert "Class_0" in [element["name"] for element in elements if element["type"] == "ObjectName"] + assert "Class_0" in [node["data"]["name"] for node in nodes if node["type"] == "objectName"] @needs_alloy diff --git a/tests/utilities/web_modeling_editor/backend/smoke_all_generators.py b/tests/utilities/web_modeling_editor/backend/smoke_all_generators.py new file mode 100644 index 000000000..6a2926e09 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/smoke_all_generators.py @@ -0,0 +1,528 @@ +"""All-generators smoke test (A2 wave). + +Iterates over every entry in the backend's generator registry and exercises +``generate(model, output_dir)`` on a representative v4 fixture. For each +generator the script prints PASS/FAIL/SKIP plus output sizing. + +This is **not** a pytest. Run directly: + + python tests/utilities/web_modeling_editor/backend/smoke_all_generators.py + +Exits 0 if no PASS=>FAIL regressions were observed (FAILs are still printed, +but the goal of this script is to surface the matrix, not to gate CI). +""" + +from __future__ import annotations + +import ast +import json +import os +import sys +import tempfile +import traceback +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional + +REPO_ROOT = Path(__file__).resolve().parents[4] +sys.path.insert(0, str(REPO_ROOT)) + +# Import the FastAPI app first to trigger the full router/service init in the +# canonical order. Importing ``config.generators`` first leads to a circular +# import via deployment/github_deploy_api -> config. +from besser.utilities.web_modeling_editor.backend.backend import app # noqa: E402,F401 +from besser.utilities.web_modeling_editor.backend.config.generators import ( # noqa: E402 + SUPPORTED_GENERATORS, + GeneratorInfo, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.class_diagram_processor import ( # noqa: E402 + process_class_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.gui_diagram_processor import ( # noqa: E402 + process_gui_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.agent_diagram_processor import ( # noqa: E402 + process_agent_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.object_diagram_processor import ( # noqa: E402 + process_object_diagram, +) + + +FIXTURES_DIR = REPO_ROOT / "tests" / "fixtures" / "v4" +CLASS_FIXTURE = FIXTURES_DIR / "class_diagram_basic.json" +WEBAPP_FIXTURE = FIXTURES_DIR / "webapp_smoke_project.json" +AGENT_FIXTURE = FIXTURES_DIR / "agent_diagram_basic.json" +OBJECT_FIXTURE = FIXTURES_DIR / "object_diagram_basic.json" + + +@dataclass +class SmokeResult: + name: str + required: str + status: str # "PASS", "FAIL", "SKIP" + output_size: int = 0 + file_count: int = 0 + notes: str = "" + detail: str = field(default="", repr=False) + + +# --------------------------------------------------------------------------- +# Fixture loading helpers +# --------------------------------------------------------------------------- + + +def _load_json(path: Path) -> dict: + with path.open("r", encoding="utf-8") as fh: + return json.load(fh) + + +def load_class_model(): + payload = _load_json(CLASS_FIXTURE) + return process_class_diagram(payload) + + +def load_webapp_models(): + """Returns (domain_model, gui_model) from the webapp project fixture.""" + raw = _load_json(WEBAPP_FIXTURE) + class_diag = raw["diagrams"]["ClassDiagram"][0] + gui_diag = raw["diagrams"]["GUINoCodeDiagram"][0] + domain = process_class_diagram(class_diag) + gui = process_gui_diagram(gui_diag["model"], class_diag["model"], domain) + return domain, gui + + +def load_agent_model(): + payload = _load_json(AGENT_FIXTURE) + return process_agent_diagram(payload) + + +def load_object_model(): + """Build a small ObjectModel from the v4 object diagram fixture.""" + payload = _load_json(OBJECT_FIXTURE) + # The processor needs an explicit reference DomainModel built from the + # embedded referenceDiagramData (mirrors the router's behavior). + ref = payload["model"].get("referenceDiagramData") or {} + ref_payload = {"title": payload.get("title", "Ref"), "model": ref} + domain = process_class_diagram(ref_payload) + obj_payload = {"title": payload.get("title"), "model": payload["model"]} + return process_object_diagram(obj_payload, domain) + + +def build_minimal_quantum_circuit(): + """Construct a tiny QuantumCircuit programmatically (one H + measure).""" + from besser.BUML.metamodel.quantum.quantum import ( + QuantumCircuit, + HadamardGate, + Measurement, + ClassicalRegister, + ) + + qc = QuantumCircuit(name="SmokeCircuit", qubits=1) + qc.add_creg(ClassicalRegister("c", 1)) + qc.add_operation(HadamardGate(target_qubit=0)) + qc.add_operation(Measurement(target_qubit=0, output_bit=0)) + return qc + + +def build_minimal_nn_model(): + """Build an NNModel with a tiny MLP for the NN generators.""" + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( + process_nn_diagram, + ) + + payload = _load_json(FIXTURES_DIR / "nn_diagram_basic.json") + return process_nn_diagram(payload) + + +def build_minimal_deployment_model(): + """Construct a DeploymentModel for Terraform. + + This is heavy: Terraform expects PublicCluster instances with a + ``config_file`` it can read. Without one, we mark Terraform SKIP because + the smoke harness has no CI fixture for it. + """ + raise RuntimeError("Terraform deployment fixture not provided") + + +# --------------------------------------------------------------------------- +# Generator runners — each returns (success, notes, detail) +# --------------------------------------------------------------------------- + + +def _walk_files(root: str) -> List[str]: + out: List[str] = [] + for dirpath, _dirs, files in os.walk(root): + for name in files: + out.append(os.path.join(dirpath, name)) + return out + + +def _python_parse_ok(out_dir: str) -> tuple[int, int]: + py_files = [p for p in _walk_files(out_dir) if p.endswith(".py")] + ok = 0 + for path in py_files: + try: + with open(path, "r", encoding="utf-8") as fh: + ast.parse(fh.read(), filename=path) + ok += 1 + except SyntaxError: + pass + return ok, len(py_files) + + +def _output_stats(out_dir: str) -> tuple[int, int]: + files = _walk_files(out_dir) + total = sum(os.path.getsize(p) for p in files if os.path.isfile(p)) + return total, len(files) + + +def run_class_based(name: str, info: GeneratorInfo, domain_model) -> SmokeResult: + cls = info.generator_class + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmp: + try: + kwargs: Dict[str, Any] = {"output_dir": tmp} + if name == "django": + # Django generator shells out to ``django-admin``. If the CLI + # is not installed in the runner's PATH the generator can + # never produce output — surface this as SKIP rather than a + # bogus FAIL. + import shutil as _sh + if not _sh.which("django-admin"): + return SmokeResult( + name, info.category, "SKIP", 0, 0, + "django-admin CLI not installed", + ) + inst = cls( + model=domain_model, + project_name="smoke_proj", + app_name="smoke_app", + output_dir=tmp, + ) + # Django shells out to django-admin and uses CWD; chdir. + cwd = os.getcwd() + try: + os.chdir(tmp) + inst.generate() + finally: + os.chdir(cwd) + else: + inst = cls(domain_model, **kwargs) + inst.generate() + size, count = _output_stats(tmp) + if count == 0: + return SmokeResult(name, info.category, "FAIL", size, count, "empty output") + ok, total_py = _python_parse_ok(tmp) + note = f"py={ok}/{total_py}" if total_py else "no .py files" + return SmokeResult(name, info.category, "PASS", size, count, note) + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, + info.category, + "FAIL", + 0, + 0, + f"{type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + +def run_webapp(name: str, info: GeneratorInfo) -> SmokeResult: + domain, gui = load_webapp_models() + cls = info.generator_class + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmp: + try: + cls(model=domain, gui_model=gui, output_dir=tmp).generate() + size, count = _output_stats(tmp) + if count == 0: + return SmokeResult(name, info.category, "FAIL", size, count, "empty output") + ok, total_py = _python_parse_ok(tmp) + return SmokeResult( + name, + info.category, + "PASS", + size, + count, + f"py={ok}/{total_py}", + ) + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, + info.category, + "FAIL", + 0, + 0, + f"{type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + +def run_react(name: str, info: GeneratorInfo) -> SmokeResult: + domain, gui = load_webapp_models() + cls = info.generator_class + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmp: + try: + cls(domain, gui, output_dir=tmp).generate() + size, count = _output_stats(tmp) + return SmokeResult(name, info.category, "PASS" if count else "FAIL", + size, count, "" if count else "empty output") + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, + info.category, + "FAIL", + 0, + 0, + f"{type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + +def run_flutter(name: str, info: GeneratorInfo) -> SmokeResult: + # FlutterGenerator(model, gui_model, main_page, module=None, output_dir). + # Use the webapp fixture's GUI model and the first screen as the main page. + cls = info.generator_class + try: + domain, gui = load_webapp_models() + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"webapp fixture parse failed: {type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + modules = list(getattr(gui, "modules", []) or []) + main_module = modules[0] if modules else None + screens = [] + for mod in modules: + screens.extend(getattr(mod, "screens", []) or []) + if not screens: + return SmokeResult(name, info.category, "FAIL", 0, 0, + "no GUI screens parsed from fixture") + main_page = screens[0] + + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmp: + try: + cls(model=domain, gui_model=gui, main_page=main_page, + module=main_module, output_dir=tmp).generate() + size, count = _output_stats(tmp) + return SmokeResult(name, info.category, "PASS" if count else "FAIL", + size, count, "" if count else "empty output") + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, + info.category, + "FAIL", + 0, + 0, + f"{type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + +def run_agent(name: str, info: GeneratorInfo) -> SmokeResult: + cls = info.generator_class + try: + agent_model = load_agent_model() + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"agent fixture parse failed: {type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmp: + try: + cls(agent_model, output_dir=tmp).generate() + size, count = _output_stats(tmp) + ok, total_py = _python_parse_ok(tmp) + return SmokeResult( + name, info.category, + "PASS" if count else "FAIL", + size, count, + f"py={ok}/{total_py}" if total_py else ("" if count else "empty output"), + ) + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"{type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + +def run_qiskit(name: str, info: GeneratorInfo) -> SmokeResult: + cls = info.generator_class + try: + qc = build_minimal_quantum_circuit() + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"quantum fixture build failed: {type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmp: + try: + cls(qc, output_dir=tmp).generate() + size, count = _output_stats(tmp) + ok, total_py = _python_parse_ok(tmp) + return SmokeResult( + name, info.category, + "PASS" if count and ok > 0 else "FAIL", + size, count, + f"py={ok}/{total_py}", + ) + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"{type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + +def run_jsonobject(name: str, info: GeneratorInfo) -> SmokeResult: + cls = info.generator_class + try: + obj_model = load_object_model() + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"object fixture parse failed: {type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmp: + try: + cls(obj_model, output_dir=tmp).generate() + size, count = _output_stats(tmp) + return SmokeResult(name, info.category, "PASS" if count else "FAIL", + size, count, "" if count else "empty output") + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"{type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + +def run_nn(name: str, info: GeneratorInfo) -> SmokeResult: + cls = info.generator_class + if cls is None: + return SmokeResult(name, info.category, "SKIP", 0, 0, "dependency not installed") + try: + nn_model = build_minimal_nn_model() + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"NN fixture build failed: {type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmp: + try: + cls(nn_model, output_dir=tmp).generate() + size, count = _output_stats(tmp) + ok, total_py = _python_parse_ok(tmp) + return SmokeResult( + name, info.category, + "PASS" if count else "FAIL", + size, count, + f"py={ok}/{total_py}", + ) + except Exception as exc: # noqa: BLE001 + return SmokeResult( + name, info.category, "FAIL", 0, 0, + f"{type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + + +def run_terraform(name: str, info: GeneratorInfo) -> SmokeResult: + return SmokeResult( + name, info.category, "SKIP", 0, 0, + "no v4 deployment fixture (DeploymentModel + .conf required)", + ) + + +# --------------------------------------------------------------------------- +# Dispatch +# --------------------------------------------------------------------------- + + +# Map generator name -> runner function. Default runner is class-based. +RUNNERS: Dict[str, Callable[[str, GeneratorInfo], SmokeResult]] = { + "web_app": run_webapp, + "react": run_react, + "flutter": run_flutter, + "agent": run_agent, + "qiskit": run_qiskit, + "jsonobject": run_jsonobject, + "pytorch": run_nn, + "tensorflow": run_nn, + "terraform": run_terraform, +} + + +def main() -> int: + print(f"[smoke] registry contains {len(SUPPORTED_GENERATORS)} generators") + + # Lazy-load class-based domain model once. + domain_model: Optional[Any] = None + try: + domain_model = load_class_model() + except Exception as exc: # noqa: BLE001 + print(f"[smoke] FATAL: failed to load class fixture: {exc!r}", file=sys.stderr) + return 2 + + results: List[SmokeResult] = [] + + for gen_name, info in SUPPORTED_GENERATORS.items(): + runner = RUNNERS.get(gen_name) + try: + if runner is not None: + res = runner(gen_name, info) + else: + # Default: class-diagram-based generator. + res = run_class_based(gen_name, info, domain_model) + except Exception as exc: # noqa: BLE001 + res = SmokeResult( + gen_name, + info.category, + "FAIL", + 0, + 0, + f"runner crash: {type(exc).__name__}: {exc}", + detail=traceback.format_exc(), + ) + results.append(res) + print( + f"[smoke] {res.status:5s} {gen_name:14s} cat={info.category:18s} " + f"size={res.output_size:>9d}B files={res.file_count:>4d} {res.notes}" + ) + if res.status == "FAIL" and res.detail: + for line in res.detail.splitlines()[-3:]: + print(f"[smoke] | {line}") + + # ----- summary ----- + counts = {"PASS": 0, "FAIL": 0, "SKIP": 0} + for r in results: + counts[r.status] = counts.get(r.status, 0) + 1 + print("") + print(f"[smoke] SUMMARY: {counts}") + + # markdown table for inclusion in the analysis doc + print("") + print("| Generator | Required diagrams | Status | Output size | Notes |") + print("|-----------|-------------------|--------|-------------|-------|") + for r in results: + # Pretty-print sizes + size = ( + f"{r.output_size}B" + if r.output_size < 1024 + else (f"{r.output_size/1024:.1f}KiB" if r.output_size < 1024 * 1024 + else f"{r.output_size/(1024*1024):.2f}MiB") + ) + notes = r.notes.replace("|", "\\|") + print(f"| `{r.name}` | {r.required} | {r.status} | {size} ({r.file_count} files) | {notes} |") + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/utilities/web_modeling_editor/backend/smoke_webapp_generation.py b/tests/utilities/web_modeling_editor/backend/smoke_webapp_generation.py new file mode 100644 index 000000000..ea19c0450 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/smoke_webapp_generation.py @@ -0,0 +1,260 @@ +"""Backend smoke test: WebApp generation E2E from a v4 ProjectInput fixture. + +This is NOT a pytest. It's a runnable script that exercises the same path the +frontend's `useGenerateCode` hook will hit after the Phase 7 v4 cutover: +ProjectInput JSON -> process_class_diagram + process_gui_diagram -> WebAppGenerator. + +Run with: + + python tests/utilities/web_modeling_editor/backend/smoke_webapp_generation.py + +Exits 0 on success, non-zero on failure. Prints a structured report to stdout. +""" + +from __future__ import annotations + +import ast +import json +import os +import sys +import tempfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[4] +sys.path.insert(0, str(REPO_ROOT)) + +from besser.utilities.web_modeling_editor.backend.models import ( # noqa: E402 + DiagramInput, +) +from besser.utilities.web_modeling_editor.backend.models.project import ( # noqa: E402 + ProjectInput, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.class_diagram_processor import ( # noqa: E402 + process_class_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.gui_diagram_processor import ( # noqa: E402 + process_gui_diagram, +) +from besser.generators.web_app import WebAppGenerator # noqa: E402 + + +FIXTURE_PATH = REPO_ROOT / "tests" / "fixtures" / "v4" / "webapp_smoke_project.json" + + +def _load_project() -> ProjectInput: + with FIXTURE_PATH.open("r", encoding="utf-8") as fh: + raw = json.load(fh) + return ProjectInput(**raw) + + +def _walk_files(root: str) -> list[str]: + out: list[str] = [] + for dirpath, _dirs, files in os.walk(root): + for name in files: + out.append(os.path.join(dirpath, name)) + return out + + +def _human_bytes(total: int) -> str: + for unit in ("B", "KiB", "MiB", "GiB"): + if total < 1024.0: + return f"{total:.1f} {unit}" + total = int(total / 1024) + return f"{total} TiB" + + +def main() -> int: + print(f"[smoke] loading fixture: {FIXTURE_PATH}") + project = _load_project() + + # Mirror the router's project -> WebApp pipeline in + # _handle_web_app_project_generation (generation_router.py). + gui_diagram: DiagramInput | None = project.get_active_diagram("GUINoCodeDiagram") + if gui_diagram is None: + print("[smoke] FAIL: no GUINoCodeDiagram in fixture", file=sys.stderr) + return 2 + + class_diagram: DiagramInput | None = project.get_referenced_diagram( + gui_diagram, "ClassDiagram" + ) + if class_diagram is None: + print("[smoke] FAIL: no referenced ClassDiagram", file=sys.stderr) + return 2 + + print("[smoke] processing ClassDiagram (v4 nodes/edges) -> DomainModel ...") + domain_model = process_class_diagram(class_diagram.model_dump()) + classes = list(getattr(domain_model, "get_classes", lambda: [])()) + print(f"[smoke] classes: {[c.name for c in classes]}") + if len(classes) < 2: + print( + "[smoke] FAIL: expected at least 2 classes from ClassDiagram fixture", + file=sys.stderr, + ) + return 2 + + print("[smoke] processing GUINoCodeDiagram -> GUIModel ...") + gui_model = process_gui_diagram( + gui_diagram.model, class_diagram.model, domain_model + ) + modules = list(getattr(gui_model, "modules", []) or []) + screens = [] + for mod in modules: + screens.extend(getattr(mod, "screens", []) or []) + print( + f"[smoke] modules={len(modules)} screens={len(screens)} " + f"screen_names={[getattr(s, 'name', '?') for s in screens]}" + ) + if not screens: + print("[smoke] FAIL: no screens parsed from GUI fixture", file=sys.stderr) + return 2 + + with tempfile.TemporaryDirectory(prefix="besser_smoke_") as tmpdir: + print(f"[smoke] running WebAppGenerator -> {tmpdir}") + gen = WebAppGenerator( + model=domain_model, gui_model=gui_model, output_dir=tmpdir + ) + try: + gen.generate() + except Exception as exc: # noqa: BLE001 + print(f"[smoke] FAIL: generator raised: {exc!r}", file=sys.stderr) + import traceback + + traceback.print_exc() + return 3 + + files = _walk_files(tmpdir) + total_bytes = sum(os.path.getsize(p) for p in files if os.path.isfile(p)) + print(f"[smoke] generated {len(files)} files / {_human_bytes(total_bytes)}") + if not files: + print("[smoke] FAIL: output directory is empty", file=sys.stderr) + return 3 + + backend_dir = os.path.join(tmpdir, "backend") + frontend_dir = os.path.join(tmpdir, "frontend") + if not os.path.isdir(backend_dir): + print("[smoke] FAIL: no backend/ subdir produced", file=sys.stderr) + return 3 + if not os.path.isdir(frontend_dir): + print("[smoke] FAIL: no frontend/ subdir produced", file=sys.stderr) + return 3 + + # Parse every Python file in backend/ with ast — at least one must + # parse cleanly, and any failure is reported as a smoke failure. + py_files = [ + p + for p in _walk_files(backend_dir) + if p.endswith(".py") and os.path.isfile(p) + ] + py_ok = 0 + py_failures: list[tuple[str, str]] = [] + for path in py_files: + try: + with open(path, "r", encoding="utf-8") as fh: + src = fh.read() + ast.parse(src, filename=path) + py_ok += 1 + except SyntaxError as exc: + py_failures.append((path, f"{exc.lineno}: {exc.msg}")) + print(f"[smoke] backend python files: {py_ok}/{len(py_files)} parse OK") + for path, why in py_failures[:5]: + print(f"[smoke] ! {path}: {why}") + if py_files and py_ok == 0: + print( + "[smoke] FAIL: no backend python file parsed cleanly", + file=sys.stderr, + ) + return 3 + if py_failures: + print( + f"[smoke] WARN: {len(py_failures)} python file(s) failed ast.parse", + file=sys.stderr, + ) + + # Frontend: check at least one TSX/JSX/TS file is non-empty. + web_exts = (".tsx", ".jsx", ".ts", ".js", ".html") + web_files = [ + p + for p in _walk_files(frontend_dir) + if p.endswith(web_exts) and os.path.isfile(p) + ] + non_empty = sum(1 for p in web_files if os.path.getsize(p) > 0) + print( + f"[smoke] frontend web files: {non_empty}/{len(web_files)} non-empty" + ) + if not web_files or non_empty == 0: + print( + "[smoke] FAIL: no non-empty frontend web sources produced", + file=sys.stderr, + ) + return 3 + + # docker-compose.yml at root + compose = os.path.join(tmpdir, "docker-compose.yml") + if not os.path.isfile(compose): + print( + "[smoke] WARN: docker-compose.yml missing at output root", + file=sys.stderr, + ) + + # ------------------------------------------------------------------ + # HTTP path: hit /generate-output-from-project the way useGenerateCode + # does (POST JSON body with the full ProjectInput + settings.generator). + # ------------------------------------------------------------------ + print("[smoke] exercising HTTP /generate-output-from-project ...") + try: + import asyncio + + import httpx + from httpx._transports.asgi import ASGITransport + + from besser.utilities.web_modeling_editor.backend.backend import app + + with FIXTURE_PATH.open("r", encoding="utf-8") as fh: + payload = json.load(fh) + # useGenerateCode sets settings.generator and a normalized name; the + # fixture already has settings.generator='web_app'. + + async def _post() -> httpx.Response: + transport = ASGITransport(app=app) + async with httpx.AsyncClient( + transport=transport, base_url="http://testserver", timeout=60.0 + ) as ac: + return await ac.post( + "/besser_api/generate-output-from-project", json=payload + ) + + resp = asyncio.run(_post()) + ctype = resp.headers.get("content-type", "") + body_len = len(resp.content) + print( + f"[smoke] HTTP status={resp.status_code} " + f"content-type={ctype!r} body_bytes={body_len}" + ) + if resp.status_code != 200: + preview = resp.text[:500] if resp.text else "" + print(f"[smoke] FAIL: HTTP non-200 — body: {preview}", file=sys.stderr) + return 4 + if "zip" not in ctype.lower(): + print( + f"[smoke] WARN: expected zip media-type, got {ctype!r}", + file=sys.stderr, + ) + if body_len < 1024: + print( + f"[smoke] FAIL: HTTP zip too small ({body_len}B)", + file=sys.stderr, + ) + return 4 + except Exception as exc: # noqa: BLE001 + print(f"[smoke] FAIL: HTTP exercise raised: {exc!r}", file=sys.stderr) + import traceback + + traceback.print_exc() + return 4 + + print("[smoke] PASS") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/utilities/web_modeling_editor/backend/spec_driven/test_model_assembly.py b/tests/utilities/web_modeling_editor/backend/spec_driven/test_model_assembly.py index 384148727..f993cc504 100644 --- a/tests/utilities/web_modeling_editor/backend/spec_driven/test_model_assembly.py +++ b/tests/utilities/web_modeling_editor/backend/spec_driven/test_model_assembly.py @@ -11,81 +11,68 @@ ) +# v4 wire shape ({nodes, edges}) — see docs/source/migrations/uml-v4-shape.md. CLASS_DIAGRAM_MODEL = { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": { - "type": "Class", - "name": "Author", - "attributes": ["attr-1"], - "methods": [], - }, - "attr-1": { - "type": "Attribute", - "name": "+ name: str", - }, - "class-2": { - "type": "Class", - "name": "Book", - "attributes": ["attr-2"], - "methods": [], - }, - "attr-2": { - "type": "Attribute", - "name": "+ title: str", + "nodes": [ + { + "id": "class-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": { + "name": "Author", + "attributes": [{"id": "attr-1", "name": "name", "attributeType": "str", "visibility": "public"}], + "methods": [], + }, }, - }, - "relationships": { - "rel-1": { - "type": "ClassBidirectional", - "source": { - "element": "class-1", - "multiplicity": "1..*", - "role": "authors", + { + "id": "class-2", "type": "class", + "position": {"x": 300, "y": 0}, "width": 160, "height": 100, + "data": { + "name": "Book", + "attributes": [{"id": "attr-2", "name": "title", "attributeType": "str", "visibility": "public"}], + "methods": [], }, - "target": { - "element": "class-2", - "multiplicity": "0..*", - "role": "books", + }, + ], + "edges": [ + { + "id": "rel-1", "type": "ClassBidirectional", + "source": "class-1", "target": "class-2", + "sourceHandle": "Right", "targetHandle": "Left", + "data": { + "sourceMultiplicity": "1..*", "sourceRole": "authors", + "targetMultiplicity": "0..*", "targetRole": "books", + "points": [], }, }, - }, + ], } BPMN_DIAGRAM_MODEL = { - "version": "3.0.0", + "version": "4.0.0", "type": "BPMNDiagram", "size": {"width": 1400, "height": 700}, - "elements": { - "start": { - "id": "start", "name": "Start", "type": "BPMNStartEvent", - "owner": None, "eventType": "default", - "bounds": {"x": 100, "y": 100, "width": 50, "height": 50}, + "nodes": [ + { + "id": "start", "type": "bpmnStartEvent", + "position": {"x": 100, "y": 100}, "width": 50, "height": 50, + "data": {"name": "Start", "eventType": "default"}, }, - "review": { - "id": "review", "name": "Review", "type": "BPMNTask", - "owner": None, "taskType": "user", "marker": "none", - "bounds": {"x": 250, "y": 100, "width": 110, "height": 60}, + { + "id": "review", "type": "bpmnTask", + "position": {"x": 250, "y": 100}, "width": 110, "height": 60, + "data": {"name": "Review", "taskType": "user", "marker": "none"}, }, - }, - "relationships": { - "flow": { - "id": "flow", "name": "", "type": "BPMNFlow", "owner": None, - "bounds": {"x": 0, "y": 0, "width": 100, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], - "source": { - "element": "start", "direction": "Right", - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}, - }, - "target": { - "element": "review", "direction": "Left", - "bounds": {"x": 100, "y": 0, "width": 0, "height": 0}, - }, - "isManuallyLayouted": False, - "flowType": "sequence", - "isDefault": False, + ], + "edges": [ + { + "id": "flow", "type": "BPMNSequenceFlow", + "source": "start", "target": "review", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "", "points": [], "isManuallyLayouted": False}, }, - }, + ], "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, } @@ -162,8 +149,8 @@ def test_bpmn_and_nn_can_drive_assembly( "title": "Primary", "model": { "type": diagram_type, - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, }], }) @@ -185,7 +172,7 @@ def test_project_without_class_diagram_is_accepted(self): { "id": "ad1", "title": "Agent", - "model": {"type": "AgentDiagram", "elements": {}, "relationships": {}}, + "model": {"type": "AgentDiagram", "nodes": [], "edges": []}, } ] }) @@ -365,7 +352,7 @@ def _assemble(monkeypatch, **kwargs): "GUINoCodeDiagram": [{"id": "gui1", "title": "Screens", "model": {"type": "GUINoCodeDiagram", "pages": []}}], "AgentDiagram": [{"id": "ad1", "title": "Helper", - "model": {"type": "AgentDiagram", "elements": {}, "relationships": {}}}], + "model": {"version": "4.0.0", "type": "AgentDiagram", "nodes": [], "edges": []}}], }) return assemble_models_from_project(project, **kwargs), agent @@ -395,8 +382,9 @@ class TestGuiOfAnotherClassDiagram: def _assemble(monkeypatch, gui_binds): monkeypatch.setattr(model_assembly_module, "process_gui_diagram", lambda *args: object()) monkeypatch.setattr(model_assembly_module, "has_agent_components", lambda gui: False) - newer = {"type": "ClassDiagram", "elements": { - "class-9": {"type": "Class", "name": "Quiz", "attributes": [], "methods": []}}, "relationships": {}} + newer = {"version": "4.0.0", "type": "ClassDiagram", "edges": [], "nodes": [ + {"id": "class-9", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Quiz", "attributes": [], "methods": []}}]} gui = {"type": "GUINoCodeDiagram", "pages": [{"frames": [{"component": { "type": "table", "attributes": {"data-source": gui_binds}}}]}]} project = ProjectInput( diff --git a/tests/utilities/web_modeling_editor/backend/test_agent_simulator_router.py b/tests/utilities/web_modeling_editor/backend/test_agent_simulator_router.py index f71dabc36..a19bfa102 100644 --- a/tests/utilities/web_modeling_editor/backend/test_agent_simulator_router.py +++ b/tests/utilities/web_modeling_editor/backend/test_agent_simulator_router.py @@ -45,39 +45,30 @@ def _run(coro): # --------------------------------------------------------------------------- def _agent_model(actions: Optional[Dict[str, Dict[str, Any]]] = None) -> Dict[str, Any]: - """Minimal AgentDiagram: initial node -> one state, with optional action elements.""" - elements: Dict[str, Any] = { - "init-node": {"id": "init-node", "type": "StateInitialNode", "name": ""}, - "state-1": { - "id": "state-1", - "type": "AgentState", - "name": "Greet", - "actions": list((actions or {}).keys()), - }, - } - elements.update(actions or {}) + """Minimal v4 AgentDiagram: one initial state with optional inline action rows.""" return { + "version": "4.0.0", "type": "AgentDiagram", - "elements": elements, - "relationships": { - "trans-init": { - "type": "AgentStateTransitionInit", - "name": "", - "source": {"element": "init-node"}, - "target": {"element": "state-1"}, - }, - }, + "nodes": [{ + "id": "state-1", + "type": "AgentState", + "position": {"x": 0, "y": 0}, + "width": 160, + "height": 100, + "data": {"name": "Greet", "initial": True, "bodies": list((actions or {}).values()), + "fallbackBodies": []}, + }], + "edges": [], + "components": {}, } def _text_reply_model() -> Dict[str, Any]: - return _agent_model({"a1": {"id": "a1", "type": "AgentStateBody", "actionType": "TextReplyAction", - "name": "Hello there"}}) + return _agent_model({"a1": {"id": "a1", "actionType": "TextReplyAction", "name": "Hello there"}}) def _custom_code_model(code: str) -> Dict[str, Any]: - return _agent_model({"a1": {"id": "a1", "type": "AgentStateBody", "actionType": "CustomCodeAction", - "name": code}}) + return _agent_model({"a1": {"id": "a1", "actionType": "CustomCodeAction", "name": code}}) def _session_payload(model: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: @@ -288,6 +279,45 @@ def test_create_session_rejects_restricted_custom_code(simulator): assert simulator.requests == [] +def _hybrid_model(**v4_actions) -> Dict[str, Any]: + """v4 nodes plus a v3-style ``elements`` map; it passes the legacy-format guard + because it has ``nodes``. The ``elements`` carry code that must never run.""" + model = _agent_model(v4_actions or None) + model["elements"] = { + "smuggled-code": {"id": "smuggled-code", "type": "AgentStateBody", "actionType": "CustomCodeAction", + "name": "def act(session):\n SMUGGLED_MARKER = 1\n", "owner": "state-1"}, + "smuggled-tool": {"id": "smuggled-tool", "type": "AgentTool", "name": "smuggled_tool", + "code": "def smuggled_tool():\n SMUGGLED_MARKER = 2\n"}, + } + return model + + +def test_hybrid_payload_elements_never_reach_the_simulator(simulator): + """The restriction checks v4 bodies only, so a v3 ``elements`` map next to + ``nodes`` must not be read by the converter either.""" + resp = _request("POST", f"{BASE}/sessions", ALICE, json=_session_payload(_hybrid_model())) + assert resp.status_code == 200, resp.text + [sent] = simulator.requests + assert "SMUGGLED_MARKER" not in sent.content.decode() + + +def test_converter_ignores_hybrid_payload_elements(): + """A v3 AgentTool in ``elements`` used to become a generated tool, whose code + the custom-code restriction never checks.""" + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.agent_diagram_processor import ( + process_agent_diagram, + ) + agent = process_agent_diagram({"title": "Agent", "model": _hybrid_model()}) + assert [tool.name for tool in agent.tools] == [] + + +def test_hybrid_payload_with_v4_custom_code_is_still_restricted(simulator): + model = _hybrid_model(a1={"id": "a1", "actionType": "CustomCodeAction", "name": "def act(session): pass"}) + resp = _request("POST", f"{BASE}/sessions", ALICE, json=_session_payload(model)) + assert resp.status_code == 403 + assert simulator.requests == [] + + def test_create_session_maps_code_validation_error_to_400(simulator, route_settings): route_settings.agent_simulator_restrict_custom_code = False model = _custom_code_model("def act(ctx):\n pass\n") @@ -636,3 +666,17 @@ async def _scenario(): await ws.expect_close(4400) _run(_scenario()) + + +@pytest.mark.parametrize("key", ["bodies", "actions", "fallbackBodies", "fallbackActions"]) +def test_custom_code_is_restricted_under_every_action_row_key(simulator, key): + """The converter reads ``actions`` / ``fallbackActions`` before the legacy + ``bodies`` / ``fallbackBodies``; the gate must check all four keys.""" + model = _agent_model() + data = model["nodes"][0]["data"] + data["bodies"], data["fallbackBodies"] = [], [] + data[key] = [{"id": "c1", "actionType": "CustomCodeAction", + "code": "def act(session):\n session.reply('CUSTOMMARK')\n"}] + resp = _request("POST", f"{BASE}/sessions", ALICE, json=_session_payload(model)) + assert resp.status_code == 403 + assert simulator.requests == [] diff --git a/tests/utilities/web_modeling_editor/backend/test_agent_without_states.py b/tests/utilities/web_modeling_editor/backend/test_agent_without_states.py new file mode 100644 index 000000000..6bb760e50 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/test_agent_without_states.py @@ -0,0 +1,129 @@ +"""An agent diagram with intents or LLMs but no states cannot become an agent. + +Asking for exactly that agent (single-diagram generation, standalone chatbot +deploy) is an error. The paths that build every agent of a project (web app / +Docker Compose generation, web-app deploy) skip it with a warning in the log, +so one agent still being drawn does not block the rest of the project. +""" + +import asyncio +import io +import logging +import zipfile + +import json +import os + +import httpx +import pytest +from httpx._transports.asgi import ASGITransport + +from besser.utilities.web_modeling_editor.backend.backend import app +from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import ( + collect_agents_from_diagrams, +) + +_COMPONENTS_ONLY = { + "version": "4.0.0", "type": "AgentDiagram", "nodes": [], "edges": [], + "components": { + "i1": {"id": "i1", "type": "AgentIntent", "name": "Greet", "bodies": ["b1"]}, + "b1": {"id": "b1", "type": "AgentIntentBody", "name": "hi", "owner": "i1"}, + }, +} +FIXTURES_V4 = os.path.join(os.path.dirname(__file__), "..", "..", "..", "fixtures", "v4") +_EMPTY = {"version": "4.0.0", "type": "AgentDiagram", "nodes": [], "edges": []} + + +def _entry(model, title="Helper"): + return {"id": "agent-1", "title": title, "model": model} + + +def _post(url, **kwargs): + async def _go(): + async with httpx.AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as ac: + return await ac.post(url, **kwargs) + return asyncio.run(_go()) + + +@pytest.fixture(autouse=True) +def _isolate_cwd(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + + +def _skip_warnings(caplog): + return [r.getMessage() for r in caplog.records + if r.levelno == logging.WARNING and "Skipping agent diagram 'Helper': it has no states" in r.getMessage()] + + +def test_collect_agents_skips_an_agent_without_states_with_a_warning(caplog): + with open(os.path.join(FIXTURES_V4, "agent_diagram_basic.json"), encoding="utf-8") as f: + drawn = json.load(f) + + with caplog.at_level(logging.WARNING): + agents, configs, _ = collect_agents_from_diagrams([_entry(_COMPONENTS_ONLY), drawn]) + + assert [agent.name for agent in agents] == ["GreetBot"] + assert list(configs) == ["GreetBot"] + assert len(_skip_warnings(caplog)) == 1 + + +def test_collect_agents_still_skips_an_empty_placeholder(): + assert collect_agents_from_diagrams([_entry(_EMPTY)])[0] == [] + + +def test_docker_compose_skips_an_agent_without_states_with_a_warning(caplog): + deployment = {"version": "4.0.0", "type": "DeploymentDiagram", "edges": [], "nodes": [ + {"id": "host", "type": "deploymentNode", "position": {"x": 0, "y": 0}, "width": 300, + "height": 200, "data": {"name": "Host", "stereotype": "node", "isComponentHeaderShown": True}}, + ]} + project = { + "id": "p", "type": "Project", "name": "P", "createdAt": "2026-01-01T00:00:00Z", + "currentDiagramType": "DeploymentDiagram", "currentDiagramIndices": {}, + "settings": {"generator": "docker_compose"}, + "diagrams": {"DeploymentDiagram": [{"id": "d", "title": "Infra", "model": deployment}], + "AgentDiagram": [_entry(_COMPONENTS_ONLY)]}, + } + with caplog.at_level(logging.WARNING): + response = _post("/besser_api/generate-output-from-project", json=project) + + assert response.status_code == 200, response.text + with zipfile.ZipFile(io.BytesIO(response.content)) as archive: + assert "docker-compose.yml" in archive.namelist() + assert len(_skip_warnings(caplog)) == 1 + + +def test_saving_to_github_keeps_the_model_files_of_an_agent_without_states(): + """Saving is storage, not generation: an agent still being drawn does not block the save.""" + from besser.utilities.web_modeling_editor.backend.services.deployment import repo_model + + project = {"id": "p", "type": "Project", "name": "P", "createdAt": "2026-01-01T00:00:00Z", + "currentDiagramIndices": {}, "diagrams": {"AgentDiagram": [_entry(_COMPONENTS_ONLY)]}} + saved = repo_model.build_model_files(project) + + assert saved.sources_built + assert repo_model.MODEL_FILE in saved.files + + +def test_standalone_agent_deploy_reports_an_agent_without_states(monkeypatch): + from besser.utilities.web_modeling_editor.backend.routers import github_deploy_api as gda + + class _FakeGitHub: + async def get_authenticated_user(self): + return {"login": "someone"} + + monkeypatch.setattr(gda, "get_user_token", lambda _sessions, _session: "fake-token") + monkeypatch.setattr(gda, "create_github_service", lambda _token: _FakeGitHub()) + body = {"id": "p", "type": "Project", "name": "P", "createdAt": "2026-01-01T00:00:00Z", + "diagrams": {"AgentDiagram": [_entry(_COMPONENTS_ONLY)]}, + "deploy_config": {"repo_name": "bot", "target": "agent"}} + response = _post("/besser_api/github/deploy-webapp", json=body, + headers={"X-GitHub-Session": "test-session"}) + assert response.status_code == 400, response.text + assert "'Helper' has no states" in response.json()["detail"] + + +def test_single_diagram_agent_generation_reports_an_agent_without_states(): + body = {"title": "Helper", "model": _COMPONENTS_ONLY, "generator": "agent"} + response = _post("/besser_api/generate-output", json=body) + assert response.status_code == 400, response.text + assert "'Helper' has no states" in response.json()["detail"] diff --git a/tests/utilities/web_modeling_editor/backend/test_ai_reverse.py b/tests/utilities/web_modeling_editor/backend/test_ai_reverse.py index a27aee51f..a2c26c54b 100644 --- a/tests/utilities/web_modeling_editor/backend/test_ai_reverse.py +++ b/tests/utilities/web_modeling_editor/backend/test_ai_reverse.py @@ -397,9 +397,9 @@ def test_import_proposes_an_ai_model_when_the_code_has_no_readable_data_classes( assert "an AI model read its code" in body["message"] diagram = body["proposed_diagram"] assert diagram["diagramType"] == "ClassDiagram" and diagram["model"]["type"] == "ClassDiagram" - elements = diagram["model"]["elements"].values() - assert {e["name"] for e in elements if e.get("type") == "Class"} == {"Customer", "Order"} - assert {e["name"] for e in elements if e.get("type") == "Enumeration"} == {"OrderStatus"} + stereotypes = {n["data"]["name"]: n["data"].get("stereotype") for n in diagram["model"]["nodes"]} + assert {name for name, kind in stereotypes.items() if kind != "Enumeration"} == {"Customer", "Order"} + assert {name for name, kind in stereotypes.items() if kind == "Enumeration"} == {"OrderStatus"} def test_import_succeeds_without_a_proposal_when_the_ai_fails(monkeypatch, tmp_path): diff --git a/tests/utilities/web_modeling_editor/backend/test_api_integration.py b/tests/utilities/web_modeling_editor/backend/test_api_integration.py index bea7074df..0934b78b0 100644 --- a/tests/utilities/web_modeling_editor/backend/test_api_integration.py +++ b/tests/utilities/web_modeling_editor/backend/test_api_integration.py @@ -31,52 +31,61 @@ def _run(coro): return asyncio.run(coro) +def _v4_node(node_id: str, node_type: str, data: Dict[str, Any]) -> Dict[str, Any]: + return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, + "width": 160, "height": 100, "data": data} + + # --------------------------------------------------------------------------- # Fixtures -- minimal valid diagram payloads # --------------------------------------------------------------------------- @pytest.fixture def class_diagram_model(): - """Minimal valid class diagram model with two classes and an association.""" + """Minimal v4 class diagram model with two classes and an association.""" return { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": { - "type": "Class", - "name": "Author", - "attributes": ["attr-1"], - "methods": [], - }, - "attr-1": { - "type": "Attribute", - "name": "+ name: str", - }, - "class-2": { - "type": "Class", - "name": "Book", - "attributes": ["attr-2"], - "methods": [], + "nodes": [ + { + "id": "class-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Author", "stereotype": None, + "attributes": [ + {"id": "attr-1", "name": "name", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - "attr-2": { - "type": "Attribute", - "name": "+ title: str", + { + "id": "class-2", "type": "class", + "position": {"x": 300, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Book", "stereotype": None, + "attributes": [ + {"id": "attr-2", "name": "title", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - }, - "relationships": { - "rel-1": { + ], + "edges": [ + { + "id": "rel-1", + "source": "class-1", "target": "class-2", "type": "ClassBidirectional", - "source": { - "element": "class-1", - "multiplicity": "1..*", - "role": "authors", - }, - "target": { - "element": "class-2", - "multiplicity": "0..*", - "role": "books", + "sourceHandle": "Right", "targetHandle": "Left", + "data": { + "name": "writes", + "sourceRole": "authors", "sourceMultiplicity": "1..*", + "targetRole": "books", "targetMultiplicity": "0..*", + "points": [], }, }, - }, + ], } @@ -84,15 +93,15 @@ def class_diagram_model(): def spring_class_diagram_input(class_diagram_model): """``class_diagram_input`` with identifiers, which JPA entities require.""" model = copy.deepcopy(class_diagram_model) + nodes_by_id = {node["id"]: node for node in model["nodes"]} for class_key, attribute_key in (("class-1", "id-1"), ("class-2", "id-2")): - model["elements"][attribute_key] = { - "type": "Attribute", + nodes_by_id[class_key]["data"]["attributes"].append({ + "id": attribute_key, "name": "id", "visibility": "public", "attributeType": "int", "isId": True, - } - model["elements"][class_key]["attributes"].append(attribute_key) + }) return { "title": "LibraryModel", "model": model, @@ -112,22 +121,25 @@ def class_diagram_input(class_diagram_model): @pytest.fixture def single_class_model(): - """Simplest possible class diagram with one class and one attribute.""" + """Simplest possible v4 class diagram: one class with one attribute.""" return { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": { - "type": "Class", - "name": "Person", - "attributes": ["attr-1"], - "methods": [], - }, - "attr-1": { - "type": "Attribute", - "name": "+ name: str", + "nodes": [ + { + "id": "class-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Person", "stereotype": None, + "attributes": [ + {"id": "attr-1", "name": "name", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - }, - "relationships": {}, + ], + "edges": [], } @@ -143,44 +155,50 @@ def single_class_input(single_class_model): @pytest.fixture def state_machine_model(): - """Minimal state machine diagram model. + """Minimal v4 state machine diagram model. - Uses the frontend's actual JSON structure where initial state is - determined by a StateInitialNode element with a StateTransition - relationship pointing to the first real state. + A StateInitialNode with a StateTransition into the first real state + establishes the initial state. """ return { + "version": "4.0.0", "type": "StateMachineDiagram", - "elements": { - "init-node": { - "type": "StateInitialNode", - "name": "", + "nodes": [ + { + "id": "init-node", "type": "StateInitialNode", + "position": {"x": 0, "y": 0}, "width": 45, "height": 45, + "measured": {"width": 45, "height": 45}, + "data": {"name": ""}, }, - "state-1": { - "type": "State", - "name": "Idle", - "bodies": [], + { + "id": "state-1", "type": "State", + "position": {"x": 100, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Idle", "bodies": [], "fallbackBodies": []}, }, - "state-2": { - "type": "State", - "name": "Active", - "bodies": [], + { + "id": "state-2", "type": "State", + "position": {"x": 400, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Active", "bodies": [], "fallbackBodies": []}, }, - }, - "relationships": { - "trans-init": { + ], + "edges": [ + { + "id": "trans-init", + "source": "init-node", "target": "state-1", "type": "StateTransition", - "name": "", - "source": {"element": "init-node"}, - "target": {"element": "state-1"}, + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "", "points": []}, }, - "trans-1": { + { + "id": "trans-1", + "source": "state-1", "target": "state-2", "type": "StateTransition", - "name": "", - "source": {"element": "state-1"}, - "target": {"element": "state-2"}, + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "", "points": []}, }, - }, + ], } @@ -195,21 +213,27 @@ def state_machine_input(state_machine_model): @pytest.fixture def enumeration_model(): - """Class diagram with an enumeration type.""" + """V4 class diagram with an enumeration type (stereotype='enumeration').""" return { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "enum-1": { - "type": "Enumeration", - "name": "Color", - "attributes": ["lit-1", "lit-2", "lit-3"], - "methods": [], + "nodes": [ + { + "id": "enum-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Color", "stereotype": "enumeration", + "attributes": [ + {"id": "lit-1", "name": "RED", "attributeType": "str", "visibility": "public"}, + {"id": "lit-2", "name": "GREEN", "attributeType": "str", "visibility": "public"}, + {"id": "lit-3", "name": "BLUE", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - "lit-1": {"type": "EnumerationLiteral", "name": "RED"}, - "lit-2": {"type": "EnumerationLiteral", "name": "GREEN"}, - "lit-3": {"type": "EnumerationLiteral", "name": "BLUE"}, - }, - "relationships": {}, + ], + "edges": [], } @@ -356,7 +380,8 @@ def test_generate_alloy_from_class_diagram(self, client, class_diagram_input): def test_generate_alloy_rejects_an_untranslatable_class_diagram(self, client, class_diagram_input): """An attribute type without an Alloy translation is a client error.""" payload = copy.deepcopy({**class_diagram_input, "generator": "alloy"}) - payload["model"]["elements"]["attr-1"]["name"] = "+ name: time" + rows = [row for node in payload["model"]["nodes"] for row in node["data"].get("attributes", [])] + next(row for row in rows if row["id"] == "attr-1")["attributeType"] = "time" response = client.post("/besser_api/generate-output", json=payload) assert response.status_code == 400 assert "Attributes of type 'time' are not supported" in response.json()["detail"] @@ -374,7 +399,7 @@ def test_generate_with_missing_generator(self, client): """Request with no generator field defaults to None and returns 400.""" payload = { "title": "Test", - "model": {"type": "ClassDiagram", "elements": {}, "relationships": {}}, + "model": {"version": "4.0.0", "type": "ClassDiagram", "nodes": [], "edges": []}, } response = client.post("/besser_api/generate-output", json=payload) assert response.status_code == 400 @@ -383,7 +408,7 @@ def test_generate_with_empty_model(self, client): """An empty class diagram model should still work (produces empty output).""" payload = { "title": "EmptyModel", - "model": {"type": "ClassDiagram", "elements": {}, "relationships": {}}, + "model": {"version": "4.0.0", "type": "ClassDiagram", "nodes": [], "edges": []}, "generator": "python", } response = client.post("/besser_api/generate-output", json=payload) @@ -539,16 +564,18 @@ def test_validate_invalid_class_name_with_spaces(self, client): payload = { "title": "BadModel", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": { - "type": "Class", - "name": "Bad Class Name", - "attributes": [], - "methods": [], + "nodes": [ + { + "id": "class-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Bad Class Name", "stereotype": None, + "attributes": [], "methods": []}, }, - }, - "relationships": {}, + ], + "edges": [], }, } response = client.post("/besser_api/validate-diagram", json=payload) @@ -562,16 +589,18 @@ def test_validate_empty_class_name(self, client): payload = { "title": "BadModel", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": { - "type": "Class", - "name": "", - "attributes": [], - "methods": [], + "nodes": [ + { + "id": "class-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "", "stereotype": None, + "attributes": [], "methods": []}, }, - }, - "relationships": {}, + ], + "edges": [], }, } response = client.post("/besser_api/validate-diagram", json=payload) @@ -580,11 +609,31 @@ def test_validate_empty_class_name(self, client): assert data["isValid"] is False assert len(data["errors"]) > 0 + @pytest.mark.parametrize("reference_title", ["", " ", None]) + def test_validate_object_diagram_with_untitled_reference(self, client, reference_title): + """Migrated projects carry an empty reference ``title``; validation must + fall back to a default name instead of failing "Name cannot be empty".""" + fixture_path = os.path.join( + os.path.dirname(__file__), "..", "..", "..", "fixtures", "v4", "object_diagram_basic.json", + ) + with open(fixture_path, encoding="utf-8") as handle: + payload = json.load(handle) + reference = payload["model"]["referenceDiagramData"] + if reference_title is None: + reference.pop("title", None) + else: + reference["title"] = reference_title + response = client.post("/besser_api/validate-diagram", json=payload) + assert response.status_code == 200 + data = response.json() + assert data["errors"] == [] + assert data["isValid"] is True + def test_validate_unsupported_diagram_type(self, client): """Unsupported diagram type returns isValid=False.""" payload = { "title": "Unknown", - "model": {"type": "UnknownDiagramType", "elements": {}, "relationships": {}}, + "model": {"version": "4.0.0", "type": "UnknownDiagramType", "nodes": [], "edges": []}, } response = client.post("/besser_api/validate-diagram", json=payload) assert response.status_code == 200 @@ -604,15 +653,17 @@ def test_validate_state_machine_no_initial_state(self, client): payload = { "title": "NoInitialSM", "model": { + "version": "4.0.0", "type": "StateMachineDiagram", - "elements": { - "state-1": { - "type": "State", - "name": "StateA", - "bodies": [], + "nodes": [ + { + "id": "state-1", "type": "State", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "StateA", "bodies": [], "fallbackBodies": []}, }, - }, - "relationships": {}, + ], + "edges": [], }, } response = client.post("/besser_api/validate-diagram", json=payload) @@ -627,9 +678,10 @@ def test_validate_state_machine_no_states(self, client): payload = { "title": "EmptySM", "model": { + "version": "4.0.0", "type": "StateMachineDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, } response = client.post("/besser_api/validate-diagram", json=payload) @@ -643,31 +695,37 @@ def test_validate_state_machine_duplicate_names(self, client): payload = { "title": "DupSM", "model": { + "version": "4.0.0", "type": "StateMachineDiagram", - "elements": { - "init-node": { - "type": "StateInitialNode", - "name": "", + "nodes": [ + { + "id": "init-node", "type": "StateInitialNode", + "position": {"x": 0, "y": 0}, "width": 45, "height": 45, + "measured": {"width": 45, "height": 45}, + "data": {"name": ""}, }, - "state-1": { - "type": "State", - "name": "Alpha", - "bodies": [], + { + "id": "state-1", "type": "State", + "position": {"x": 100, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Alpha", "bodies": [], "fallbackBodies": []}, }, - "state-2": { - "type": "State", - "name": "Alpha", - "bodies": [], + { + "id": "state-2", "type": "State", + "position": {"x": 400, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Alpha", "bodies": [], "fallbackBodies": []}, }, - }, - "relationships": { - "trans-init": { + ], + "edges": [ + { + "id": "trans-init", + "source": "init-node", "target": "state-1", "type": "StateTransition", - "name": "", - "source": {"element": "init-node"}, - "target": {"element": "state-1"}, + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "", "points": []}, }, - }, + ], }, } response = client.post("/besser_api/validate-diagram", json=payload) @@ -698,9 +756,14 @@ def test_validate_returns_warnings_list(self, client, class_diagram_input): def test_design_check_warnings_leave_an_older_model_valid_and_generating(self, client, single_class_model): """A model saved before the #756 design checks, which trips only their warnings, still generates.""" model = copy.deepcopy(single_class_model) - model["elements"]["class-1"]["attributes"].append("attr-2") - model["elements"]["attr-2"] = {"type": "Attribute", "name": "+ id: int"} # 'id' not the identifier - model["elements"]["class-2"] = {"type": "Class", "name": "Note", "attributes": [], "methods": []} # isolated + # 'id' not the identifier + model["nodes"][0]["data"]["attributes"].append( + {"id": "attr-2", "name": "id", "attributeType": "int", "visibility": "public"} + ) + model["nodes"].append({ # isolated + "id": "class-2", "type": "class", "position": {"x": 300, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Note", "attributes": [], "methods": []}, + }) payload = {"title": "SavedBefore756", "model": model, "generator": "python"} validation = client.post("/besser_api/validate-diagram", json=payload).json() @@ -727,9 +790,10 @@ def test_validate_object_diagram_missing_reference(self, client): payload = { "title": "ObjTest", "model": { + "version": "4.0.0", "type": "ObjectDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, } response = client.post("/besser_api/validate-diagram", json=payload) @@ -748,7 +812,7 @@ def test_validate_user_diagram_has_no_reference_model_warnings(self, client): from besser.utilities.web_modeling_editor.backend.routers import validation_router as vr assert vr.user_reference_domain_model.validate(raise_exception=False)["warnings"] - payload = {"title": "UserProfile", "model": {"type": "UserDiagram", "elements": {}, "relationships": {}}} + payload = {"title": "UserProfile", "model": {"version": "4.0.0", "type": "UserDiagram", "nodes": [], "edges": []}} data = client.post("/besser_api/validate-diagram", json=payload).json() @@ -788,9 +852,10 @@ def _fake_check_ocl_constraint(_domain_model, object_model=None, evaluate=True): payload = { "title": "UserProfile", "model": { + "version": "4.0.0", "type": "UserDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, } @@ -819,38 +884,41 @@ def _fake_check_ocl_constraint(_domain_model, object_model=None, evaluate=True): @classmethod def _conference_payload(cls, slot_role: str) -> Dict[str, Any]: """Event / Session / Room / ScheduleSlot (DateTime start/end) + the issue's invariant.""" - elements: Dict[str, Any] = {} + nodes = [] for cid, name, attrs in [ ("c-event", "Event", [("title", "str")]), ("c-session", "Session", [("title", "str")]), ("c-room", "Room", [("name", "str")]), - ("c-slot", "ScheduleSlot", [("startTime", "DateTime"), ("endTime", "DateTime")]), + ("c-slot", "ScheduleSlot", [("startTime", "datetime"), ("endTime", "datetime")]), ]: - elements[cid] = { - "type": "Class", "name": name, "methods": [], - "attributes": [f"{cid}-{attr}" for attr, _ in attrs], - } - for attr, attr_type in attrs: - elements[f"{cid}-{attr}"] = {"type": "Attribute", "name": f"+ {attr}: {attr_type}"} - elements["ocl-1"] = {"type": "ClassOCLConstraint", "constraint": cls._OVERLAP_OCL} + nodes.append(_v4_node(cid, "class", { + "name": name, "methods": [], + "attributes": [ + {"id": f"{cid}-{attr}", "name": attr, "attributeType": attr_type, + "visibility": "public"} + for attr, attr_type in attrs + ], + })) + nodes.append(_v4_node("ocl-1", "ClassOCLConstraint", {"expression": cls._OVERLAP_OCL})) def _rel(rid, target, role): return { - "id": rid, "type": "ClassBidirectional", "name": rid, - "source": {"element": "c-session", "role": "", "multiplicity": "0..*"}, - "target": {"element": target, "role": role, "multiplicity": "1"}, + "id": rid, "type": "ClassBidirectional", "source": "c-session", "target": target, + "data": {"name": rid, "sourceRole": "", "sourceMultiplicity": "0..*", + "targetRole": role, "targetMultiplicity": "1", "points": []}, } return { "title": "Conference", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": elements, - "relationships": { - "SessionRoom": _rel("SessionRoom", "c-room", ""), - "SessionSlot": _rel("SessionSlot", "c-slot", slot_role), - "SessionEvent": _rel("SessionEvent", "c-event", ""), - }, + "nodes": nodes, + "edges": [ + _rel("SessionRoom", "c-room", ""), + _rel("SessionSlot", "c-slot", slot_role), + _rel("SessionEvent", "c-event", ""), + ], }, } @@ -942,7 +1010,7 @@ def test_export_unsupported_diagram_type(self, client): """Exporting an unsupported diagram type returns 400.""" payload = { "title": "Unknown", - "model": {"type": "UnknownType", "elements": {}, "relationships": {}}, + "model": {"version": "4.0.0", "type": "UnknownType", "nodes": [], "edges": []}, } response = client.post("/besser_api/export-buml", json=payload) assert response.status_code == 400 @@ -953,7 +1021,7 @@ def test_export_missing_diagram_type(self, client): """Exporting without a diagram type returns 400.""" payload = { "title": "NoType", - "model": {"elements": {}, "relationships": {}}, + "model": {"version": "4.0.0", "nodes": [], "edges": []}, } response = client.post("/besser_api/export-buml", json=payload) assert response.status_code == 400 @@ -1019,8 +1087,8 @@ def test_component_buml_with_relationships_round_trips(self, client): assert response.status_code == 200, response.text data = response.json() assert data["diagramType"] == "ComponentDiagram" - assert {r["type"] for r in data["model"]["relationships"].values()} == { - "ComponentDependency", "ComponentInterfaceProvided"} + assert {e["type"] for e in data["model"]["edges"]} == { + "ComponentDependency", "ComponentProvidedInterface"} def test_deployment_buml_with_relationships_round_trips(self, client): from besser.BUML.metamodel.uml_deployment import ( @@ -1040,7 +1108,7 @@ def test_deployment_buml_with_relationships_round_trips(self, client): assert response.status_code == 200, response.text data = response.json() assert data["diagramType"] == "DeploymentDiagram" - assert {r["type"] for r in data["model"]["relationships"].values()} == { + assert {e["type"] for e in data["model"]["edges"]} == { "DeploymentAssociation", "DeploymentDependency"} @@ -1114,20 +1182,23 @@ def test_generate_class_with_methods(self, client): payload = { "title": "MethodModel", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": { - "type": "Class", - "name": "Calculator", - "attributes": [], - "methods": ["method-1"], - }, - "method-1": { - "type": "Method", - "name": "+ add(a: int, b: int): int", + "nodes": [ + { + "id": "class-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Calculator", "stereotype": None, + "attributes": [], + "methods": [ + {"id": "method-1", "name": "+ add(a: int, b: int): int"}, + ], + }, }, - }, - "relationships": {}, + ], + "edges": [], }, "generator": "python", } @@ -1141,32 +1212,40 @@ def test_generate_with_inheritance(self, client): payload = { "title": "InheritModel", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": { - "type": "Class", - "name": "Animal", - "attributes": ["attr-1"], - "methods": [], - }, - "attr-1": { - "type": "Attribute", - "name": "+ species: str", + "nodes": [ + { + "id": "class-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Animal", "stereotype": None, + "attributes": [ + {"id": "attr-1", "name": "species", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - "class-2": { - "type": "Class", - "name": "Dog", - "attributes": [], - "methods": [], + { + "id": "class-2", "type": "class", + "position": {"x": 0, "y": 200}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Dog", "stereotype": None, + "attributes": [], "methods": [], + }, }, - }, - "relationships": { - "rel-1": { + ], + "edges": [ + { + "id": "rel-1", + "source": "class-2", "target": "class-1", "type": "ClassInheritance", - "source": {"element": "class-2"}, - "target": {"element": "class-1"}, + "sourceHandle": "Top", "targetHandle": "Bottom", + "data": {"points": []}, }, - }, + ], }, "generator": "python", } @@ -1181,16 +1260,20 @@ def test_generate_abstract_class(self, client): payload = { "title": "AbstractModel", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": { - "type": "AbstractClass", - "name": "Shape", - "attributes": [], - "methods": [], + "nodes": [ + { + "id": "class-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Shape", "stereotype": "abstract", + "attributes": [], "methods": [], + }, }, - }, - "relationships": {}, + ], + "edges": [], }, "generator": "python", } @@ -1209,18 +1292,24 @@ def test_validate_duplicate_enumeration_literal(self, client): payload = { "title": "DupLiterals", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "enum-1": { - "type": "Enumeration", - "name": "Status", - "attributes": ["lit-1", "lit-2"], - "methods": [], + "nodes": [ + { + "id": "enum-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Status", "stereotype": "enumeration", + "attributes": [ + {"id": "lit-1", "name": "ACTIVE", "attributeType": "str", "visibility": "public"}, + {"id": "lit-2", "name": "ACTIVE", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - "lit-1": {"type": "EnumerationLiteral", "name": "ACTIVE"}, - "lit-2": {"type": "EnumerationLiteral", "name": "ACTIVE"}, - }, - "relationships": {}, + ], + "edges": [], }, } response = client.post("/besser_api/validate-diagram", json=payload) @@ -1234,17 +1323,23 @@ def test_validate_empty_enumeration_literal_name(self, client): payload = { "title": "EmptyLit", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "enum-1": { - "type": "Enumeration", - "name": "Status", - "attributes": ["lit-1"], - "methods": [], + "nodes": [ + { + "id": "enum-1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Status", "stereotype": "enumeration", + "attributes": [ + {"id": "lit-1", "name": "", "attributeType": "str", "visibility": "public"}, + ], + "methods": [], + }, }, - "lit-1": {"type": "EnumerationLiteral", "name": ""}, - }, - "relationships": {}, + ], + "edges": [], }, } response = client.post("/besser_api/validate-diagram", json=payload) @@ -1289,9 +1384,10 @@ def test_project_generation_missing_generator(self, client): { "title": "Main", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, } ], @@ -1313,9 +1409,10 @@ def test_project_generation_unsupported_generator(self, client): { "title": "Main", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, } ], @@ -1359,20 +1456,26 @@ def test_project_backend_generation_runs_nn_implemented_method(self, client): nn_model = json.load(f) class_model = { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "cls-classifier": { - "id": "cls-classifier", "name": "Classifier", "type": "Class", "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, - "attributes": [], "methods": ["meth-predict"], - }, - "meth-predict": { - "id": "meth-predict", "name": "+ predict(pixels: any): any", "type": "ClassMethod", - "owner": "cls-classifier", "bounds": {"x": 0, "y": 40, "width": 159, "height": 30}, - "implementationType": "neural_network", "neuralNetworkId": "nn-diagram-1", + "nodes": [ + { + "id": "cls-classifier", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": { + "name": "Classifier", "stereotype": None, "attributes": [], + "methods": [ + { + "id": "meth-predict", "name": "predict", "visibility": "public", + "parameters": [{"id": "p-pixels", "name": "pixels", "parameterType": "any"}], + "returnType": "any", "attributeType": "any", + "implementationType": "neural_network", "neuralNetworkId": "nn-diagram-1", + }, + ], + }, }, - }, - "relationships": {}, + ], + "edges": [], } payload = { "id": "proj-nn", @@ -1454,9 +1557,10 @@ async def fake_class_handler(*_args, **_kwargs): result = _run(dispatch.generate_from_diagram(DiagramInput( title="Deployment", model={ + "version": "4.0.0", "type": "DeploymentDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, generator="docker_compose", ))) @@ -1501,9 +1605,10 @@ async def fake_project_handler(*_args, **_kwargs): "docker_compose", "DeploymentDiagram", { + "version": "4.0.0", "type": "DeploymentDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, ) @@ -1535,9 +1640,10 @@ async def fake_project_handler(*_args, **_kwargs): "docker_compose", "DeploymentDiagram", { + "version": "4.0.0", "type": "DeploymentDiagram", - "elements": {}, - "relationships": {}, + "nodes": [], + "edges": [], }, ) @@ -1576,6 +1682,22 @@ async def fake_generate(diagram_input): assert result == "master-fallback" _DEPLOYMENT = { + "version": "4.0.0", + "type": "DeploymentDiagram", + "nodes": [ + {"id": "host", "type": "deploymentNode", "position": {"x": 0, "y": 0}, + "width": 300, "height": 200, + "data": {"name": "Host", "stereotype": "node", "isComponentHeaderShown": True}}, + {"id": "app", "type": "deploymentArtifact", "parentId": "host", + "position": {"x": 10, "y": 40}, "width": 160, "height": 40, + "data": {"name": "App", "manifests": []}}, + ], + "edges": [], + } + + # The same deployment in the legacy v3 editor shape, rejected with HTTP 400. + _DEPLOYMENT_V3 = { + "version": "3.0.0", "type": "DeploymentDiagram", "elements": { "host": {"id": "host", "name": "Host", "type": "DeploymentNode", "owner": None, @@ -1610,16 +1732,55 @@ def test_project_docker_compose_returns_zip_with_provenance(self, client): def test_project_docker_compose_reports_an_invalid_deployment_as_400(self, client): model = copy.deepcopy(self._DEPLOYMENT) - model["relationships"]["bad"] = { - "id": "bad", "name": "", "type": "DeploymentAssociation", "owner": None, - "source": {"element": "host"}, "target": {"element": "app"}, - } + model["edges"].append({ + "id": "bad", "type": "DeploymentAssociation", "source": "host", "target": "app", + "sourceHandle": "right", "targetHandle": "left", "data": {"points": []}, + }) project = self._project_input("docker_compose", "DeploymentDiagram", model) response = client.post("/besser_api/generate-output-from-project", json=project.model_dump(mode="json")) assert response.status_code == 400 assert "bad" in response.json()["detail"] + def test_single_docker_compose_rejects_a_legacy_v3_deployment(self, client): + response = client.post("/besser_api/generate-output", json={ + "title": "Deployment", "model": self._DEPLOYMENT_V3, "generator": "docker_compose", + }) + assert response.status_code == 400 + assert "legacy v3 editor format" in response.json()["detail"] + + def test_project_docker_compose_rejects_a_legacy_v3_deployment(self, client): + project = self._project_input("docker_compose", "DeploymentDiagram", self._DEPLOYMENT) + payload = project.model_dump(mode="json") + payload["diagrams"]["DeploymentDiagram"][0]["model"] = self._DEPLOYMENT_V3 + response = client.post("/besser_api/generate-output-from-project", json=payload) + assert response.status_code == 400 + assert "legacy v3 editor format" in response.json()["detail"] + + @pytest.mark.parametrize("diagram_type, element_type", [ + ("ComponentDiagram", "Component"), + ("DeploymentDiagram", "DeploymentNode"), + ]) + def test_validate_rejects_legacy_v3_component_and_deployment(self, client, diagram_type, element_type): + response = client.post("/besser_api/validate-diagram", json={ + "title": "Legacy", + "model": { + "version": "3.0.0", "type": diagram_type, + "elements": {"x": {"id": "x", "name": "X", "type": element_type, "owner": None, + "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}}}, + "relationships": {}, + }, + }) + assert response.status_code == 400 + assert "legacy v3 editor format" in response.json()["detail"] + + def test_validate_reads_a_v4_deployment(self, client): + response = client.post("/besser_api/validate-diagram", json={ + "title": "Deployment", "model": self._DEPLOYMENT, + }) + assert response.status_code == 200, response.text + assert response.json()["isValid"] is True, response.json() + def test_configuration_error_maps_to_500_with_its_message(self): from fastapi import HTTPException from besser.utilities.web_modeling_editor.backend.routers.error_handler import ( @@ -1681,7 +1842,7 @@ def _fake_call_openai_chat(*_args, **_kwargs): monkeypatch.setattr(gr, "call_openai_chat", _fake_call_openai_chat) payload = { - "userProfileModel": {"type": "UserDiagram", "elements": {}, "relationships": {}}, + "userProfileModel": {"version": "4.0.0", "type": "UserDiagram", "nodes": [], "edges": []}, "userProfileName": "Alice", "model": "gpt-5-mini", "currentConfig": {}, @@ -1724,7 +1885,7 @@ def test_recommend_agent_config_llm_parse_error_returns_500(self, client, monkey monkeypatch.setattr(gr, "call_openai_chat", lambda *_args, **_kwargs: "not-json") payload = { - "userProfileModel": {"type": "UserDiagram", "elements": {}, "relationships": {}}, + "userProfileModel": {"version": "4.0.0", "type": "UserDiagram", "nodes": [], "edges": []}, "userProfileName": "Alice", } response = client.post( @@ -1746,7 +1907,7 @@ def _raise_runtime_error(*_args, **_kwargs): monkeypatch.setattr(gr, "call_openai_chat", _raise_runtime_error) payload = { - "userProfileModel": {"type": "UserDiagram", "elements": {}, "relationships": {}}, + "userProfileModel": {"version": "4.0.0", "type": "UserDiagram", "nodes": [], "edges": []}, } response = client.post( "/besser_api/recommend-agent-config-llm", @@ -1786,7 +1947,7 @@ def _fake_manual_mapping(*_args, **_kwargs): monkeypatch.setattr(gr, "build_manual_mapping_recommendation", _fake_manual_mapping) payload = { - "userProfileModel": {"type": "UserDiagram", "elements": {}, "relationships": {}}, + "userProfileModel": {"version": "4.0.0", "type": "UserDiagram", "nodes": [], "edges": []}, "userProfileName": "Bob", "currentConfig": {}, } @@ -1822,45 +1983,53 @@ def test_recommend_agent_config_mapping_invalid_payload_returns_400(self, client @staticmethod def _build_user_profile_diagram_payload(age: int) -> Dict[str, Any]: - """Return a real UserDiagram JSON with a User root and a Personal_Information + """Return a real v4 UserDiagram with a User root and a Personal_Information child object holding ``age``. The reference user_buml_model.User class looks up children via the ``Personal_Information_end`` association, so the User class needs an instance with that attribute populating the ``age`` slot to drive the manual mapping rules deterministically. """ return { + "version": "4.0.0", "type": "UserDiagram", - "elements": { - "user-1": { - "id": "user-1", - "type": "UserModelName", - "name": "alice", - "className": "User", - "attributes": [], - }, - "pi-1": { - "id": "pi-1", - "type": "UserModelName", - "name": "alice_personal_info", - "className": "Personal_Information", - "attributes": ["pi-1-age"], + "nodes": [ + { + "id": "user-1", "type": "UserModelName", + "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "measured": {"width": 200, "height": 100}, + "data": { + "name": "alice", + "className": "User", + "attributes": [], + }, }, - "pi-1-age": { - "id": "pi-1-age", - "type": "UserModelAttribute", - "name": "age", - "attributeOperator": "==", - "attributeValue": str(age), + { + "id": "pi-1", "type": "UserModelName", + "position": {"x": 300, "y": 0}, "width": 200, "height": 100, + "measured": {"width": 200, "height": 100}, + "data": { + "name": "alice_personal_info", + "className": "Personal_Information", + "attributes": [ + { + "id": "pi-1-age", + "name": "age", + "attributeOperator": "==", + "attributeValue": str(age), + }, + ], + }, }, - }, - "relationships": { - "link-pi": { + ], + "edges": [ + { + "id": "link-pi", + "source": "user-1", "target": "pi-1", "type": "ObjectLink", - "name": "Personal_Information_end", - "source": {"element": "user-1"}, - "target": {"element": "pi-1"}, + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "Personal_Information_end", "points": []}, }, - }, + ], } def test_recommend_agent_config_mapping_end_to_end_no_llm(self, client, monkeypatch): @@ -2021,34 +2190,35 @@ class TestStandaloneChatbotDeploy: @staticmethod def _minimal_agent_diagram() -> Dict[str, Any]: - """Return a minimal valid AgentDiagram (StateInitialNode + AgentState - connected by AgentStateTransitionInit). Element ids are strings to - match the frontend's Apollon JSON shape. + """Return a minimal valid v4 AgentDiagram (StateInitialNode + AgentState + connected by AgentStateTransitionInit). """ return { + "version": "4.0.0", "type": "AgentDiagram", - "elements": { - "init-node": { - "id": "init-node", - "type": "StateInitialNode", - "name": "", + "nodes": [ + { + "id": "init-node", "type": "StateInitialNode", + "position": {"x": 0, "y": 0}, "width": 45, "height": 45, + "measured": {"width": 45, "height": 45}, + "data": {"name": ""}, }, - "state-1": { - "id": "state-1", - "type": "AgentState", - "name": "Greet", - "bodies": [], - "fallbackBodies": [], + { + "id": "state-1", "type": "AgentState", + "position": {"x": 100, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": {"name": "Greet", "bodies": [], "fallbackBodies": []}, }, - }, - "relationships": { - "trans-init": { + ], + "edges": [ + { + "id": "trans-init", + "source": "init-node", "target": "state-1", "type": "AgentStateTransitionInit", - "name": "", - "source": {"element": "init-node"}, - "target": {"element": "state-1"}, + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "", "points": []}, }, - }, + ], } def test_deploy_target_agent_invokes_chatbot_path(self, client, monkeypatch): @@ -2278,7 +2448,7 @@ def explode(*args, **kwargs): response = client.post("/besser_api/validate-diagram", json={ "title": "Diagram", - "model": {"type": "ClassDiagram", "elements": {}, "relationships": {}}, + "model": {"version": "4.0.0", "type": "ClassDiagram", "nodes": [], "edges": []}, }) assert response.status_code == 200 diff --git a/tests/utilities/web_modeling_editor/backend/test_association_class_rebinding.py b/tests/utilities/web_modeling_editor/backend/test_association_class_rebinding.py index 447079d36..998cd3aaa 100644 --- a/tests/utilities/web_modeling_editor/backend/test_association_class_rebinding.py +++ b/tests/utilities/web_modeling_editor/backend/test_association_class_rebinding.py @@ -25,41 +25,48 @@ ) -def _cls(eid, name, owner=None): - return {"id": eid, "name": name, "type": "Class", "attributes": [], "methods": [], - "owner": owner, "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}} +def _cls(eid, name): + """A v4 ``class`` node.""" + return {"id": eid, "type": "class", + "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": {"name": name, "stereotype": None, "attributes": [], "methods": []}} def _assoc(rid, name, src, tgt, rtype="ClassBidirectional", src_mult="1", tgt_mult="0..*"): - return {"id": rid, "name": name, "type": rtype, - "source": {"element": src, "multiplicity": src_mult, "role": ""}, - "target": {"element": tgt, "multiplicity": tgt_mult, "role": name}} + """A v4 association edge; the source role is left empty (class-name fallback).""" + return {"id": rid, "type": rtype, "source": src, "target": tgt, + "data": {"name": name, + "sourceRole": "", "sourceMultiplicity": src_mult, + "targetRole": name, "targetMultiplicity": tgt_mult, + "points": []}} + + +def _diagram(title, nodes, edges): + return {"title": title, + "model": {"version": "4.0.0", "type": "ClassDiagram", "nodes": nodes, "edges": edges}} @pytest.fixture def restaurant_shape(): """Order--MenuItem with OrderLine as the association class, AND OrderLine separately associated to both ends -- exactly what the agent produced.""" - return { - "title": "New_Project", - "model": { - "type": "ClassDiagram", - "elements": { - "c_order": _cls("c_order", "Order"), - "c_item": _cls("c_item", "MenuItem"), - "c_line": _cls("c_line", "OrderLine"), - }, - "relationships": { - "r_om": _assoc("r_om", "orderMenuItem", "c_order", "c_item"), - # the promotion: OrderLine is the association class of r_om - "r_link": {"id": "r_link", "name": "", "type": "ClassLinkRel", - "source": {"element": "c_line"}, - "target": {"element": "r_om"}}, - "r_lines": _assoc("r_lines", "lines", "c_line", "c_order"), - "r_ol": _assoc("r_ol", "orderLines_1", "c_item", "c_line"), - }, - }, - } + return _diagram( + "New_Project", + [ + _cls("c_order", "Order"), + _cls("c_item", "MenuItem"), + _cls("c_line", "OrderLine"), + ], + [ + _assoc("r_om", "orderMenuItem", "c_order", "c_item"), + # the promotion: OrderLine is the association class of r_om + # (v4: a ClassLinkRel edge from the class node to the association edge) + {"id": "r_link", "type": "ClassLinkRel", "source": "c_line", "target": "r_om", + "data": {"points": []}}, + _assoc("r_lines", "lines", "c_line", "c_order"), + _assoc("r_ol", "orderLines_1", "c_item", "c_line"), + ], + ) def _domain(payload): @@ -106,12 +113,8 @@ def test_exactly_one_OrderLine_object_is_reachable(restaurant_shape): def test_a_plain_diagram_is_untouched(): """No ClassLinkRel -> nothing to promote, nothing to rebind.""" - payload = { - "title": "Plain", - "model": {"type": "ClassDiagram", - "elements": {"a": _cls("a", "Book"), "b": _cls("b", "Author")}, - "relationships": {"r": _assoc("r", "writes", "a", "b")}}, - } + payload = _diagram("Plain", [_cls("a", "Book"), _cls("b", "Author")], + [_assoc("r", "writes", "a", "b")]) domain = _domain(payload) diff --git a/tests/utilities/web_modeling_editor/backend/test_code_reverse.py b/tests/utilities/web_modeling_editor/backend/test_code_reverse.py index d2144d90c..61b806652 100644 --- a/tests/utilities/web_modeling_editor/backend/test_code_reverse.py +++ b/tests/utilities/web_modeling_editor/backend/test_code_reverse.py @@ -157,7 +157,7 @@ async def post(): assert body["analysis"]["entities"] == ["Booking", "Room"] diagram = body["proposed_diagram"] assert diagram["diagramType"] == "ClassDiagram" and diagram["model"]["type"] == "ClassDiagram" - names = {e.get("name") for e in diagram["model"]["elements"].values() if e.get("type") == "Class"} + names = {n["data"]["name"] for n in diagram["model"]["nodes"] if n["type"] == "class"} assert names == {"Booking", "Room"} diff --git a/tests/utilities/web_modeling_editor/backend/test_deploy_app.py b/tests/utilities/web_modeling_editor/backend/test_deploy_app.py index 8e11f4565..065578b4c 100644 --- a/tests/utilities/web_modeling_editor/backend/test_deploy_app.py +++ b/tests/utilities/web_modeling_editor/backend/test_deploy_app.py @@ -20,12 +20,17 @@ "generator": "django", "config": {"project_name": "shop", "app_name": "store"}, "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "class-1": {"type": "Class", "name": "Book", "attributes": ["attr-1"], "methods": []}, - "attr-1": {"type": "Attribute", "name": "+ title: str"}, - }, - "relationships": {}, + "nodes": [{ + "id": "class-1", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": { + "name": "Book", + "attributes": [{"id": "attr-1", "name": "title", "attributeType": "str", "visibility": "public"}], + "methods": [], + }, + }], + "edges": [], }, } diff --git a/tests/utilities/web_modeling_editor/backend/test_deploy_live_urls.py b/tests/utilities/web_modeling_editor/backend/test_deploy_live_urls.py index b513a4782..d03c53678 100644 --- a/tests/utilities/web_modeling_editor/backend/test_deploy_live_urls.py +++ b/tests/utilities/web_modeling_editor/backend/test_deploy_live_urls.py @@ -15,11 +15,11 @@ AGENT_DIAGRAM = { "id": "ag1", "title": "Helper", "model": { - "type": "AgentDiagram", - "elements": {"init": {"id": "init", "type": "StateInitialNode", "name": ""}, - "s1": {"id": "s1", "type": "AgentState", "name": "Greet", "bodies": [], "fallbackBodies": []}}, - "relationships": {"t": {"type": "AgentStateTransitionInit", "name": "", - "source": {"element": "init"}, "target": {"element": "s1"}}}, + "version": "4.0.0", "type": "AgentDiagram", + # v4: the initial state is the ``data.initial`` flag (no init node or edge). + "nodes": [{"id": "s1", "type": "AgentState", "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": {"name": "Greet", "initial": True, "bodies": [], "fallbackBodies": []}}], + "edges": [], }, } diff --git a/tests/utilities/web_modeling_editor/backend/test_generator_filenames.py b/tests/utilities/web_modeling_editor/backend/test_generator_filenames.py index a01969589..83cd6052b 100644 --- a/tests/utilities/web_modeling_editor/backend/test_generator_filenames.py +++ b/tests/utilities/web_modeling_editor/backend/test_generator_filenames.py @@ -72,12 +72,15 @@ def test_supabase_download_keeps_the_migration_filename(tmp_path, monkeypatch): "title": "Library", "generator": "supabase", "model": { + "version": "4.0.0", "type": "ClassDiagram", - "elements": { - "c1": {"type": "Class", "name": "Book", "attributes": ["a1"], "methods": []}, - "a1": {"type": "Attribute", "name": "+ title: str"}, - }, - "relationships": {}, + "nodes": [{ + "id": "c1", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 70, + "data": {"name": "Book", "methods": [], "attributes": [ + {"id": "a1", "name": "title", "attributeType": "str", "visibility": "public"}, + ]}, + }], + "edges": [], }, } diff --git a/tests/utilities/web_modeling_editor/backend/test_github_repo_sync.py b/tests/utilities/web_modeling_editor/backend/test_github_repo_sync.py index 48649251e..42018390f 100644 --- a/tests/utilities/web_modeling_editor/backend/test_github_repo_sync.py +++ b/tests/utilities/web_modeling_editor/backend/test_github_repo_sync.py @@ -448,11 +448,10 @@ def test_the_sidebar_saves_the_one_model_file_and_drops_the_legacy_one(monkeypat def test_the_model_history_says_what_each_commit_changed_and_who_made_it(monkeypatch): with_loan = json.loads(json.dumps(CLASS_DIAGRAM_MODEL)) - loan_id = "loan-class" - with_loan["elements"][loan_id] = { - "id": loan_id, "name": "Loan", "type": "Class", "owner": None, - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, "attributes": [], "methods": [], - } + with_loan["nodes"].append({ + "id": "loan-class", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Loan", "attributes": [], "methods": []}, + }) fake = _SidebarGitHub(files_at={ (repo_model.MODEL_FILE, "2" * 40): json.dumps(_envelope(with_loan)), (repo_model.MODEL_FILE, "1" * 40): json.dumps(_envelope()), @@ -472,15 +471,18 @@ def test_the_model_history_says_what_each_commit_changed_and_who_made_it(monkeyp def _model_with_an_unknown_type() -> dict: """An attribute typed by an enumeration the model does not have.""" model = copy.deepcopy(CLASS_DIAGRAM_MODEL) - model["elements"]["attr-1"]["name"] = "+ kind: RoomType" + model["nodes"][0]["data"]["attributes"][0].update(name="kind", attributeType="RoomType") return model def _model_with_two_enumerations_of_one_name() -> dict: """Two enumerations left at the palette's default name, as in a repository of a live two-person test.""" model = copy.deepcopy(CLASS_DIAGRAM_MODEL) - for element_id in ("enum-1", "enum-2"): - model["elements"][element_id] = {"type": "Enumeration", "name": "Enumeration", "attributes": []} + for node_id in ("enum-1", "enum-2"): + model["nodes"].append({ + "id": node_id, "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Enumeration", "stereotype": "Enumeration", "attributes": [], "methods": []}, + }) return model @@ -489,7 +491,7 @@ def _as_the_editor_saves_it(class_model) -> dict: envelope = _envelope(class_model) envelope["project"]["diagrams"]["StateMachineDiagram"] = [{ "id": "sm1", "title": "Empty", - "model": {"type": "StateMachineDiagram", "elements": {}, "relationships": {}}, + "model": {"version": "4.0.0", "type": "StateMachineDiagram", "nodes": [], "edges": []}, }] envelope["project"]["currentDiagramIndices"]["StateMachineDiagram"] = 0 return envelope @@ -533,7 +535,10 @@ def test_the_history_does_not_call_a_version_after_an_unreadable_one_a_change(mo def test_the_history_still_lists_changes_beside_other_diagrams(monkeypatch): with_loan = copy.deepcopy(CLASS_DIAGRAM_MODEL) - with_loan["elements"]["loan-class"] = {"type": "Class", "name": "Loan", "attributes": [], "methods": []} + with_loan["nodes"].append({ + "id": "loan-class", "type": "class", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Loan", "attributes": [], "methods": []}, + }) newest, first = _history_changes( monkeypatch, json.dumps(_as_the_editor_saves_it(with_loan)), @@ -553,7 +558,7 @@ def test_a_pull_request_does_not_list_an_unreadable_head_as_removals(): def test_deleting_every_class_is_still_listed_as_removals(): - empty = {"type": "ClassDiagram", "elements": {}, "relationships": {}} + empty = {"version": "4.0.0", "type": "ClassDiagram", "nodes": [], "edges": []} assert "class Author removed" in repo_model.describe_change( _as_the_editor_saves_it(CLASS_DIAGRAM_MODEL), _as_the_editor_saves_it(empty) ) @@ -736,7 +741,8 @@ def test_the_link_file_lists_each_diagram_with_its_hash_and_buml_source(): diagram each came from, or which diagrams have none.""" from besser.utilities.web_modeling_editor.backend.services.spec_driven.model_assembly import diagram_sha256 envelope = _envelope() - envelope["project"]["diagrams"]["ObjectDiagram"] = [{"id": "od1", "title": "Books", "model": {"elements": {}}}] + books = {"version": "4.0.0", "type": "ObjectDiagram", "nodes": [], "edges": []} + envelope["project"]["diagrams"]["ObjectDiagram"] = [{"id": "od1", "title": "Books", "model": books}] link = json.loads(repo_model.model_files(envelope)[repo_model.LINK_FILE]) @@ -744,7 +750,7 @@ def test_the_link_file_lists_each_diagram_with_its_hash_and_buml_source(): assert link["diagrams"] == [ {"type": "ClassDiagram", "id": "cd1", "title": "Library", "sha256": diagram_sha256(CLASS_DIAGRAM_MODEL), "buml_source": "buml/domain_model.py"}, - {"type": "ObjectDiagram", "id": "od1", "title": "Books", "sha256": diagram_sha256({"elements": {}}), + {"type": "ObjectDiagram", "id": "od1", "title": "Books", "sha256": diagram_sha256(books), "buml_source": None}, ] diff --git a/tests/utilities/web_modeling_editor/backend/test_github_round_trip.py b/tests/utilities/web_modeling_editor/backend/test_github_round_trip.py index ac919932c..db940a7e5 100644 --- a/tests/utilities/web_modeling_editor/backend/test_github_round_trip.py +++ b/tests/utilities/web_modeling_editor/backend/test_github_round_trip.py @@ -240,9 +240,13 @@ def test_a_branch_past_the_first_page_is_pushed_to(github): def _with_class(model: dict, name: str, attribute: str = "id: int") -> dict: """``model`` plus class ``name``, as the editor adds one.""" model = json.loads(json.dumps(model)) - class_id, attr_id = f"class-{name.lower()}", f"attr-{name.lower()}" - model["elements"][class_id] = {"type": "Class", "name": name, "attributes": [attr_id], "methods": []} - model["elements"][attr_id] = {"type": "Attribute", "name": f"+ {attribute}"} + attr_name, attr_type = (part.strip() for part in attribute.split(":")) + model["nodes"].append({ + "id": f"class-{name.lower()}", "type": "class", "position": {"x": 0, "y": 200}, "width": 160, "height": 100, + "data": {"name": name, "methods": [], "attributes": [{ + "id": f"attr-{name.lower()}", "name": attr_name, "attributeType": attr_type, "visibility": "public", + }]}, + }) return model @@ -270,8 +274,8 @@ def _save(model, base_sha: str) -> httpx.Response: def _saved_classes(github, repo) -> set[str]: saved = json.loads(github.files(repo)[repo_model.MODEL_FILE][1]) - elements = saved["project"]["diagrams"]["ClassDiagram"][0]["model"]["elements"] - return {e["name"] for e in elements.values() if e["type"] == "Class"} + nodes = saved["project"]["diagrams"]["ClassDiagram"][0]["model"]["nodes"] + return {n["data"]["name"] for n in nodes if n["type"] == "class"} def test_two_people_adding_different_classes_both_keep_theirs(github): @@ -369,7 +373,7 @@ def test_the_sync_status_says_whose_account_a_commit_is_and_whether_it_is_a_merg def _renamed(model: dict, element_id: str, name: str) -> dict: model = json.loads(json.dumps(model)) - model["elements"][element_id]["name"] = name + next(n for n in model["nodes"] if n["id"] == element_id)["data"]["name"] = name return model @@ -384,7 +388,8 @@ def test_two_people_renaming_the_same_class_is_a_conflict_kept_for_a_pull_reques assert github.ref(repo, "main") == theirs # nothing landed on the branch side = r.json()["conflict_branch"] on_side = json.loads(github.files(repo, side)[repo_model.MODEL_FILE][1]) - assert on_side["project"]["diagrams"]["ClassDiagram"][0]["model"]["elements"]["class-1"]["name"] == "Creator" + side_nodes = on_side["project"]["diagrams"]["ClassDiagram"][0]["model"]["nodes"] + assert next(n for n in side_nodes if n["id"] == "class-1")["data"]["name"] == "Creator" assert not any(b.startswith("besser/sync-merge-") or b.startswith("besser/sync-code-") for b in github.out(repo, "for-each-ref", "--format=%(refname:lstrip=2)").split()) @@ -780,11 +785,9 @@ def generate(self): monkeypatch.setattr(github_deploy_api, "get_generator_info", lambda _name: SimpleNamespace(generator_class=_Generator)) agent = { "id": "ag1", "title": "Helper", "model": { - "type": "AgentDiagram", - "elements": {"init": {"id": "init", "type": "StateInitialNode", "name": ""}, - "s1": {"id": "s1", "type": "AgentState", "name": "Greet", "bodies": [], "fallbackBodies": []}}, - "relationships": {"t": {"type": "AgentStateTransitionInit", "name": "", - "source": {"element": "init"}, "target": {"element": "s1"}}}, + "version": "4.0.0", "type": "AgentDiagram", "edges": [], "components": {}, + "nodes": [{"id": "s1", "type": "AgentState", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Greet", "initial": True, "bodies": [], "fallbackBodies": []}}], }, "configYaml": f"nlp:\n openai:\n api_key: {key}\n", } @@ -1312,11 +1315,9 @@ def generate(self): monkeypatch.setattr(github_deploy_api, "get_generator_info", lambda _name: SimpleNamespace(generator_class=_Generator)) agent = { "id": "ag1", "title": "Helper", "model": { - "type": "AgentDiagram", - "elements": {"init": {"id": "init", "type": "StateInitialNode", "name": ""}, - "s1": {"id": "s1", "type": "AgentState", "name": "Greet", "bodies": [], "fallbackBodies": []}}, - "relationships": {"t": {"type": "AgentStateTransitionInit", "name": "", - "source": {"element": "init"}, "target": {"element": "s1"}}}, + "version": "4.0.0", "type": "AgentDiagram", "edges": [], "components": {}, + "nodes": [{"id": "s1", "type": "AgentState", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Greet", "initial": True, "bodies": [], "fallbackBodies": []}}], }, } export = _envelope() @@ -1469,9 +1470,9 @@ def test_a_spec_driven_push_credits_what_it_adds_to_whoever_pushes(github): assert r.status_code == 200, r.text project = json.loads(github.files(repo)[repo_model.MODEL_FILE][1])["project"] records = project["attribution"] - elements = project["diagrams"]["ClassDiagram"][0]["model"]["elements"] - assert [elements[element]["name"] for element in records] == ["Loan"] - assert [record["addedBy"] for record in records.values()] == ["ben"] + # React Flow keeps an attribute as a row of its class, and the row is credited with the class. + assert set(records) == {"class-loan", "attr-loan"} + assert {record["addedBy"] for record in records.values()} == {"ben"} def test_the_import_names_who_changed_which_files_since_the_last_run(github): @@ -1539,11 +1540,9 @@ def generate(self): lambda _name: SimpleNamespace(generator_class=_Generator)) repo = _repo_with_a_run_record(github, tmp_path) agent = {"id": "ag1", "title": "Helper", "model": { - "type": "AgentDiagram", - "elements": {"init": {"id": "init", "type": "StateInitialNode", "name": ""}, - "s1": {"id": "s1", "type": "AgentState", "name": "Greet", "bodies": [], "fallbackBodies": []}}, - "relationships": {"t": {"type": "AgentStateTransitionInit", "name": "", - "source": {"element": "init"}, "target": {"element": "s1"}}}, + "version": "4.0.0", "type": "AgentDiagram", "edges": [], "components": {}, + "nodes": [{"id": "s1", "type": "AgentState", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Greet", "initial": True, "bodies": [], "fallbackBodies": []}}], }} r = _call("POST", "/besser_api/github/deploy-webapp", headers=SESSION, json={ "name": "Helper", "diagrams": {"AgentDiagram": [agent]}, "currentDiagramIndices": {"AgentDiagram": 0}, @@ -1633,11 +1632,9 @@ def generate(self): if path.startswith(".agent-trace/") or path == ".besser_attribution.json"} _unreadable_records(monkeypatch, failure) agent = {"id": "ag1", "title": "Helper", "model": { - "type": "AgentDiagram", - "elements": {"init": {"id": "init", "type": "StateInitialNode", "name": ""}, - "s1": {"id": "s1", "type": "AgentState", "name": "Greet", "bodies": [], "fallbackBodies": []}}, - "relationships": {"t": {"type": "AgentStateTransitionInit", "name": "", - "source": {"element": "init"}, "target": {"element": "s1"}}}, + "version": "4.0.0", "type": "AgentDiagram", "edges": [], "components": {}, + "nodes": [{"id": "s1", "type": "AgentState", "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Greet", "initial": True, "bodies": [], "fallbackBodies": []}}], }} with caplog.at_level("WARNING"): r = _call("POST", "/besser_api/github/deploy-webapp", headers=SESSION, json={ diff --git a/tests/utilities/web_modeling_editor/backend/test_inter_diagram_export_e2e.py b/tests/utilities/web_modeling_editor/backend/test_inter_diagram_export_e2e.py index ca20c3413..d32ea09cb 100644 --- a/tests/utilities/web_modeling_editor/backend/test_inter_diagram_export_e2e.py +++ b/tests/utilities/web_modeling_editor/backend/test_inter_diagram_export_e2e.py @@ -14,8 +14,7 @@ ``project_builder.py`` that emits BPMN + Component + Deployment sections into a single executable ``project.py``. -The payloads mirror the real-export wire shape used by the converter unit -tests. They are kept inline so the test is self-contained and CI-safe while +The payloads use the v4 wire shape (``{nodes, edges}``) the editor sends. They are kept inline so the test is self-contained and CI-safe while still exercising the same shape as real WME exports. Async/ASGI harness mirrors ``test_api_integration.py`` (the installed @@ -82,47 +81,66 @@ def _isolate_artifacts(tmp_path, monkeypatch): # Wire-shape fixtures (mirror the converter unit-test fixtures) # --------------------------------------------------------------------------- +def _by_id(items: list) -> dict: + return {item["id"]: item for item in items} + + +def _data_of(model: dict, item_id: str) -> dict: + """The ``data`` of the node or edge ``item_id`` of a v4 model.""" + return {**_by_id(model["nodes"]), **_by_id(model["edges"])}[item_id]["data"] + + +def _interface(node_id: str) -> dict: + return {"id": node_id, "type": "componentInterface", "position": {"x": 700, "y": 100}, + "width": 20, "height": 20, "data": {"name": node_id}} + + +def _component_edge(edge_id: str, edge_type: str, source: str, target: str, **data) -> dict: + return {"id": edge_id, "type": edge_type, "source": source, "target": target, + "data": {"name": "", "points": [], **data}} + + def _component_diagram() -> dict: """Agentic Component diagram: a Subsystem holding two agents, a `solution` agent submitting to a `supervision` agent.""" return { "title": "Component Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "ComponentDiagram", "size": {"width": 1400, "height": 740}, - "elements": { - "grp": { - "id": "grp", "name": "ConsensusGroup", "type": "Subsystem", - "owner": None, - "bounds": {"x": 100, "y": 100, "width": 520, "height": 280}, - "stereotype": "subsystem", "displayStereotype": True, + "nodes": [ + { + "id": "grp", "type": "componentSubsystem", + "position": {"x": 100, "y": 100}, "width": 520, "height": 280, + "data": {"name": "ConsensusGroup", "stereotype": "subsystem", + "isComponentSubsystemHeaderShown": True}, }, - "orch": { - "id": "orch", "name": "OrchestratorAgent", "type": "Component", - "owner": "grp", - "bounds": {"x": 140, "y": 180, "width": 160, "height": 80}, - "stereotype": "solution", "displayStereotype": True, + { + "id": "orch", "type": "component", "parentId": "grp", + "position": {"x": 40, "y": 80}, "width": 160, "height": 80, + "data": {"name": "OrchestratorAgent", "stereotype": "solution", + "isComponentHeaderShown": True}, }, - "worker": { - "id": "worker", "name": "WorkerAgent", "type": "Component", - "owner": "grp", - "bounds": {"x": 420, "y": 180, "width": 160, "height": 80}, - "stereotype": "supervision", "displayStereotype": True, + { + "id": "worker", "type": "component", "parentId": "grp", + "position": {"x": 320, "y": 80}, "width": 160, "height": 80, + "data": {"name": "WorkerAgent", "stereotype": "supervision", + "isComponentHeaderShown": True}, }, - }, - "relationships": { - "rel": { - "id": "rel", "name": "", "type": "ComponentDependency", - "owner": None, - "bounds": {"x": 300, "y": 220, "width": 120, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 120, "y": 0}], - "source": {"element": "orch", "direction": "Right"}, - "target": {"element": "worker", "direction": "Left"}, - "isManuallyLayouted": False, - "stereotype": "submits", + ], + "edges": [ + { + "id": "rel", "type": "ComponentDependency", + "source": "orch", "target": "worker", + "sourceHandle": "right", "targetHandle": "left", + "data": { + "name": "", "label": "", "isManuallyLayouted": False, + "points": [{"x": 300, "y": 220}, {"x": 420, "y": 220}], + "stereotype": "submits", + }, }, - }, + ], "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, }, @@ -135,56 +153,48 @@ def _deployment_diagram() -> dict: return { "title": "Deployment Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "DeploymentDiagram", "size": {"width": 1040, "height": 640}, - "elements": { - "n1": { - "id": "n1", "name": "EdgeDevice", "type": "DeploymentNode", - "owner": None, - "bounds": {"x": -500, "y": -300, "width": 440, "height": 340}, - "stereotype": "device", "displayStereotype": True, + "nodes": [ + { + "id": "n1", "type": "deploymentNode", + "position": {"x": -500, "y": -300}, "width": 440, "height": 340, + "data": {"name": "EdgeDevice", "stereotype": "device", + "isComponentHeaderShown": True}, }, - "a1": { - "id": "a1", "name": "agent-runtime [3]", - "type": "DeploymentArtifact", - "owner": "n1", - "bounds": {"x": -450, "y": -200, "width": 160, "height": 40}, + { + "id": "a1", "type": "deploymentArtifact", "parentId": "n1", + "position": {"x": 50, "y": 100}, "width": 160, "height": 40, + "data": {"name": "agent-runtime [3]"}, }, - "n2": { - "id": "n2", "name": "LLMHost", "type": "DeploymentNode", - "owner": None, - "bounds": {"x": 230, "y": 0, "width": 160, "height": 100}, - "stereotype": "executionEnvironment external", - "displayStereotype": True, + { + "id": "n2", "type": "deploymentNode", + "position": {"x": 230, "y": 0}, "width": 160, "height": 100, + "data": {"name": "LLMHost", "stereotype": "executionEnvironment external", + "isComponentHeaderShown": True}, }, - }, - "relationships": { + ], + "edges": [ # Explicit artifact -> node edge: carries the `[3]` multiplicity # (parsed off the artifact name onto the DeploymentRelation). - "r-deploys": { - "id": "r-deploys", "name": "", "type": "DeploymentAssociation", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 1, "height": 120}, - "path": [{"x": 0, "y": 0}, {"x": 0, "y": 120}], - "source": {"direction": "Down", "element": "a1"}, - "target": {"direction": "Down", "element": "n1"}, - "isManuallyLayouted": False, - "stereotype": "", + { + "id": "r-deploys", "type": "DeploymentAssociation", + "source": "a1", "target": "n1", + "sourceHandle": "bottom", "targetHandle": "bottom", + "data": {"name": "", "stereotype": "", "isManuallyLayouted": False, + "points": [{"x": 0, "y": 0}, {"x": 0, "y": 120}]}, }, # Node <-> node edge: becomes a CommunicationPath, `HTTPS` rides # through as a free-form stereotype. - "r-comm": { - "id": "r-comm", "name": "", "type": "DeploymentAssociation", - "owner": None, - "bounds": {"x": 0, "y": 0, "width": 290, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 290, "y": 0}], - "source": {"direction": "Downright", "element": "n1"}, - "target": {"direction": "Left", "element": "n2"}, - "isManuallyLayouted": False, - "stereotype": "HTTPS", + { + "id": "r-comm", "type": "DeploymentAssociation", + "source": "n1", "target": "n2", + "sourceHandle": "right-bottom", "targetHandle": "left", + "data": {"name": "", "stereotype": "HTTPS", "isManuallyLayouted": False, + "points": [{"x": 0, "y": 0}, {"x": 290, "y": 0}]}, }, - }, + ], "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, }, @@ -193,41 +203,36 @@ def _deployment_diagram() -> dict: def _bpmn_diagram() -> dict: """Pool-less BPMN process: StartEvent -> Task -> EndEvent.""" - def _node(eid, typ, name, **extra): - base = { - "id": eid, "name": name, "type": typ, "owner": None, - "bounds": {"x": 100, "y": 100, "width": 110, "height": 60}, + def _node(eid, typ, name, **data): + return { + "id": eid, "type": typ, + "position": {"x": 100, "y": 100}, "width": 110, "height": 60, + "data": {"name": name, **data}, } - base.update(extra) - return base def _flow(rid, src, tgt): return { - "id": rid, "name": "", "type": "BPMNFlow", "owner": None, - "bounds": {"x": 0, "y": 0, "width": 100, "height": 1}, - "path": [{"x": 0, "y": 0}, {"x": 100, "y": 0}], - "source": {"element": src, "direction": "Right", - "bounds": {"x": 0, "y": 0, "width": 0, "height": 0}}, - "target": {"element": tgt, "direction": "Left", - "bounds": {"x": 100, "y": 0, "width": 0, "height": 0}}, - "isManuallyLayouted": False, "flowType": "sequence", "isDefault": False, + "id": rid, "type": "BPMNSequenceFlow", "source": src, "target": tgt, + "sourceHandle": "right", "targetHandle": "left", + "data": {"name": "", "isManuallyLayouted": False, "isDefault": False, + "points": [{"x": 0, "y": 0}, {"x": 100, "y": 0}]}, } return { "title": "BPMN Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "BPMNDiagram", "size": {"width": 1400, "height": 700}, - "elements": { - "s1": _node("s1", "BPMNStartEvent", "go", eventType="default"), - "t1": _node("t1", "BPMNTask", "Review", taskType="user", marker="none"), - "e1": _node("e1", "BPMNEndEvent", "done", eventType="default"), - }, - "relationships": { - "f1": _flow("f1", "s1", "t1"), - "f2": _flow("f2", "t1", "e1"), - }, + "nodes": [ + _node("s1", "bpmnStartEvent", "go", eventType="default"), + _node("t1", "bpmnTask", "Review", taskType="user", marker="none"), + _node("e1", "bpmnEndEvent", "done", eventType="default"), + ], + "edges": [ + _flow("f1", "s1", "t1"), + _flow("f2", "t1", "e1"), + ], "interactive": {"elements": {}, "relationships": {}}, "assessments": {}, }, @@ -261,18 +266,13 @@ def _project_payload() -> dict: def test_validation_collects_role_and_ambiguous_binding_errors(): diagram = _component_diagram() model = diagram["model"] - model["relationships"]["rel"]["stereotype"] = "supervises" - model["elements"]["tool"] = {"type": "Component", "name": "Search", "stereotype": "tool"} - model["relationships"]["uses"] = { - "type": "ComponentDependency", "stereotype": "uses", - "source": {"element": "orch"}, "target": {"element": "tool"}, - } + _data_of(model, "rel")["stereotype"] = "supervises" + model["nodes"].append({"id": "tool", "type": "component", "position": {"x": 700, "y": 300}, + "width": 160, "height": 80, "data": {"name": "Search", "stereotype": "tool"}}) + model["edges"].append(_component_edge("uses", "ComponentDependency", "orch", "tool", stereotype="uses")) for iface in ("query", "index"): - model["elements"][iface] = {"type": "ComponentInterface", "name": iface} - model["relationships"]["provides-" + iface] = { - "type": "ComponentInterfaceProvided", - "source": {"element": "tool"}, "target": {"element": iface}, - } + model["nodes"].append(_interface(iface)) + model["edges"].append(_component_edge("provides-" + iface, "ComponentProvidedInterface", "tool", iface)) response = _post(f"{API}/validate-diagram", json=diagram) assert response.status_code == 200, response.text result = response.json() @@ -282,12 +282,30 @@ def test_validation_collects_role_and_ambiguous_binding_errors(): class TestExportBumlSingleDiagram: + @pytest.mark.parametrize("diagram_type, element_type", [ + ("ComponentDiagram", "Component"), + ("DeploymentDiagram", "DeploymentNode"), + ]) + def test_legacy_v3_diagram_is_rejected(self, diagram_type, element_type): + legacy = { + "title": "Legacy", + "model": { + "version": "3.0.0", "type": diagram_type, + "elements": {"x": {"id": "x", "name": "X", "type": element_type, "owner": None, + "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}}}, + "relationships": {}, + }, + } + resp = _post(f"{API}/export-buml", json=legacy) + assert resp.status_code == 400 + assert "legacy v3 editor format" in resp.json()["detail"] + @pytest.mark.parametrize("direction", [None, "directed", "reciprocal"], ids=["legacy", "directed", "reciprocal"]) def test_collaboration_retains_one_relationship_and_its_id_through_buml(self, direction): diagram = _component_diagram() model = diagram["model"] - model["elements"]["worker"]["stereotype"] = "solution" - edge = model["relationships"]["rel"] + _data_of(model, "worker")["stereotype"] = "solution" + edge = _data_of(model, "rel") edge["stereotype"] = "collaborates" if direction is not None: edge["collaborationDirection"] = direction @@ -308,20 +326,20 @@ def test_collaboration_retains_one_relationship_and_its_id_through_buml(self, di result = imported.json() assert result["diagramType"] == "ComponentDiagram" rebuilt = result["model"] - assert rebuilt["elements"]["orch"]["stereotype"] == "solution" - assert rebuilt["elements"]["worker"]["stereotype"] == "solution" - assert rebuilt["relationships"] == model["relationships"] + assert _data_of(rebuilt, "orch")["stereotype"] == "solution" + assert _data_of(rebuilt, "worker")["stereotype"] == "solution" + assert _by_id(rebuilt["edges"]) == _by_id(model["edges"]) def test_reverse_collaboration_duplicate_is_rejected_by_validation_and_export(self): diagram = _component_diagram() model = diagram["model"] - model["elements"]["worker"]["stereotype"] = "solution" - edge = model["relationships"]["rel"] - edge.update(stereotype="collaborates", collaborationDirection="directed") - model["relationships"]["reverse"] = { + _data_of(model, "worker")["stereotype"] = "solution" + edge = _by_id(model["edges"])["rel"] + edge["data"].update(stereotype="collaborates", collaborationDirection="directed") + model["edges"].append({ **edge, "id": "reverse", "source": edge["target"], "target": edge["source"], - "collaborationDirection": "reciprocal", - } + "data": {**edge["data"], "collaborationDirection": "reciprocal"}, + }) validation = _post(f"{API}/validate-diagram", json=diagram) assert validation.status_code == 200, validation.text @@ -336,7 +354,7 @@ def test_reverse_collaboration_duplicate_is_rejected_by_validation_and_export(se def test_missing_agentic_endpoint_is_reported_by_validation_and_export(self): diagram = _component_diagram() - diagram["model"]["relationships"]["rel"]["target"]["element"] = "missing-worker" + _by_id(diagram["model"]["edges"])["rel"]["target"] = "missing-worker" validation = _post(f"{API}/validate-diagram", json=diagram) assert validation.status_code == 200, validation.text assert not validation.json()["isValid"] @@ -398,16 +416,12 @@ def test_project_with_three_diagram_families_reconstructs(self): component = project["diagrams"]["ComponentDiagram"][0]["model"] binding = {"required": "query", "provided": "read"} for node in ("query", "read", "write"): - component["elements"][node] = {"type": "ComponentInterface", "name": node} + component["nodes"].append(_interface(node)) for iface, owner, kind in (("query", "orch", "Required"), ("read", "grp", "Provided"), ("write", "grp", "Provided")): - component["relationships"]["owner-" + iface] = { - "type": "ComponentInterface" + kind, "source": {"element": owner}, "target": {"element": iface}, - } - component["relationships"]["use-group"] = { - "type": "ComponentDependency", "stereotype": "uses", "source": {"element": "orch"}, - "target": {"element": "grp"}, "interfaceBinding": binding, - } + component["edges"].append(_component_edge("owner-" + iface, f"Component{kind}Interface", owner, iface)) + component["edges"].append(_component_edge("use-group", "ComponentDependency", "orch", "grp", + stereotype="uses", interfaceBinding=binding)) resp = _post(f"{API}/export-project-as-buml", json=project) assert resp.status_code == 200, resp.text source = resp.text @@ -435,16 +449,16 @@ def test_project_with_three_diagram_families_reconstructs(self): assert component_model["type"] == "ComponentDiagram" assert deployment_model["type"] == "DeploymentDiagram" - assert component_model["elements"] - assert component_model["relationships"]["use-group"]["interfaceBinding"] == binding - assert deployment_model["elements"] + assert component_model["nodes"] + assert _by_id(component_model["edges"])["use-group"]["data"]["interfaceBinding"] == binding + assert deployment_model["nodes"] def test_role_violation_names_its_agents_in_the_project_export_error(self): # Diagrams drawn before the role rules can hold «supervises» between two solution agents. project = _project_payload() component = project["diagrams"]["ComponentDiagram"][0]["model"] - component["elements"]["worker"]["stereotype"] = "solution" - component["relationships"]["rel"]["stereotype"] = "supervises" + _data_of(component, "worker")["stereotype"] = "solution" + _data_of(component, "rel")["stereotype"] = "supervises" resp = _post(f"{API}/export-project-as-buml", json=project) assert resp.status_code == 400, resp.text diff --git a/tests/utilities/web_modeling_editor/backend/test_kg_complex_pipeline.py b/tests/utilities/web_modeling_editor/backend/test_kg_complex_pipeline.py index 1e0322392..099cd1da0 100644 --- a/tests/utilities/web_modeling_editor/backend/test_kg_complex_pipeline.py +++ b/tests/utilities/web_modeling_editor/backend/test_kg_complex_pipeline.py @@ -75,8 +75,7 @@ def test_class_diagram_with_all_accepts(client, kg_payload: dict): assert resp.status_code == 200, resp.text body = resp.json() assert body["diagramType"] == "ClassDiagram" - elements = body["model"]["elements"] - class_names = {e["name"] for e in elements.values() if e.get("type") == "Class"} + class_names = {n["data"]["name"] for n in body["model"]["nodes"] if n["type"] == "class"} # Person and Pet survive; Thing exists because :likes was attached to it. assert "Person" in class_names assert "Pet" in class_names @@ -95,8 +94,7 @@ def test_class_diagram_with_skip_drops_property(client, kg_payload: dict): ) assert resp.status_code == 200, resp.text body = resp.json() - relationships = body["model"]["relationships"] - rel_names = {r.get("name") for r in relationships.values()} + rel_names = {e["data"].get("name") for e in body["model"]["edges"]} assert "likes" not in rel_names diff --git a/tests/utilities/web_modeling_editor/backend/test_kg_export_endpoint.py b/tests/utilities/web_modeling_editor/backend/test_kg_export_endpoint.py index 12fa3e973..580473e3a 100644 --- a/tests/utilities/web_modeling_editor/backend/test_kg_export_endpoint.py +++ b/tests/utilities/web_modeling_editor/backend/test_kg_export_endpoint.py @@ -77,9 +77,9 @@ def test_export_kg_rejects_non_kg_payload(client): "title": "NotKG", "model": { "type": "ClassDiagram", - "version": "1.0.0", - "elements": {}, - "relationships": {}, + "version": "4.0.0", + "nodes": [], + "edges": [], }, } resp = client.post("/besser_api/kg/export/ttl", json=class_payload) diff --git a/tests/utilities/web_modeling_editor/backend/test_kg_preflight_endpoint.py b/tests/utilities/web_modeling_editor/backend/test_kg_preflight_endpoint.py index e0e38b657..5680017de 100644 --- a/tests/utilities/web_modeling_editor/backend/test_kg_preflight_endpoint.py +++ b/tests/utilities/web_modeling_editor/backend/test_kg_preflight_endpoint.py @@ -139,8 +139,7 @@ def test_class_diagram_with_accept_decision(client): assert resp.status_code == 200, resp.text body = resp.json() # Thing class should be present after attach_to_thing. - elements = body["model"]["elements"] - class_names = {e["name"] for e in elements.values() if e.get("type") == "Class"} + class_names = {n["data"]["name"] for n in body["model"]["nodes"] if n["type"] == "class"} assert "Thing" in class_names @@ -174,7 +173,7 @@ def test_class_diagram_with_skip_decision(client): resp = client.post("/besser_api/kg/to-class-diagram", json=payload2) assert resp.status_code == 200, resp.text body = resp.json() - rel_types = {r.get("name") for r in body["model"]["relationships"].values()} + rel_types = {e["data"].get("name") for e in body["model"]["edges"]} assert "likes" not in rel_types # property dropped diff --git a/tests/utilities/web_modeling_editor/backend/test_kg_to_diagrams_endpoints.py b/tests/utilities/web_modeling_editor/backend/test_kg_to_diagrams_endpoints.py index 013afdf76..81bb0d879 100644 --- a/tests/utilities/web_modeling_editor/backend/test_kg_to_diagrams_endpoints.py +++ b/tests/utilities/web_modeling_editor/backend/test_kg_to_diagrams_endpoints.py @@ -60,12 +60,12 @@ def test_class_endpoint_returns_class_diagram(client, kg_payload: dict): body = response.json() assert body["diagramType"] == "ClassDiagram" assert body["model"]["type"] == "ClassDiagram" - elements = body["model"]["elements"] - relationships = body["model"]["relationships"] - types = {e["type"] for e in elements.values()} - assert "Class" in types - assert "ClassAttribute" in types - rel_types = {r["type"] for r in relationships.values()} + nodes = body["model"]["nodes"] + edges = body["model"]["edges"] + classes = [n for n in nodes if n["type"] == "class"] + assert classes + assert any(n["data"]["attributes"] for n in classes) + rel_types = {e["type"] for e in edges} # Plain associations are emitted as ClassBidirectional; navigability is # carried by the explicit per-end "navigable" flags rather than by the # relationship type. A plain owl:ObjectProperty is navigable @@ -73,10 +73,10 @@ def test_class_endpoint_returns_class_diagram(client, kg_payload: dict): # becomes navigable when (and only when) owl:inverseOf names it. assert "ClassBidirectional" in rel_types # worksFor association assert "ClassInheritance" in rel_types # Employee → Person - assoc = next(r for r in relationships.values() if r["type"] == "ClassBidirectional") - assert [assoc["source"]["navigable"], assoc["target"]["navigable"]].count(True) == 1 - assert assoc["target"]["role"] == "worksFor" - assert assoc["target"]["navigable"] is True + assoc = next(e["data"] for e in edges if e["type"] == "ClassBidirectional") + assert [assoc["sourceNavigable"], assoc["targetNavigable"]].count(True) == 1 + assert assoc["targetRole"] == "worksFor" + assert assoc["targetNavigable"] is True def test_endpoints_reject_non_kg_payload(client): @@ -133,8 +133,6 @@ def test_class_endpoint_emits_ocl_constraint_for_constraint_bearing_kg(client): response = client.post("/besser_api/kg/to-class-diagram", json=payload) assert response.status_code == 200, response.text body = response.json() - elements = body["model"]["elements"] - types = {e["type"] for e in elements.values()} - assert "ClassOCLConstraint" in types - ocl_texts = [e["constraint"] for e in elements.values() if e["type"] == "ClassOCLConstraint"] + ocl_texts = [n["data"]["expression"] for n in body["model"]["nodes"] if n["type"] == "ClassOCLConstraint"] + assert ocl_texts assert any("self.name" in c for c in ocl_texts) diff --git a/tests/utilities/web_modeling_editor/backend/test_layout_preserving_import.py b/tests/utilities/web_modeling_editor/backend/test_layout_preserving_import.py new file mode 100644 index 000000000..cd38fd3f7 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/test_layout_preserving_import.py @@ -0,0 +1,77 @@ +"""/get-json-model with ``existing_model``: a re-imported B-UML file keeps the diagram's layout (issue #774).""" + +import json + +from besser.BUML.metamodel.state_machine.agent import Agent +from besser.utilities.buml_code_builder.agent_model_builder import agent_model_to_code + +URL = "/besser_api/get-json-model" + +# An agent written with keyword arguments, as people (and LLMs) write B-UML by hand. +# The agent parser reads the exporter's positional form only. +KEYWORD_STYLE_AGENT = '''from besser.BUML.metamodel.state_machine.agent import Agent +agent = Agent(name="kw") +hello = agent.new_intent(name="hello", training_sentences=["hi"]) +s0 = agent.new_state(name="initial", initial=True) +s1 = agent.new_state(name="next") +s0.when_intent_matched(hello).go_to(s1) +''' + + +def agent_source(tmp_path, with_farewell): + agent = Agent("Greeter") + hello = agent.new_intent("hello_intent", ["hi"]) + initial = agent.new_state("initial", initial=True) + greeting = agent.new_state("greeting") + initial.when_intent_matched(hello).go_to(greeting) + if with_farewell: + greeting.go_to(agent.new_state("farewell")) + path = tmp_path / "agent.py" + agent_model_to_code(agent, str(path)) + return path.read_text() + + +def post(client, source, existing_model=None): + data = {"existing_model": existing_model} if existing_model is not None else None + response = client.post(URL, files={"buml_file": ("agent.py", source.encode(), "text/plain")}, data=data) + assert response.status_code == 200, response.text + return response.json() + + +def test_reimport_keeps_the_layout_of_the_existing_diagram(client, tmp_path): + first = post(client, agent_source(tmp_path, with_farewell=False)) + existing = first["model"] + for index, node in enumerate(existing["nodes"]): + node["position"] = {"x": 500 + 300 * index, "y": 400} + + body = post(client, agent_source(tmp_path, with_farewell=True), json.dumps(existing)) + + nodes = {node["data"]["name"]: node for node in body["model"]["nodes"]} + for old in existing["nodes"]: + assert (nodes[old["data"]["name"]]["id"], nodes[old["data"]["name"]]["position"]) == \ + (old["id"], old["position"]) + codes = [warning["code"] for warning in body["warnings"]] + assert codes == ["layout-adopted", "element-added"] + added = body["warnings"][1] + assert (added["name"], added["placedNextTo"], added["elementId"]) == \ + ("farewell", "greeting", nodes["farewell"]["id"]) + assert body["diagramType"] == body["model"]["type"] == "AgentDiagram" + + +def test_without_existing_model_the_response_is_unchanged(client, tmp_path): + body = post(client, agent_source(tmp_path, with_farewell=False)) + assert body["warnings"] is None + assert [node["position"] for node in body["model"]["nodes"]] == [{"x": -280, "y": -80}, {"x": 210, "y": -80}] + + +def test_unusable_existing_model_imports_with_a_warning(client, tmp_path): + body = post(client, agent_source(tmp_path, with_farewell=False), "{not json") + assert [warning["code"] for warning in body["warnings"]] == ["layout-not-adopted"] + assert len(body["model"]["nodes"]) == 2 + + +def test_partly_read_agent_says_so(client): + body = post(client, KEYWORD_STYLE_AGENT) + assert body["model"]["nodes"] == [] + assert [warning["code"] for warning in body["warnings"]] == ["buml-import-partial"] + assert "could be read only up to an unsupported statement" in body["warnings"][0]["message"] diff --git a/tests/utilities/web_modeling_editor/backend/test_legacy_v3_rejection.py b/tests/utilities/web_modeling_editor/backend/test_legacy_v3_rejection.py new file mode 100644 index 000000000..8557507cc --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/test_legacy_v3_rejection.py @@ -0,0 +1,553 @@ +"""Legacy v3 diagram payloads are rejected with HTTP 400, not converted to nothing. + +The JSON -> B-UML converters read only the v4 ``{nodes, edges}`` wire shape. +Before the guard, a v3 ``{version: '3.x', elements, relationships}`` payload +was silently accepted: ``/export-buml`` returned an empty model, +``/validate-diagram`` answered ``isValid: true`` and the generators produced +near-empty code. Every endpoint that takes diagram or project JSON must now +refuse it with an actionable message, while v4 payloads and the GUI +(GrapesJS) / quantum-circuit formats are unaffected. +""" + +import asyncio +import copy +import json +import os +from typing import Any, Dict + +import httpx +import pytest +from httpx._transports.asgi import ASGITransport + +from besser.utilities.web_modeling_editor.backend.backend import app +from besser.utilities.web_modeling_editor.backend.models import DiagramInput, ProjectInput +from besser.utilities.web_modeling_editor.backend.services.exceptions import ( + ConversionError, + LegacyDiagramFormatError, +) +from besser.utilities.web_modeling_editor.backend.services.validators.legacy_format import ( + ensure_project_not_legacy, + is_legacy_v3_model, +) + +LEGACY_MARKER = "legacy v3 editor format" +FIXTURES_V4 = os.path.join(os.path.dirname(__file__), "..", "..", "..", "fixtures", "v4") + + +def _post(url: str, **kwargs) -> httpx.Response: + async def _go(): + async with httpx.AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as ac: + return await ac.post(url, **kwargs) + return asyncio.run(_go()) + + +@pytest.fixture(autouse=True) +def _isolate_cwd(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + + +# --------------------------------------------------------------------------- +# Payloads +# --------------------------------------------------------------------------- + +def _v3_model(diagram_type: str = "ClassDiagram") -> Dict[str, Any]: + """A v3 editor model: one element, keyed maps, version 3.0.0.""" + return { + "version": "3.0.0", + "type": diagram_type, + "size": {"width": 800, "height": 600}, + "interactive": {"elements": {}, "relationships": {}}, + "elements": { + "e1": { + "id": "e1", "name": "Book", "type": "Class", "owner": None, + "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}, + "attributes": [], "methods": [], + }, + }, + "relationships": {}, + "assessments": {}, + } + + +def _v4_class_model() -> Dict[str, Any]: + with open(os.path.join(FIXTURES_V4, "class_diagram_basic.json"), encoding="utf-8") as f: + return json.load(f)["model"] + + +def _gui_model() -> Dict[str, Any]: + # GrapesJS project data: its own unrelated version, no ``type``. + return {"pages": [], "styles": [], "assets": [], "symbols": [], "version": "0.21.13"} + + +def _quantum_model() -> Dict[str, Any]: + return {"cols": [], "gates": [], "gateMetadata": {}, "initialStates": [], "version": "1.0.0"} + + +def _kg_model() -> Dict[str, Any]: + # Cytoscape-backed: nodes/edges like v4 UML, but its own format. + return { + "type": "KnowledgeGraphDiagram", + "version": "1.0.0", + "nodes": [{"id": "n1", "nodeType": "class", "label": "Person"}], + "edges": [], + } + + +def _diagram(model: Dict[str, Any], title: str = "Legacy", **extra) -> Dict[str, Any]: + return {"title": title, "model": model, **extra} + + +def _project(class_model: Dict[str, Any], **settings) -> Dict[str, Any]: + return { + "id": "proj-1", + "type": "Project", + "name": "LegacyProject", + "createdAt": "2025-01-01T00:00:00Z", + "currentDiagramType": "ClassDiagram", + "currentDiagramIndices": {"ClassDiagram": 0}, + "diagrams": { + "ClassDiagram": [{"id": "cd-1", "title": "Domain", "model": class_model}], + "GUINoCodeDiagram": [{"id": "gui-1", "title": "GUI", "model": _gui_model()}], + "QuantumCircuitDiagram": [{"id": "q-1", "title": "Circuit", "model": _quantum_model()}], + "KnowledgeGraphDiagram": [{"id": "kg-1", "title": "Graph", "model": _kg_model()}], + }, + "settings": settings or None, + } + + +def _assert_legacy_rejected(response: httpx.Response) -> None: + assert response.status_code == 400, response.text + detail = response.json()["detail"] + assert LEGACY_MARKER in detail + assert "current BESSER web editor" in detail + + +# --------------------------------------------------------------------------- +# Detection +# --------------------------------------------------------------------------- + +class TestDetection: + @pytest.mark.parametrize("model", [ + _v3_model(), + {"version": "3.0.0", "type": "AgentDiagram"}, # version rule + {"type": "ClassDiagram", "elements": {}, "relationships": {}}, # shape rule, no version + {"elements": {}}, # untyped v3 shape + ]) + def test_legacy_models_are_detected(self, model): + assert is_legacy_v3_model(model) + + @pytest.mark.parametrize("model", [ + {"version": "4.0.0", "type": "ClassDiagram", "nodes": [], "edges": []}, + {}, + _gui_model(), + _quantum_model(), + _kg_model(), + # GUI / quantum / KG are exempt by type even with a v3-looking body. + {"type": "GUINoCodeDiagram", "version": "3.1.0", "elements": {}}, + {"type": "QuantumCircuitDiagram", "version": "3.0.0", "elements": {}}, + {"type": "KnowledgeGraphDiagram", "version": "3.0.0", "elements": {}}, + # A typeless model with a 3.x version is not UML (GrapesJS could get there). + {"pages": [], "version": "3.0.0"}, + None, + "not a dict", + ]) + def test_non_legacy_models_pass(self, model): + assert not is_legacy_v3_model(model) + + def test_exempt_by_project_key(self): + assert not is_legacy_v3_model({"elements": {}}, "GUINoCodeDiagram") + assert not is_legacy_v3_model({"elements": {}}, "QuantumCircuitDiagram") + assert not is_legacy_v3_model({"elements": {}}, "KnowledgeGraphDiagram") + + def test_populated_v3_maps_with_empty_nodes_are_legacy(self): + # Converted to an empty model with HTTP 200 while "nodes" alone decided. + v3 = _v3_model() + assert is_legacy_v3_model({**v3, "version": "4.0.0", "nodes": [], "edges": []}) + assert is_legacy_v3_model({"type": "ClassDiagram", "nodes": [], "elements": v3["elements"]}) + assert is_legacy_v3_model({"type": "ClassDiagram", "nodes": [], "relationships": {"r1": {"id": "r1"}}}) + # Empty leftovers beside "nodes" are not v3 content. + assert not is_legacy_v3_model({"type": "ClassDiagram", "nodes": [], "elements": {}, "relationships": {}}) + + def test_non_empty_nodes_are_v4_whatever_the_version_says(self): + model = {**_v4_class_model(), "version": "3.0.0"} + assert model["nodes"] + assert not is_legacy_v3_model(model) + assert not is_legacy_v3_model({**model, "elements": _v3_model()["elements"]}) + DiagramInput(**_diagram(model)) + # The version rule still holds without node content. + assert is_legacy_v3_model({**model, "nodes": []}) + + def test_bucket_decides_the_exemption_not_the_model_type(self): + mislabelled = {**_v3_model(), "type": "GUINoCodeDiagram"} + assert is_legacy_v3_model(mislabelled, "ClassDiagram") + assert not is_legacy_v3_model(mislabelled, "GUINoCodeDiagram") + assert not is_legacy_v3_model(mislabelled) + with pytest.raises(LegacyDiagramFormatError, match="'Domain'"): + ProjectInput(**_project(mislabelled)) + with pytest.raises(LegacyDiagramFormatError): + ensure_project_not_legacy({"ClassDiagram": [{"title": "D", "model": mislabelled}]}) + + def test_error_is_a_conversion_error(self): + assert issubclass(LegacyDiagramFormatError, ConversionError) + + def test_diagram_input_rejects_v3(self): + with pytest.raises(LegacyDiagramFormatError, match="Diagram 'Legacy' \\(ClassDiagram\\)"): + DiagramInput(**_diagram(_v3_model())) + + def test_diagram_input_rejects_v3_reference_data(self): + with pytest.raises(LegacyDiagramFormatError): + DiagramInput(**_diagram( + {"version": "4.0.0", "type": "ObjectDiagram", "nodes": [], "edges": []}, + referenceDiagramData=_v3_model(), + )) + with pytest.raises(LegacyDiagramFormatError): + DiagramInput(**_diagram({ + "version": "4.0.0", "type": "ObjectDiagram", "nodes": [], "edges": [], + "referenceDiagramData": {"title": "Ref", "model": _v3_model()}, + })) + + def test_diagram_input_accepts_v4_gui_and_quantum(self): + DiagramInput(**_diagram(_v4_class_model())) + DiagramInput(**_diagram(_gui_model())) + DiagramInput(**_diagram(_quantum_model())) + DiagramInput(**_diagram(_kg_model())) + + def test_project_input_rejects_any_v3_uml_diagram(self): + with pytest.raises(LegacyDiagramFormatError, match="'Domain'"): + ProjectInput(**_project(_v3_model())) + + def test_project_input_accepts_v4_with_gui_and_quantum(self): + ProjectInput(**_project(_v4_class_model())) + + def test_raw_project_diagrams_single_and_list_layouts(self): + with pytest.raises(LegacyDiagramFormatError): + ensure_project_not_legacy({"ClassDiagram": {"title": "D", "model": _v3_model()}}) + with pytest.raises(LegacyDiagramFormatError): + ensure_project_not_legacy({"AgentDiagram": [{"title": "A", "model": _v3_model("AgentDiagram")}]}) + ensure_project_not_legacy(_project(_v4_class_model())["diagrams"]) + ensure_project_not_legacy(None) + + +# --------------------------------------------------------------------------- +# Single-diagram endpoints +# --------------------------------------------------------------------------- + +UML_TYPES = [ + "ClassDiagram", "ObjectDiagram", "StateMachineDiagram", "AgentDiagram", + "UserDiagram", "NNDiagram", "BPMNDiagram", +] + + +@pytest.mark.parametrize("diagram_type", UML_TYPES) +@pytest.mark.parametrize("endpoint", ["/besser_api/export-buml", "/besser_api/validate-diagram"]) +def test_single_diagram_endpoints_reject_v3(endpoint, diagram_type): + _assert_legacy_rejected(_post(endpoint, json=_diagram(_v3_model(diagram_type)))) + + +@pytest.mark.parametrize("generator", ["python", "pydantic", "django", "sql"]) +def test_generate_output_rejects_v3(generator): + payload = _diagram(_v3_model(), generator=generator) + _assert_legacy_rejected(_post("/besser_api/generate-output", json=payload)) + + +def test_generate_output_rejects_v3_agent(): + payload = _diagram(_v3_model("AgentDiagram"), generator="agent") + _assert_legacy_rejected(_post("/besser_api/generate-output", json=payload)) + + +def test_deploy_app_rejects_v3(): + payload = _diagram(_v3_model(), generator="django") + _assert_legacy_rejected(_post("/besser_api/deploy-app", json=payload)) + + +def test_transform_agent_model_json_rejects_v3(): + _assert_legacy_rejected( + _post("/besser_api/transform-agent-model-json", json=_diagram(_v3_model("AgentDiagram"))) + ) + + +def test_object_diagram_with_v3_reference_rejected(): + payload = _diagram( + {"version": "4.0.0", "type": "ObjectDiagram", "nodes": [], "edges": []}, + referenceDiagramData={"title": "Ref", "model": _v3_model()}, + ) + _assert_legacy_rejected(_post("/besser_api/export-buml", json=payload)) + + +def test_v4_single_diagram_endpoints_unaffected(): + payload = _diagram(_v4_class_model(), title="Library") + assert _post("/besser_api/export-buml", json=payload).status_code == 200 + validated = _post("/besser_api/validate-diagram", json=payload) + assert validated.status_code == 200 + assert validated.json()["isValid"] is True + generated = _post("/besser_api/generate-output", json={**payload, "generator": "python"}) + assert generated.status_code == 200 + assert "class " in generated.text + + +def test_quantum_generation_unaffected(): + payload = _diagram(_quantum_model(), title="Circuit", generator="qiskit") + response = _post("/besser_api/generate-output", json=payload) + assert LEGACY_MARKER not in response.text + + +# --------------------------------------------------------------------------- +# Project endpoints +# --------------------------------------------------------------------------- + +def test_export_project_as_buml_rejects_v3(): + _assert_legacy_rejected(_post("/besser_api/export-project-as-buml", json=_project(_v3_model()))) + + +@pytest.mark.parametrize("generator", ["python", "web_app", "backend"]) +def test_generate_output_from_project_rejects_v3(generator): + payload = _project(_v3_model(), generator=generator) + _assert_legacy_rejected(_post("/besser_api/generate-output-from-project", json=payload)) + + +def test_v4_project_with_gui_and_quantum_unaffected(): + exported = _post("/besser_api/export-project-as-buml", json=_project(_v4_class_model())) + assert exported.status_code == 200, exported.text + generated = _post( + "/besser_api/generate-output-from-project", + json=_project(_v4_class_model(), generator="python"), + ) + assert generated.status_code == 200, generated.text + + +@pytest.mark.parametrize("endpoint", ["/besser_api/spec-driven/generate", "/besser_api/spec-driven/preview"]) +def test_spec_driven_rejects_v3_project(endpoint): + body = { + "project": _project(_v3_model()), + "instructions": "Build a library app.", + "api_key": "sk-test", + } + _assert_legacy_rejected(_post(endpoint, json=body)) + + +# --------------------------------------------------------------------------- +# Agent simulator, personalization, GitHub deploy +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize("endpoint", ["/besser_api/simulation/validate", "/besser_api/simulation/sessions"]) +def test_simulation_rejects_v3_agent(endpoint): + _assert_legacy_rejected(_post(endpoint, json={"title": "Agent", "model": _v3_model("AgentDiagram")})) + + +def test_personalize_gui_page_rejects_v3_user_profile(): + body = {"guiPage": {"components": [], "css": []}, "userProfileModel": _v3_model("UserDiagram")} + _assert_legacy_rejected(_post("/besser_api/personalize-gui-page", json=body)) + + +@pytest.mark.parametrize("endpoint", [ + "/besser_api/recommend-agent-config-mapping", + "/besser_api/recommend-agent-config-llm", +]) +def test_agent_config_recommendation_rejects_v3_user_profile(monkeypatch, endpoint): + from besser.utilities.web_modeling_editor.backend.routers import generation_router as gr + monkeypatch.setattr(gr, "get_user_token", lambda _sessions, _session: "fake-token") + _assert_legacy_rejected(_post( + endpoint, + json={"userProfileModel": _v3_model("UserDiagram")}, + headers={"X-GitHub-Session": "test-session"}, + )) + + +def test_personalize_gui_page_rejects_wrapped_v3_user_profile(): + body = { + "guiPage": {"components": [], "css": []}, + "userProfileModel": {"title": "Profile", "model": _v3_model("UserDiagram")}, + } + _assert_legacy_rejected(_post("/besser_api/personalize-gui-page", json=body)) + + +@pytest.mark.parametrize("wrap", [False, True], ids=["bare", "wrapped"]) +def test_image_import_rejects_v3_existing_model(monkeypatch, wrap): + from besser.BUML.metamodel.structural import DomainModel + from besser.utilities.web_modeling_editor.backend.routers import conversion_router + + # Before the guard the v3 model was dropped and the image imported without it. + monkeypatch.setattr(conversion_router, "image_to_buml", lambda **_: DomainModel(name="FromImage")) + existing = {"title": "Existing", "model": _v3_model()} if wrap else _v3_model() + response = _post( + "/besser_api/get-json-model-from-image", + files={"image_file": ("diagram.png", b"\x89PNG\r\n\x1a\n" + b"\0" * 16, "image/png")}, + data={"api_key": "sk-test", "existing_model": json.dumps(existing)}, + ) + _assert_legacy_rejected(response) + + +def test_class_diagram_with_populated_v3_maps_and_empty_nodes_is_rejected(): + model = {**_v3_model(), "version": "4.0.0", "nodes": [], "edges": []} + _assert_legacy_rejected(_post("/besser_api/export-buml", json=_diagram(model))) + + +def test_project_with_mislabelled_v3_class_diagram_is_rejected(): + project = _project({**_v3_model(), "type": "GUINoCodeDiagram"}) + _assert_legacy_rejected(_post("/besser_api/export-project-as-buml", json=project)) + + +def test_github_deploy_webapp_rejects_v3_before_calling_github(monkeypatch): + from besser.utilities.web_modeling_editor.backend.routers import github_deploy_api as gda + + monkeypatch.setattr(gda, "get_user_token", lambda _sessions, _session: "fake-token") + + def _no_github(_token): + raise AssertionError("GitHub must not be contacted for a legacy payload") + + monkeypatch.setattr(gda, "create_github_service", _no_github) + body = copy.deepcopy(_project(_v3_model())) + body["deploy_config"] = {"repo_name": "legacy-app"} + _assert_legacy_rejected(_post( + "/besser_api/github/deploy-webapp", json=body, headers={"X-GitHub-Session": "test-session"}, + )) + + +def test_github_project_save_stores_a_legacy_project_without_buml_sources(): + """Saving to GitHub is storage: a v3 project is stored, but no B-UML is written for it.""" + from besser.utilities.web_modeling_editor.backend.services.deployment import repo_model + + legacy = repo_model.build_model_files(_project(_v3_model())) + current = repo_model.build_model_files(_project(_v4_class_model())) + + assert repo_model.MODEL_FILE in legacy.files and not legacy.sources_built + assert "buml/domain_model.py" not in legacy.files + assert current.sources_built and "buml/domain_model.py" in current.files + + +# --------------------------------------------------------------------------- +# Models nested in an agent diagram's config +# --------------------------------------------------------------------------- + +def _v4_agent_model() -> Dict[str, Any]: + with open(os.path.join(FIXTURES_V4, "agent_diagram_basic.json"), encoding="utf-8") as f: + return json.load(f)["model"] + + +def _v4_user_model() -> Dict[str, Any]: + return {"version": "4.0.0", "type": "UserDiagram", "nodes": [], "edges": []} + + +@pytest.mark.parametrize("entry", [ + {"user_profile": _v3_model("UserDiagram")}, + {"user_profile": _v4_user_model(), "agent_model": _v3_model("AgentDiagram")}, + {"user_profile": {"title": "Profile", "model": _v3_model("UserDiagram")}}, + {"user_profile": _v4_user_model(), "agent_model": {"title": "Variant", "model": _v3_model("AgentDiagram")}}, +], ids=["v3-user-profile", "v3-agent-model", "wrapped-v3-user-profile", "wrapped-v3-agent-model"]) +def test_generate_output_rejects_v3_personalization_mapping(entry): + payload = _diagram( + _v4_agent_model(), generator="agent", + config={"personalizationMapping": [{"name": "variant", **entry}]}, + ) + response = _post("/besser_api/generate-output", json=payload) + _assert_legacy_rejected(response) + assert "personalizationMapping[0]" in response.json()["detail"] + + +def test_normalize_personalization_mapping_rejects_v3_before_conversion(): + from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import ( + normalize_personalization_mapping, + ) + + def _must_not_run(_payload): + raise AssertionError("a v3 user profile must be rejected before conversion") + + config = {"personalizationMapping": [{"user_profile": _v3_model("UserDiagram")}]} + with pytest.raises(LegacyDiagramFormatError): + normalize_personalization_mapping(config, {"model": _v4_agent_model()}, _must_not_run) + + +def test_transform_agent_model_json_rejects_v3_user_profile_in_config(): + payload = _diagram( + _v4_agent_model(), config={"userProfileModel": _v3_model("UserDiagram")}, + ) + response = _post("/besser_api/transform-agent-model-json", json=payload) + _assert_legacy_rejected(response) + assert "config.userProfileModel" in response.json()["detail"] + + +# --------------------------------------------------------------------------- +# Malformed v4 payloads are 400s, and the converters refuse v3 themselves +# --------------------------------------------------------------------------- + +def _v4(diagram_type: str, **parts) -> Dict[str, Any]: + model = {"version": "4.0.0", "type": diagram_type, "nodes": [], "edges": []} + model.update(parts) + return model + + +_CLASS_NODE = {"id": "a", "type": "class", "data": {"name": "A"}} +_MALFORMED = { + "nodes_dict": {"nodes": {"a": {}}}, + "nodes_strs": {"nodes": ["x", 1, None], "edges": ["y"]}, + "node_data_list": {"nodes": [{"id": "a", "type": "class", "data": [1]}]}, + "edge_data_list": {"nodes": [_CLASS_NODE], "edges": [ + {"id": "e", "type": "ClassBidirectional", "source": "a", "target": "a", "data": [1]}]}, + "edge_ids_unhashable": {"nodes": [{"id": ["a"], "type": "class", "data": {"name": "A"}}], + "edges": [{"id": {}, "type": "ClassInheritance", "source": ["a"], + "target": {"x": 1}}]}, +} + + +@pytest.mark.parametrize("diagram_type", ["ClassDiagram", "StateMachineDiagram", "AgentDiagram"]) +@pytest.mark.parametrize("case", sorted(_MALFORMED)) +def test_malformed_v4_payload_is_a_400(diagram_type, case): + body = {"title": "T", "model": _v4(diagram_type, **_MALFORMED[case])} + for url, extra in (("/besser_api/export-buml", {}), + ("/besser_api/generate-output", {"generator": "python"})): + response = _post(url, json={**body, **extra}) + assert response.status_code == 400, (url, response.status_code, response.text[:200]) + + +@pytest.mark.parametrize("process, diagram_type", [ + ("process_class_diagram", "ClassDiagram"), + ("process_state_machine", "StateMachineDiagram"), + ("process_agent_diagram", "AgentDiagram"), + ("process_bpmn_diagram", "BPMNDiagram"), + ("process_component_diagram", "ComponentDiagram"), + ("process_deployment_diagram", "DeploymentDiagram"), + ("process_nn_diagram", "NNDiagram"), +]) +def test_converters_refuse_v3_json(process, diagram_type): + from besser.utilities.web_modeling_editor.backend.services import converters + with pytest.raises(ConversionError): + getattr(converters, process)({"title": "T", "model": _v3_model(diagram_type)}) + + +def test_object_converter_refuses_v3_json(): + from besser.BUML.metamodel.structural import Class, DomainModel + from besser.utilities.web_modeling_editor.backend.services.converters import process_object_diagram + with pytest.raises(ConversionError): + process_object_diagram({"title": "T", "model": _v3_model("ObjectDiagram")}, + DomainModel(name="D", types={Class(name="A")})) + + +_CLASS_B = {"id": "b", "type": "class", "data": {"name": "B"}} +_MALFORMED_CLASS = { + "attrs_not_list": ({"nodes": [{"id": "a", "type": "class", "data": { + "name": "A", "attributes": "x", "methods": {"a": 1}}}]}, "must be a list of objects"), + "methods_not_list": ({"nodes": [{"id": "a", "type": "class", "data": { + "name": "A", "methods": {"a": 1}}}]}, "must be a list of objects"), + "attribute_row_not_object": ({"nodes": [{"id": "a", "type": "class", "data": { + "name": "A", "attributes": [1]}}]}, "must be a list of objects"), + "inherit_cycle": ({"nodes": [_CLASS_NODE, _CLASS_B], "edges": [ + {"id": "e1", "type": "ClassInheritance", "source": "a", "target": "b", "data": {}}, + {"id": "e2", "type": "ClassInheritance", "source": "b", "target": "a", "data": {}}]}, + "Inheritance cycle"), +} + + +# Class-diagram content the v4 shape check lets through; a StateMachineDiagram +# body sent to a class generator takes the same converter path. +@pytest.mark.parametrize("diagram_type", ["ClassDiagram", "StateMachineDiagram"]) +@pytest.mark.parametrize("case", sorted(_MALFORMED_CLASS)) +def test_malformed_class_content_is_a_400(diagram_type, case): + parts, message = _MALFORMED_CLASS[case] + body = {"title": "T", "model": _v4(diagram_type, **parts)} + urls = [("/besser_api/generate-output", {"generator": "python"})] + if diagram_type == "ClassDiagram": + urls.append(("/besser_api/export-buml", {})) + for url, extra in urls: + response = _post(url, json={**body, **extra}) + assert response.status_code == 400, (url, response.status_code, response.text[:200]) + assert message in response.json()["detail"] diff --git a/tests/utilities/web_modeling_editor/backend/test_model_attribution.py b/tests/utilities/web_modeling_editor/backend/test_model_attribution.py index 6b7aa08ee..e34a60316 100644 --- a/tests/utilities/web_modeling_editor/backend/test_model_attribution.py +++ b/tests/utilities/web_modeling_editor/backend/test_model_attribution.py @@ -41,22 +41,14 @@ async def run(): def _model(*classes: str, attributes: tuple = ()) -> dict: - """An Apollon class diagram; each name in ``attributes`` is an attribute of the first class.""" - elements = {} - for index, name in enumerate(classes): - elements[f"id-{name}"] = { - "id": f"id-{name}", "type": "Class", "name": name, "owner": None, - "bounds": {"x": index * 300, "y": 0, "width": 200, "height": 100}, - "attributes": [f"id-{a}" for a in attributes] if index == 0 else [], "methods": [], - } - for attribute in attributes: - elements[f"id-{attribute}"] = { - "id": f"id-{attribute}", "type": "ClassAttribute", "name": f"+ {attribute}: str", "owner": f"id-{classes[0]}", - "bounds": {"x": 0, "y": 40, "width": 200, "height": 30}, - } - return {"version": "3.0.0", "type": "ClassDiagram", "size": {"width": 800, "height": 600}, - "interactive": {"elements": {}, "relationships": {}}, "elements": elements, "relationships": {}, - "assessments": {}} + """A v4 class diagram; each name in ``attributes`` is an attribute row of the first class.""" + nodes = [{ + "id": f"id-{name}", "type": "class", "position": {"x": index * 300, "y": 0}, "width": 200, "height": 100, + "data": {"name": name, "methods": [], "attributes": [ + {"id": f"id-{a}", "name": a, "attributeType": "str", "visibility": "public"} for a in attributes + ] if index == 0 else []}, + } for index, name in enumerate(classes)] + return {"version": "4.0.0", "type": "ClassDiagram", "nodes": nodes, "edges": [], "assessments": {}} def _envelope(model: dict, attribution: dict | None = None) -> dict: @@ -297,7 +289,9 @@ def test_stamping_touches_no_diagram(): def _with_relationship(model: dict, relationship_id: str = "rel-1") -> dict: - return {**model, "relationships": {relationship_id: {"id": relationship_id, "type": "ClassBidirectional"}}} + edge = {"id": relationship_id, "type": "ClassBidirectional", "source": model["nodes"][0]["id"], + "target": model["nodes"][0]["id"], "data": {}} + return {**model, "edges": [edge]} def test_a_new_relationship_is_credited_to_who_added_it(): diff --git a/tests/utilities/web_modeling_editor/backend/test_personalization_mapping_v4.py b/tests/utilities/web_modeling_editor/backend/test_personalization_mapping_v4.py new file mode 100644 index 000000000..a2de67401 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/test_personalization_mapping_v4.py @@ -0,0 +1,206 @@ +"""Integration coverage for the agent personalization mapping with v4 payloads. + +The migration frontend bundles personalization state (saved configurations, +user profiles, per-diagram base models) and ships **v4** ``agent_model`` / +``user_profile`` payloads inside ``config.personalizationMapping`` when +generating a personalized agent. These tests pin the backend side of that +contract: + +- ``normalize_personalization_mapping`` converts a v4 AgentDiagram payload + into a BUML agent model and routes the raw user-profile payload through the + profile generator callback; +- ``generate_user_profile_document`` accepts a v4 UserDiagram model (the + exact shape the frontend stores in ``besser_userProfiles``) end-to-end + through the real object processor + JSONObject generator; +- malformed mapping entries surface as HTTP 400s instead of being swallowed. + +There was previously zero ``personalizationMapping`` coverage in ``tests/``. +""" + +from __future__ import annotations + +import json +import os +from copy import deepcopy + +import pytest +from fastapi import HTTPException + +from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import ( + normalize_personalization_mapping, +) +from besser.utilities.web_modeling_editor.backend.services.utils.user_profile_utils import ( + generate_user_profile_document, +) + + +FIXTURES_DIR = os.path.join( + os.path.dirname(__file__), "..", "..", "..", "fixtures", "v4" +) + + +def _load(name: str) -> dict: + path = os.path.normpath(os.path.join(FIXTURES_DIR, name)) + with open(path) as f: + return json.load(f) + + +def _v4_user_profile_model() -> dict: + """Minimal v4 UserDiagram model, as stored in ``besser_userProfiles``. + + ``className`` references the backend's user reference domain model + (``constants/user_buml_model.py``) the same way the frontend inspector + does. + """ + return { + "version": "4.0.0", + "id": "user-profile-1", + "title": "Teenager", + "type": "UserDiagram", + "nodes": [ + { + "id": "user-node-1", + "type": "UserModelName", + "position": {"x": 0, "y": 0}, + "width": 160, + "height": 70, + "measured": {"width": 160, "height": 70}, + "data": {"name": "Teen", "className": "User", "attributes": []}, + }, + { + "id": "user-node-2", + "type": "UserModelName", + "position": {"x": 0, "y": 160}, + "width": 160, + "height": 70, + "measured": {"width": 160, "height": 70}, + "data": { + "name": "TeenInfo", + "className": "Personal_Information", + "attributes": [ + {"id": "attr-1", "name": "age", "value": "16", "attributeOperator": "=="}, + ], + }, + }, + ], + "edges": [], + "assessments": {}, + } + + +# --------------------------------------------------------------------------- +# normalize_personalization_mapping — v4 agent_model conversion +# --------------------------------------------------------------------------- + + +def test_normalize_personalization_mapping_converts_v4_agent_model(): + fixture = _load("agent_diagram_basic.json") + + forwarded_profiles = [] + + def fake_profile_generator(payload): + forwarded_profiles.append(payload) + return {"model": {"name": "Teenager"}} + + config = { + "personalizationMapping": [ + { + "name": "Teenager", + "configuration": {"agentStyle": "friendly"}, + "user_profile": _v4_user_profile_model(), + "agent_model": deepcopy(fixture["model"]), + } + ] + } + json_data = { + "title": fixture.get("title", "Agent"), + "model": deepcopy(fixture["model"]), + "config": config, + } + + normalize_personalization_mapping(config, json_data, fake_profile_generator) + + entry = config["personalizationMapping"][0] + + # The v4 agent_model payload was converted to a BUML agent model in place. + agent = entry["agent_model"] + assert not isinstance(agent, dict) + assert any(s.name == "Greeting" for s in agent.states) + assert any(i.name == "greet" for i in agent.intents) + + # The user_profile was replaced by the simplified profile document and the + # raw v4 payload was forwarded untouched to the generator callback. + assert entry["user_profile"] == {"model": {"name": "Teenager"}} + assert len(forwarded_profiles) == 1 + assert forwarded_profiles[0]["type"] == "UserDiagram" + assert isinstance(forwarded_profiles[0]["nodes"], list) + + # The updated config is written back onto the payload. + assert json_data["config"] is config + + +def test_normalize_personalization_mapping_missing_user_profile_is_400(): + config = {"personalizationMapping": [{"name": "x", "agent_model": {"nodes": [], "edges": []}}]} + with pytest.raises(HTTPException) as exc_info: + normalize_personalization_mapping(config, {"config": config}, lambda payload: payload) + assert exc_info.value.status_code == 400 + assert "user_profile" in exc_info.value.detail + + +def test_normalize_personalization_mapping_non_dict_entry_is_400(): + config = {"personalizationMapping": ["not-an-object"]} + with pytest.raises(HTTPException) as exc_info: + normalize_personalization_mapping(config, {"config": config}, lambda payload: payload) + assert exc_info.value.status_code == 400 + + +def test_normalize_personalization_mapping_empty_mapping_is_noop(): + config = {"personalizationMapping": []} + json_data = {"config": config} + normalize_personalization_mapping(config, json_data, lambda payload: payload) + assert config["personalizationMapping"] == [] + assert json_data["config"] is config + + +# --------------------------------------------------------------------------- +# generate_user_profile_document — real v4 UserDiagram end-to-end +# --------------------------------------------------------------------------- + + +def test_generate_user_profile_document_accepts_v4_user_diagram(): + """The exact v4 model shape the frontend stores in ``besser_userProfiles`` + (and ships in ``personalizationMapping[].user_profile``) must flow through + the real object processor + JSONObject generator.""" + result = generate_user_profile_document(_v4_user_profile_model()) + + assert isinstance(result, dict) and result, "expected a non-empty profile document" + # Hierarchy normalization fired: "model" root, never raw "objects". + assert "model" in result and "objects" not in result + + +def test_normalize_personalization_mapping_end_to_end_with_real_profile_generator(): + """Full pipeline: v4 agent_model -> BUML agent AND v4 user_profile -> + simplified profile document, exactly as the generation router wires it.""" + fixture = _load("agent_diagram_basic.json") + config = { + "personalizationMapping": [ + { + "name": "Teenager", + "configuration": {"agentStyle": "friendly"}, + "user_profile": _v4_user_profile_model(), + "agent_model": deepcopy(fixture["model"]), + } + ] + } + json_data = { + "title": fixture.get("title", "Agent"), + "model": deepcopy(fixture["model"]), + "config": config, + } + + normalize_personalization_mapping(config, json_data, generate_user_profile_document) + + entry = config["personalizationMapping"][0] + assert not isinstance(entry["agent_model"], dict) + assert isinstance(entry["user_profile"], dict) and entry["user_profile"] + assert "model" in entry["user_profile"] diff --git a/tests/utilities/web_modeling_editor/backend/test_placeholder_elements.py b/tests/utilities/web_modeling_editor/backend/test_placeholder_elements.py index 86253d790..e713712b0 100644 --- a/tests/utilities/web_modeling_editor/backend/test_placeholder_elements.py +++ b/tests/utilities/web_modeling_editor/backend/test_placeholder_elements.py @@ -10,20 +10,20 @@ from besser.BUML.metamodel.structural import PLACEHOLDER_NAME from besser.utilities.web_modeling_editor.backend.services.converters import process_class_diagram -from tests.utilities.web_modeling_editor.backend.services.converters.placeholder_diagram import placeholder_diagram +from tests.utilities.web_modeling_editor.backend.services.converters.placeholder_diagram import ( + association, class_diagram, class_node, edge, placeholder_diagram, +) def _visible_diagram() -> dict: """The diagram of ``placeholder_diagram`` without its "..." classes and literals.""" diagram = placeholder_diagram() - elements = diagram["model"]["elements"] - hidden = {key for key, element in elements.items() - if element.get("name") == PLACEHOLDER_NAME and element["type"] in ("Class", "EnumerationLiteral")} - diagram["model"]["elements"] = {key: element for key, element in elements.items() if key not in hidden} - diagram["model"]["elements"]["kind"]["attributes"].remove("hidden-lit") - diagram["model"]["relationships"] = { - key: rel for key, rel in diagram["model"]["relationships"].items() - if not ({rel["source"]["element"], rel["target"]["element"]} & hidden)} + model = diagram["model"] + hidden = {node["id"] for node in model["nodes"] if node["data"]["name"] == PLACEHOLDER_NAME} + model["nodes"] = [node for node in model["nodes"] if node["id"] not in hidden] + for node in model["nodes"]: + node["data"]["attributes"] = [row for row in node["data"]["attributes"] if row["name"] != PLACEHOLDER_NAME] + model["edges"] = [e for e in model["edges"] if not ({e["source"], e["target"]} & hidden)] return diagram @@ -54,7 +54,7 @@ def test_the_quality_check_accepts_placeholders(post): def test_the_quality_check_still_reports_a_real_invalid_name(post): diagram = placeholder_diagram() - diagram["model"]["elements"]["dog"]["name"] = "2nd" + next(node for node in diagram["model"]["nodes"] if node["id"] == "dog")["data"]["name"] = "2nd" data = post("validate-diagram", diagram).json() @@ -85,30 +85,14 @@ def test_generation_keeps_the_real_literals_of_an_enumeration_with_a_placeholder assert "class ..." not in response.text -def _class(name): - return {"type": "Class", "name": name, "attributes": [], "methods": [], - "bounds": {"x": 0, "y": 0, "width": 160, "height": 100}} - - -def _inheritance(specific, general): - return {"type": "ClassInheritance", "source": {"element": specific}, "target": {"element": general}} - - -def _diagram(elements, relationships=None): - return {"title": "Zoo", "model": {"type": "ClassDiagram", "elements": elements, - "relationships": relationships or {}}} - - _EXPORT_CASES = { - "generalization": _diagram({"animal": _class("Animal"), "h1": _class(PLACEHOLDER_NAME)}, - {"g1": _inheritance("h1", "animal")}), - "two": _diagram({"animal": _class("Animal"), "dog": _class("Dog"), - "h1": _class(PLACEHOLDER_NAME), "h2": _class(PLACEHOLDER_NAME)}, - {"g1": _inheritance("h1", "animal"), "g2": _inheritance("h2", "dog")}), - "association": _diagram({"owner": _class("Owner"), "h1": _class(PLACEHOLDER_NAME)}, {"a1": { - "type": "ClassBidirectional", - "source": {"element": "owner", "multiplicity": "1", "role": "owner"}, - "target": {"element": "h1", "multiplicity": "0..*", "role": "hidden"}}}), + "generalization": class_diagram([class_node("animal", "Animal"), class_node("h1", PLACEHOLDER_NAME)], + [edge("g1", "ClassInheritance", "h1", "animal")]), + "two": class_diagram([class_node("animal", "Animal"), class_node("dog", "Dog"), + class_node("h1", PLACEHOLDER_NAME), class_node("h2", PLACEHOLDER_NAME)], + [edge("g1", "ClassInheritance", "h1", "animal"), edge("g2", "ClassInheritance", "h2", "dog")]), + "association": class_diagram([class_node("owner", "Owner"), class_node("h1", PLACEHOLDER_NAME)], + [association("a1", "owner", "h1", "owner", "hidden")]), "all": placeholder_diagram(), } diff --git a/tests/utilities/web_modeling_editor/backend/test_project_trace_export.py b/tests/utilities/web_modeling_editor/backend/test_project_trace_export.py index 838bd35e0..7d93e7c41 100644 --- a/tests/utilities/web_modeling_editor/backend/test_project_trace_export.py +++ b/tests/utilities/web_modeling_editor/backend/test_project_trace_export.py @@ -55,22 +55,23 @@ def artifact(element_id, name, element_type, parent): "newValue": name, "timestamp": T}) return artifacts[element_id] - elements = model["elements"] - for element in elements.values(): - if element.get("owner") is None and element["type"] in ("Class", "Enumeration"): - artifact(element["id"], element["name"], element["type"], root) - for element in elements.values(): - owner = elements.get(element.get("owner") or "") - if owner is not None: - kind = ("EnumerationLiteral" if owner["type"] == "Enumeration" else - "Method" if element["type"] == "ClassMethod" else "Property") - artifact(element["id"], element["name"], kind, artifacts[owner["id"]]) - for rel in model["relationships"].values(): - ends = [elements[rel[side]["element"]]["name"] for side in ("source", "target")] - if rel["type"] == "ClassInheritance": - artifact(rel["id"], f"{ends[0]} → {ends[1]}", "Generalization", root) + classes = [node for node in model["nodes"] if node["type"] == "class"] + for node in classes: + artifact(node["id"], node["data"]["name"], node["data"].get("stereotype") or "Class", root) + for node in classes: + enumeration = node["data"].get("stereotype") == "Enumeration" + for row in node["data"].get("attributes") or []: + artifact(row["id"], row["name"], "EnumerationLiteral" if enumeration else "Property", + artifacts[node["id"]]) + for row in node["data"].get("methods") or []: + artifact(row["id"], row["name"], "Method", artifacts[node["id"]]) + names = {node["id"]: node["data"]["name"] for node in classes} + for edge in model["edges"]: + ends = [names[edge["source"]], names[edge["target"]]] + if edge["type"] == "ClassInheritance": + artifact(edge["id"], f"{ends[0]} → {ends[1]}", "Generalization", root) else: - artifact(rel["id"], rel.get("name") or f"{ends[0]} – {ends[1]}", "BinaryAssociation", root) + artifact(edge["id"], edge["data"].get("name") or f"{ends[0]} – {ends[1]}", "BinaryAssociation", root) artifact("gone", "Ghost", "Class", root) # drawn, then deleted: only the record is left changes.append({"id": "c-gone-deleted", "kind": "DELETED", "artifactId": "a-gone", "oldValue": "Ghost", "timestamp": "2026-10-29T09:31:00.000Z"}) @@ -109,7 +110,21 @@ def _export(client, project) -> str: def _class_names(body) -> set: (diagram,) = body["project"]["diagrams"]["ClassDiagram"] - return {e["name"] for e in diagram["model"]["elements"].values() if e["type"] == "Class"} + return {n["data"]["name"] for n in diagram["model"]["nodes"] + if n["type"] == "class" and not n["data"].get("stereotype")} + + +def _names_by_id(model) -> dict: + """The name of every element of a v4 diagram by its id: nodes, their attribute and method rows, edges + and an agent's components.""" + names = {} + for node in model["nodes"]: + names[node["id"]] = node["data"].get("name") + for row in node["data"].get("attributes", []) + node["data"].get("methods", []): + names[row["id"]] = row.get("name") + names.update({edge["id"]: edge["data"].get("name") for edge in model["edges"]}) + names.update({c_id: c.get("name") for c_id, c in (model.get("components") or {}).items()}) + return names def _without_element_ids(trace): @@ -145,7 +160,7 @@ def test_every_traced_element_is_found_in_the_imported_project(client, project, """Without ids in the structural section the import gives elements new ids; the trace follows.""" body = _import(client, _export(client, {**project, "trace": trace})).json() (diagram,) = body["project"]["diagrams"]["ClassDiagram"] - imported = {**diagram["model"]["elements"], **diagram["model"]["relationships"]} + imported = _names_by_id(diagram["model"]) for artifact in body["trace"]["artifacts"]: if artifact["type"] != "ModelArtifact" or artifact["name"] == "Ghost": continue @@ -153,7 +168,7 @@ def test_every_traced_element_is_found_in_the_imported_project(client, project, assert artifact["elementId"] == diagram["id"] continue assert artifact["elementId"] in imported, artifact - label = imported[artifact["elementId"]].get("name") or "" + label = imported[artifact["elementId"]] or "" assert artifact["name"] in label or label in artifact["name"], artifact # "open" in "+ open()" ghost = next(a for a in body["trace"]["artifacts"] if a["name"] == "Ghost") assert ghost["elementId"] == "gone" # deleted: nothing to match, the record keeps its id @@ -163,12 +178,12 @@ def test_two_associations_of_the_same_name_keep_their_own_trace(client, project, """Live: the Library template's two "books" associations; the import names the second ``books_1``, and its trace followed the first one by name.""" model = class_diagram["model"] - author = next(e for e in model["elements"].values() if e.get("name") == "Publication") - (holds_id,) = [k for k, r in model["relationships"].items() if r.get("name") == "holds"] - model["relationships"][holds_id]["name"] = "books" - second = copy.deepcopy(model["relationships"][holds_id]) - second.update(id="writes", source={**second["source"], "element": author["id"]}) - model["relationships"]["writes"] = second + author = next(n for n in model["nodes"] if n["data"].get("name") == "Publication") + (holds,) = [e for e in model["edges"] if e["data"].get("name") == "holds"] + holds["data"]["name"] = "books" + second = copy.deepcopy(holds) + second.update(id="writes", source=author["id"]) + model["edges"].append(second) project = {**project, "diagrams": {"ClassDiagram": [class_diagram]}} response = client.post("/besser_api/traceability/generate-output", json={ **class_diagram, "generator": "sqlalchemy", "config": {"dbms": "sqlite"}, "actorName": "Ada Lovelace", @@ -181,9 +196,9 @@ def test_two_associations_of_the_same_name_keep_their_own_trace(client, project, body = _import(client, _export(client, {**project, "trace": trace})).json() (diagram,) = body["project"]["diagrams"]["ClassDiagram"] imported = diagram["model"] - names = {e["id"]: e.get("name") for e in imported["elements"].values()} - ends_of = {rid: {names[r["source"]["element"]], names[r["target"]["element"]]} - for rid, r in imported["relationships"].items() if r["type"] != "ClassInheritance"} + names = _names_by_id(imported) + ends_of = {e["id"]: {names[e["source"]], names[e["target"]]} + for e in imported["edges"] if e["type"] != "ClassInheritance"} associations = [a for a in body["trace"]["artifacts"] if a["type"] == "ModelArtifact" and a["elementType"] == "BinaryAssociation"] # Each artifact found its own association, not both the first one. @@ -293,7 +308,7 @@ def gui_trace(client, gui_project): **class_diagram, "generator": "sqlalchemy", "config": {"dbms": "sqlite"}, "actorName": "Ada Lovelace"}) assert response.status_code == 200, response.text trace = {**response.json()["trace"], "projectId": "project-1"} - book_id = next(e["id"] for e in class_diagram["model"]["elements"].values() if e.get("name") == "Book") + book_id = next(n["id"] for n in class_diagram["model"]["nodes"] if n["data"].get("name") == "Book") book = next(a for a in trace["artifacts"] if a.get("elementId") == book_id) gui_artifacts = [ {"id": "a-gui", "type": "ModelArtifact", "name": "GUI Diagram", "elementId": "gui-diagram", @@ -338,7 +353,7 @@ def test_a_gui_trace_matches_the_imported_gui_not_the_class_diagram(client, gui_ assert f'"{artifacts[artifact_id]["elementId"]}"' in gui_json assert artifacts["a-gone"]["elementId"] == "gone-button" # deleted: kept as a record # The class side still matches by name. - book = next(e["id"] for e in class_diagram["model"]["elements"].values() if e.get("name") == "Book") + book = next(n["id"] for n in class_diagram["model"]["nodes"] if n["data"].get("name") == "Book") assert any(a.get("elementId") == book and a["elementType"] == "Class" for a in artifacts.values()) assert body["trace"]["traceLinks"] == gui_trace["traceLinks"] @@ -400,17 +415,16 @@ def test_generated_element_traces_find_their_elements_in_the_imported_project(cl (agent_back,), (bpmn_back,), (quantum_back,) = (diagrams["AgentDiagram"], diagrams["BPMN"], diagrams["QuantumCircuitDiagram"]) - agent_elements = {**agent_back["model"]["elements"], **agent_back["model"].get("components", {})} + agent_elements = _names_by_id(agent_back["model"]) states_and_intents = [a for a in _element_artifacts(body["trace"], "Agent") if a["elementType"] in ("AgentState", "Intent")] assert states_and_intents for artifact in states_and_intents: - assert agent_elements[artifact["elementId"]]["name"] == artifact["name"] + assert agent_elements[artifact["elementId"]] == artifact["name"] bpmn_elements = _element_artifacts(body["trace"], "BPMNModel") assert bpmn_elements - assert {a["elementId"] for a in bpmn_elements} <= (set(bpmn_back["model"]["elements"]) - | set(bpmn_back["model"]["relationships"])) + assert {a["elementId"] for a in bpmn_elements} <= set(_names_by_id(bpmn_back["model"])) gates = _element_artifacts(body["trace"], "QuantumCircuit") assert {a["elementId"] for a in gates} == {f"{quantum_back['id']}:gate:0:0", f"{quantum_back['id']}:gate:1:1"} diff --git a/tests/utilities/web_modeling_editor/backend/test_sdmx_import.py b/tests/utilities/web_modeling_editor/backend/test_sdmx_import.py index acb25c06e..7be403eba 100644 --- a/tests/utilities/web_modeling_editor/backend/test_sdmx_import.py +++ b/tests/utilities/web_modeling_editor/backend/test_sdmx_import.py @@ -91,7 +91,7 @@ def test_import_from_a_preset_provider(fake_fetch): data = resp.json() assert data["diagramType"] == "ClassDiagram" and data["model"]["type"] == "ClassDiagram" assert data["title"] == "MyModel" - names = {e["name"] for e in data["model"]["elements"].values() if e.get("type") in ("Class", "Enumeration")} + names = {n["data"]["name"] for n in data["model"]["nodes"] if n.get("type") == "class"} assert {"Observation", "Freq", "Product"} <= names assert fake_fetch == [("eurostat", "https://ec.europa.eu/eurostat/api/dissemination/sdmx/2.1", None, "DF_TEST", "latest", True)] diff --git a/tests/utilities/web_modeling_editor/backend/test_supabase_generation_v4.py b/tests/utilities/web_modeling_editor/backend/test_supabase_generation_v4.py new file mode 100644 index 000000000..62d247625 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/test_supabase_generation_v4.py @@ -0,0 +1,164 @@ +""" +Route-level tests for Supabase generation from v4 ClassDiagram payloads. + +POSTs the canonical v4 wire shape ({nodes, edges}) to /besser_api/generate-output +with generator='supabase' and exercises the user_root config contract: + +- valid user_root -> 200, stable HTTP filename supabase_output.sql, auth.users mirror +- empty user_root -> 200, auth integration skipped (no mirror, no RLS) +- invalid user_root -> 400 with the exact router detail message +""" + +import asyncio +import re + +import pytest +import httpx +from httpx._transports.asgi import ASGITransport + +from besser.utilities.web_modeling_editor.backend.backend import app + +BASE_URL = "http://testserver" + +_INVALID_USER_ROOT_DETAIL = ( + "Invalid user_root: must be a class name matching " + "[A-Za-z_][A-Za-z0-9_]{0,62} (or empty to skip auth integration)." +) + + +def _post(url: str, **kwargs) -> httpx.Response: + async def _request(): + transport = ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url=BASE_URL) as ac: + return await ac.request("POST", url, **kwargs) + + return asyncio.run(_request()) + + +@pytest.fixture(autouse=True) +def isolate_backend_test_artifacts(tmp_path, monkeypatch): + """Keep generated test artifacts out of the repository root.""" + monkeypatch.chdir(tmp_path) + + +@pytest.fixture +def user_rooted_class_diagram_model(): + """v4 ClassDiagram: User (isId attr) 1 --< 0..* Note.""" + return { + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "class-user", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "User", "stereotype": None, + "attributes": [ + {"id": "attr-user-id", "name": "id", "attributeType": "str", + "visibility": "public", "isId": True}, + ], + "methods": [], + }, + }, + { + "id": "class-note", "type": "class", + "position": {"x": 300, "y": 0}, "width": 160, "height": 100, + "measured": {"width": 160, "height": 100}, + "data": { + "name": "Note", "stereotype": None, + "attributes": [ + {"id": "attr-note-id", "name": "id", "attributeType": "str", + "visibility": "public", "isId": True}, + {"id": "attr-note-title", "name": "title", "attributeType": "str", + "visibility": "public"}, + ], + "methods": [], + }, + }, + ], + "edges": [ + { + "id": "rel-user-note", + "source": "class-user", "target": "class-note", + "type": "ClassBidirectional", + "sourceHandle": "Right", "targetHandle": "Left", + "data": { + "name": "user_note", + "sourceRole": "user", "sourceMultiplicity": "1", + "targetRole": "notes", "targetMultiplicity": "0..*", + "points": [], + }, + }, + ], + } + + +@pytest.fixture +def supabase_input(user_rooted_class_diagram_model): + """DiagramInput payload targeting the supabase generator.""" + return { + "title": "SupabaseDemo", + "model": user_rooted_class_diagram_model, + "generator": "supabase", + } + + +class TestSupabaseGenerateOutputV4: + """POST /besser_api/generate-output with generator='supabase' (v4 model).""" + + def test_supabase_registered_in_supported_generators(self): + async def _request(): + transport = ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url=BASE_URL) as ac: + return await ac.get("/besser_api/") + + response = asyncio.run(_request()) + assert response.status_code == 200 + assert "supabase" in response.json()["supported_generators"] + + def test_generate_supabase_with_user_root(self, supabase_input): + """Valid user_root yields auth.users mirroring + RLS, migration-style filename.""" + payload = {**supabase_input, "config": {"user_root": "User"}} + response = _post("/besser_api/generate-output", json=payload) + assert response.status_code == 200, response.text + + content_disp = response.headers.get("content-disposition", "") + assert re.search(r'filename="\d{14}_supabasedemo\.sql"', content_disp), content_disp + + body = response.text + assert "auth.users" in body + assert "handle_new_user" in body + assert 'CREATE TABLE IF NOT EXISTS public."user"' in body + assert 'CREATE TABLE IF NOT EXISTS public."note"' in body + assert "ENABLE ROW LEVEL SECURITY" in body + + def test_generate_supabase_empty_user_root_skips_auth(self, supabase_input): + """Empty user_root means 'skip auth integration' (no mirror, no RLS).""" + payload = {**supabase_input, "config": {"user_root": ""}} + response = _post("/besser_api/generate-output", json=payload) + assert response.status_code == 200, response.text + + body = response.text + assert "auth.users" not in body + assert "handle_new_user" not in body + assert "ENABLE ROW LEVEL SECURITY" not in body + # The tables themselves are still emitted. + assert 'CREATE TABLE IF NOT EXISTS public."user"' in body + assert 'CREATE TABLE IF NOT EXISTS public."note"' in body + + def test_generate_supabase_invalid_user_root_returns_400(self, supabase_input): + """An injection-shaped user_root is rejected at the HTTP boundary.""" + payload = {**supabase_input, "config": {"user_root": 'Robert"; DROP'}} + response = _post("/besser_api/generate-output", json=payload) + assert response.status_code == 400 + assert response.json()["detail"] == _INVALID_USER_ROOT_DETAIL + + def test_generate_supabase_missing_user_root_defaults_to_user(self, supabase_input): + """Omitting user_root entirely falls back to DEFAULT_SUPABASE_USER_ROOT.""" + response = _post("/besser_api/generate-output", json=supabase_input) + assert response.status_code == 200, response.text + body = response.text + # Default 'User' matches the diagram's User class -> auth integration on. + assert "auth.users" in body + assert "handle_new_user" in body diff --git a/tests/utilities/web_modeling_editor/backend/test_traceability_endpoint.py b/tests/utilities/web_modeling_editor/backend/test_traceability_endpoint.py index 0b4ff5a8e..be509f174 100644 --- a/tests/utilities/web_modeling_editor/backend/test_traceability_endpoint.py +++ b/tests/utilities/web_modeling_editor/backend/test_traceability_endpoint.py @@ -15,6 +15,11 @@ URL = "/besser_api/traceability/generate-output" +def _classes(model: dict) -> dict: + """Node id -> name of the plain classes of a v4 class diagram.""" + return {n["id"]: n["data"]["name"] for n in model["nodes"] if n["type"] == "class" and not n["data"].get("stereotype")} + + @pytest.fixture def payload(library_book_author_model): return { @@ -45,7 +50,7 @@ def test_trace_links_each_class_to_its_definition_line(payload, traced): trace = traced["trace"] lines = base64.b64decode(traced["contentBase64"]).decode("utf-8").split("\n") artifacts = {a["id"]: a for a in trace["artifacts"]} - class_ids = {e["id"]: e["name"] for e in payload["model"]["elements"].values() if e["type"] == "Class"} + class_ids = _classes(payload["model"]) linked = {} for link in trace["traceLinks"]: source, target = artifacts[link["sourceId"]], artifacts[link["targetId"]] @@ -195,7 +200,7 @@ def test_backend_trace_covers_its_files_and_points_at_their_lines(payload, trace files = {a["path"]: a for a in artifacts.values() if a["type"] == "CodeArtifact" and "startLine" not in a} # Every generated text file is in the trace (the provenance note is added to the ZIP, not generated). assert set(files) == set(entries) - {"BESSER_GENERATION.md"} - classes = {e["id"]: e["name"] for e in payload["model"]["elements"].values() if e["type"] == "Class"} + classes = _classes(payload["model"]) whole_files, lines = {}, {} for link in trace["traceLinks"]: source, target = artifacts[link["sourceId"]], artifacts[link["targetId"]] diff --git a/tests/utilities/web_modeling_editor/backend/test_traced_generation_all.py b/tests/utilities/web_modeling_editor/backend/test_traced_generation_all.py index 8e170bea5..b30754463 100644 --- a/tests/utilities/web_modeling_editor/backend/test_traced_generation_all.py +++ b/tests/utilities/web_modeling_editor/backend/test_traced_generation_all.py @@ -67,15 +67,16 @@ def _quantum_diagram() -> dict: def _deployment_diagram(agent_diagram_id=None) -> dict: """A node running two artifacts, one of them the agent of ``agent_diagram_id`` when given.""" - def element(element_id, element_type, name, owner=None, **extra): - return {"id": element_id, "type": element_type, "name": name, "owner": owner, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}, **extra} + def node(node_id, node_type, name, parent=None, **data): + node = {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": {"name": name, **data}} + return {**node, "parentId": parent} if parent else node agent = {"agentModelRef": agent_diagram_id} if agent_diagram_id else {} return {"id": "deployment-diagram", "title": "Cloud", "model": { - "version": "3.0.0", "type": "DeploymentDiagram", "relationships": {}, - "elements": {"node-1": element("node-1", "DeploymentNode", "server"), - "artifact-api": element("artifact-api", "DeploymentArtifact", "api", "node-1"), - "artifact-bot": element("artifact-bot", "DeploymentArtifact", "librarybot", "node-1", **agent)}}} + "version": "4.0.0", "type": "DeploymentDiagram", "edges": [], + "nodes": [node("node-1", "deploymentNode", "server", stereotype="node"), + node("artifact-api", "deploymentArtifact", "api", "node-1"), + node("artifact-bot", "deploymentArtifact", "librarybot", "node-1", **agent)]}} DEPLOYMENT_DIAGRAM = _deployment_diagram() @@ -84,20 +85,18 @@ def element(element_id, element_type, name, owner=None, **extra): def _alloy_class_diagram() -> dict: """The library diagram without the attribute types the Alloy translation refuses (float, datetime, ...).""" diagram = json.loads(json.dumps(CLASS_DIAGRAM)) - elements = diagram["model"]["elements"] - refused = {key for key, element in elements.items() if element.get("type") == "ClassAttribute" - and str(element.get("attributeType", "")).lower() in {"float", "datetime", "time", "timedelta", "any"}} - for key in refused: - del elements[key] - for element in elements.values(): - if isinstance(element.get("attributes"), list): - element["attributes"] = [key for key in element["attributes"] if key not in refused] + refused = {"float", "datetime", "time", "timedelta", "any"} + for node in diagram["model"]["nodes"]: + if node["type"] == "class": + node["data"]["attributes"] = [row for row in node["data"].get("attributes") or [] + if str(row.get("attributeType", "")).lower() not in refused] return diagram OBJECT_DIAGRAM = {"id": "object-diagram", "title": "Books", "model": { - "type": "ObjectDiagram", "relationships": {}, - "elements": {"o1": {"id": "o1", "type": "ObjectName", "name": "dune", "className": "Book", "attributes": []}}, + "version": "4.0.0", "type": "ObjectDiagram", "edges": [], + "nodes": [{"id": "o1", "type": "objectName", "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": {"name": "dune", "className": "Book", "attributes": [], "methods": []}}], "referenceDiagramData": {"title": CLASS_DIAGRAM["title"], "model": CLASS_DIAGRAM["model"]}}} # What each generator runs on: the diagram it reads at /generate-output, its config, and the @@ -192,16 +191,15 @@ def _assert_same_delivery_and_a_valid_trace(generator, traced_response, plain_re def _editor_ids(diagram: dict) -> set: """The ids the editor knows the elements of ``diagram`` by: the keys and ``id`` values its JSON holds - at any depth (Apollon elements and relationships, GUI pages and components' ``attributes.id``), and + at any depth (nodes, edges and their rows, agent components, GUI pages and components' ``attributes.id``), and for a quantum circuit, whose cells have no ids, each gate's cell (``:gate::``, the editor's ``snapshotQuantumModel``).""" ids, pending = set(), [diagram["model"]] while pending: value = pending.pop() if isinstance(value, dict): - for key in ("elements", "relationships", "components"): - if isinstance(value.get(key), dict): - ids.update(value[key]) + if isinstance(value.get("components"), dict): # an agent diagram's intents, tools, ... + ids.update(value["components"]) if isinstance(value.get("id"), str): ids.add(value["id"]) pending.extend(value.values()) @@ -300,7 +298,7 @@ def test_the_web_app_traces_the_lines_of_its_backend(client): trace = client.post(TRACED_PROJECT, json=project).json()["trace"] fragments = {a["path"] for a in trace["artifacts"] if a["type"] == "CodeArtifact" and "startLine" in a} assert {"backend/sql_alchemy.py", "backend/pydantic_classes.py", "backend/main_api.py"} <= fragments - book = next(e["id"] for e in CLASS_DIAGRAM["model"]["elements"].values() if e.get("name") == "Book") + book = next(n["id"] for n in CLASS_DIAGRAM["model"]["nodes"] if n["data"].get("name") == "Book") book_artifact = next(a for a in trace["artifacts"] if a.get("elementId") == book) class_root = next(a for a in trace["artifacts"] if a.get("elementId") == "class-diagram") assert book_artifact["parentId"] == class_root["id"] diff --git a/tests/utilities/web_modeling_editor/backend/test_user_display_name_spaces.py b/tests/utilities/web_modeling_editor/backend/test_user_display_name_spaces.py index 863595801..b6a665047 100644 --- a/tests/utilities/web_modeling_editor/backend/test_user_display_name_spaces.py +++ b/tests/utilities/web_modeling_editor/backend/test_user_display_name_spaces.py @@ -13,26 +13,25 @@ ) -def _box(): - return {"x": 0, "y": 0, "width": 200, "height": 100} +def _node(node_id, data): + return {"id": node_id, "type": "UserModelName", "position": {"x": 0, "y": 0}, + "width": 200, "height": 100, "data": data} def _model(name_row="name = Alice Smith"): # The editor labels the User box with the profile name and writes `name = `. return { + "version": "4.0.0", "type": "UserDiagram", - "elements": { - "u": {"id": "u", "type": "UserModelName", "className": "User", "name": "Alice Smith", - "attributes": ["un"], "methods": [], "owner": None, "bounds": _box()}, - "un": {"id": "un", "type": "UserModelAttribute", "name": name_row, "owner": "u", "bounds": _box()}, - "d": {"id": "d", "type": "UserModelName", "className": "Disability", "name": "low vision", - "attributes": [], "methods": [], "owner": None, "bounds": _box()}, - }, - "relationships": { - "l": {"id": "l", "name": "", "type": "ObjectLink", "owner": None, "bounds": _box(), - "source": {"element": "u", "direction": "Right"}, - "target": {"element": "d", "direction": "Left"}}, - }, + "nodes": [ + _node("u", {"className": "User", "name": "Alice Smith", + "attributes": [{"id": "un", "name": name_row}], "methods": []}), + _node("d", {"className": "Disability", "name": "low vision", "attributes": [], "methods": []}), + ], + "edges": [ + {"id": "l", "type": "UserModelLink", "source": "u", "target": "d", + "sourceHandle": "right", "targetHandle": "left", "data": {"name": "", "points": []}}, + ], } diff --git a/tests/utilities/web_modeling_editor/backend/test_user_name_repair.py b/tests/utilities/web_modeling_editor/backend/test_user_name_repair.py index 09cfc0f87..13c4bdbdd 100644 --- a/tests/utilities/web_modeling_editor/backend/test_user_name_repair.py +++ b/tests/utilities/web_modeling_editor/backend/test_user_name_repair.py @@ -4,16 +4,19 @@ from besser.utilities.web_modeling_editor.backend.routers.validation_router import validate_diagram +def _user(node_id, name, rows): + return {"id": node_id, "type": "UserModelName", "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": {"name": name, "className": "User", "attributes": rows}} + + def test_unnamed_users_warn_without_blocking_and_only_missing_fields_are_repaired(): # Profiles saved before User.name existed, and those the modeling agent builds # (its User metamodel has no name), must still validate and generate. - model = {"type": "UserDiagram", "elements": { - "old": {"type": "UserModelName", "className": "User", "name": "user_1", "attributes": []}, - "empty": {"type": "UserModelName", "className": "User", "name": "user_2", "attributes": ["empty_name"]}, - "empty_name": {"type": "UserModelAttribute", "name": "name = "}, - "named": {"type": "UserModelName", "className": "User", "name": "user_3", "attributes": ["named_name"]}, - "named_name": {"type": "UserModelAttribute", "name": "name = Alice"}, - }, "relationships": {}} + model = {"version": "4.0.0", "type": "UserDiagram", "nodes": [ + _user("old", "user_1", []), + _user("empty", "user_2", [{"id": "empty_name", "name": "name = "}]), + _user("named", "user_3", [{"id": "named_name", "name": "name = Alice"}]), + ], "edges": []} result = asyncio.run(validate_diagram(DiagramInput(title="Users", model=model), None, None)) assert result["isValid"] is True, result["errors"] assert any("no name" in warning for warning in result["warnings"]) @@ -21,10 +24,9 @@ def test_unnamed_users_warn_without_blocking_and_only_missing_fields_are_repaire def test_named_users_carry_no_name_warning(): - model = {"type": "UserDiagram", "elements": { - "named": {"type": "UserModelName", "className": "User", "name": "user_1", "attributes": ["named_name"]}, - "named_name": {"type": "UserModelAttribute", "name": "name = Alice"}, - }, "relationships": {}} + model = {"version": "4.0.0", "type": "UserDiagram", "nodes": [ + _user("named", "user_1", [{"id": "named_name", "name": "name = Alice"}]), + ], "edges": []} result = asyncio.run(validate_diagram(DiagramInput(title="Users", model=model), None, None)) assert result["isValid"] is True, result["errors"] assert not any("no name" in warning for warning in result["warnings"]) diff --git a/tests/utilities/web_modeling_editor/backend/test_user_profile_download.py b/tests/utilities/web_modeling_editor/backend/test_user_profile_download.py index 64f7495bf..546626980 100644 --- a/tests/utilities/web_modeling_editor/backend/test_user_profile_download.py +++ b/tests/utilities/web_modeling_editor/backend/test_user_profile_download.py @@ -7,26 +7,26 @@ import pytest +def _node(node_id, data): + return {'id': node_id, 'type': 'UserModelName', 'position': {'x': 0, 'y': 0}, + 'width': 200, 'height': 100, 'data': data} + + @pytest.mark.parametrize('count', [1, 2]) def test_user_profile_download_contains_generated_json(client, count): - elements = { - f'user-{i}': { - 'id': f'user-{i}', 'type': 'UserModelName', 'name': f'user_{i}', - 'className': 'User', 'attributes': [f'name-{i}'], + nodes = [ + _node(f'user-{i}', { + 'name': f'user_{i}', 'className': 'User', + 'attributes': [{'id': f'name-{i}', 'name': f'name = Person{i}', + 'personalization': {'content': {'adaptContentToUserProfile': True}}}], 'personalization': {'presentation': {'language': f'language_{i}'}, 'gui': {'modality': {'readAloud': True}}}, - } - for i in range(1, count + 1) - } - elements.update({ - f'name-{i}': {'id': f'name-{i}', 'type': 'UserModelAttribute', 'owner': f'user-{i}', - 'name': f'name = Person{i}', - 'personalization': {'content': {'adaptContentToUserProfile': True}}} + }) for i in range(1, count + 1) - }) + ] response = client.post('/besser_api/generate-output', json={ 'title': 'Profiles', 'generator': 'jsonobject', - 'model': {'type': 'UserDiagram', 'elements': elements, 'relationships': {}}, + 'model': {'version': '4.0.0', 'type': 'UserDiagram', 'nodes': nodes, 'edges': []}, }) assert response.status_code == 200, response.text assert response.content @@ -57,10 +57,10 @@ def test_download_keeps_rules_captured_before_editor_merges_profile_boxes(client ] response = client.post('/besser_api/generate-output', json={ 'title': 'Profile', 'generator': 'jsonobject', - 'model': {'type': 'UserDiagram', 'elements': { - 'root': {'id': 'root', 'type': 'UserModelName', 'name': 'user_1', 'className': 'User', - 'attributes': [], 'profilePersonalizationRules': captured}, - }, 'relationships': {}}, + 'model': {'version': '4.0.0', 'type': 'UserDiagram', 'nodes': [ + _node('root', {'name': 'user_1', 'className': 'User', + 'attributes': [], 'profilePersonalizationRules': captured}), + ], 'edges': []}, }) assert response.status_code == 200, response.text assert response.json()['personalizationRules'] == captured diff --git a/tests/utilities/web_modeling_editor/backend/test_v4_round_trip.py b/tests/utilities/web_modeling_editor/backend/test_v4_round_trip.py new file mode 100644 index 000000000..5149eecf5 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/test_v4_round_trip.py @@ -0,0 +1,458 @@ +"""Round-trip tests for the v4 wire shape. + +Each test loads a hand-authored v4 fixture from ``tests/fixtures/v4/``, +runs it through the JSON->BUML processor, then back through the +BUML->JSON converter, and asserts the structural shape survives. + +We deliberately compare a *structural projection* of the model rather +than byte equality: layout positions are recomputed by the converter +and uuid-keyed ids may not match when the metamodel has its own ids. +The properties verified are: + +- diagram type matches +- nodes are produced +- edges are produced (when the fixture has any) +- node ``type`` distribution matches the input +- edge ``type`` distribution matches the input +- key ``data.name`` values for top-level nodes survive +""" + +from __future__ import annotations + +import json +import os +from collections import Counter + +import pytest + +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.class_diagram_processor import ( + process_class_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.class_diagram_converter import ( + class_buml_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.state_machine_processor import ( + process_state_machine, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.state_machine_converter import ( + state_machine_object_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.object_diagram_processor import ( + process_object_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.agent_diagram_processor import ( + process_agent_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( + process_nn_diagram, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.nn_diagram_converter import ( + nn_model_to_json, +) + + +FIXTURES_DIR = os.path.join( + os.path.dirname(__file__), "..", "..", "..", "fixtures", "v4" +) + + +def _load(name: str) -> dict: + path = os.path.normpath(os.path.join(FIXTURES_DIR, name)) + with open(path) as f: + return json.load(f) + + +def _v4_data(d: dict) -> dict: + """Return the inner v4 ``model`` dict from a top-level fixture / output.""" + if "nodes" in d or "edges" in d: + return d + return d.get("model") or {} + + +def _node_types(d: dict) -> Counter: + inner = _v4_data(d) + return Counter(n.get("type") for n in inner.get("nodes") or []) + + +def _edge_types(d: dict) -> Counter: + inner = _v4_data(d) + return Counter(e.get("type") for e in inner.get("edges") or []) + + +def _top_level_names(d: dict) -> set[str]: + inner = _v4_data(d) + return { + (n.get("data") or {}).get("name") + for n in inner.get("nodes") or [] + if not n.get("parentId") + } + + +# --------------------------------------------------------------------------- +# Class diagram round-trip +# --------------------------------------------------------------------------- + +def test_v4_class_diagram_round_trip(): + fixture = _load("class_diagram_basic.json") + domain_model = process_class_diagram(fixture) + re_emitted = class_buml_to_json(domain_model) + assert re_emitted.get("type") == "ClassDiagram" + # ``nodes`` and ``edges`` must be present at the top level. + assert isinstance(re_emitted.get("nodes"), list) + assert isinstance(re_emitted.get("edges"), list) + # Node-type distribution preserved (Book, Author both `class`, + # Genre `class` with stereotype 'Enumeration' also surfaces as 'class'; + # the OCL sticky note keeps its own node type). + types_in = _node_types(fixture) + types_out = _node_types(re_emitted) + assert types_out["class"] == types_in["class"] + assert types_out["ClassOCLConstraint"] == types_in["ClassOCLConstraint"] + # Edge-type distribution preserved (incl. the visual OCL link). + edges_in = _edge_types(fixture) + edges_out = _edge_types(re_emitted) + assert edges_in["ClassBidirectional"] == edges_out["ClassBidirectional"] + assert edges_in["ClassOCLLink"] == edges_out["ClassOCLLink"] + # Top-level class names round-trip. + names = _top_level_names(re_emitted) + assert "Book" in names + assert "Author" in names + assert "Genre" in names + + +def test_v4_class_diagram_stereotype_capitalized_on_emit(): + """The frontend compares stereotypes case-sensitively against the + capitalized canonical forms — the converter must emit 'Enumeration' + (and 'Abstract'), never the lowercase variants.""" + fixture = _load("class_diagram_basic.json") + re_emitted = class_buml_to_json(process_class_diagram(fixture)) + genre = next( + n for n in re_emitted["nodes"] + if (n.get("data") or {}).get("name") == "Genre" + ) + assert genre["data"]["stereotype"] == "Enumeration" + + +def test_v4_class_diagram_method_rows_structured(): + """Method rows re-emit in the canonical inspector shape: bare name, + structured ``parameters`` and ``returnType`` mirrored onto + ``attributeType``.""" + fixture = _load("class_diagram_basic.json") + re_emitted = class_buml_to_json(process_class_diagram(fixture)) + book = next( + n for n in re_emitted["nodes"] + if (n.get("data") or {}).get("name") == "Book" + ) + methods = book["data"]["methods"] + assert len(methods) == 1 + method = methods[0] + assert method["name"] == "summary" + assert method["returnType"] == "str" + assert method["attributeType"] == "str" + assert [(p["name"], p["parameterType"]) for p in method["parameters"]] == [ + ("verbose", "bool"), + ] + + +def test_v4_library_ocl_template_round_trip(): + """The real Library_OCL webapp template (4 classes, 11 sticky-note OCL + constraints incl. method pre/post) survives JSON -> BUML -> JSON with + every constraint re-emitted as a visible, linked node.""" + template = _load("library_ocl_template.json") + domain_model = process_class_diagram( + {"title": template.get("title") or "Library_OCL", "model": template} + ) + assert domain_model.ocl_warnings == [] + # 7 class-level invariants in ``constraints``; the other 4 are method + # pre/post conditions routed onto ``Method.pre`` / ``Method.post``. + assert len(domain_model.constraints) == 7 + pre_post = sum( + len(getattr(m, "pre", []) or []) + len(getattr(m, "post", []) or []) + for t in domain_model.types if isinstance(getattr(t, "methods", None), (set, list)) + for m in t.methods + ) + assert pre_post == 4 + + re_emitted = class_buml_to_json(domain_model) + types_out = _node_types(re_emitted) + edges_out = _edge_types(re_emitted) + assert types_out["class"] == 4 + assert types_out["ClassOCLConstraint"] == 11 + assert edges_out["ClassOCLLink"] == 11 + assert edges_out["ClassBidirectional"] == 2 + + +# --------------------------------------------------------------------------- +# State machine round-trip +# --------------------------------------------------------------------------- + +def _class_node(node_id, name, x, y, **extra): + data = {"name": name, "attributes": [], "methods": [], **extra.pop("data", {})} + return {"id": node_id, "type": "class", "position": {"x": x, "y": y}, + "width": 160, "height": 100, "data": data, **extra} + + +def _class_round_trip(nodes, edges=()): + model = {"version": "4.0.0", "type": "ClassDiagram", "nodes": list(nodes), "edges": list(edges)} + return class_buml_to_json(process_class_diagram({"title": "Shapes", "model": model})) + + +def test_v4_class_in_package_keeps_its_absolute_position(): + """A child ``position`` is relative to its package. The package is not + re-emitted, so the class and enumeration must come back at absolute positions.""" + package = {"id": "pkg", "type": "package", "position": {"x": 300, "y": 200}, + "width": 500, "height": 400, "data": {"name": "shapes"}} + out = _class_round_trip([ + package, + _class_node("c-circle", "Circle", 40, 60, parentId="pkg"), + _class_node("e-kind", "Kind", 250, 60, parentId="pkg", data={"stereotype": "Enumeration"}), + _class_node("c-free", "Free", 10, 20), + ]) + + positions = {n["data"]["name"]: n["position"] for n in out["nodes"]} + assert not [n for n in out["nodes"] if n.get("parentId")] + assert positions == { + "Circle": {"x": 340, "y": 260}, + "Kind": {"x": 550, "y": 260}, + "Free": {"x": 10, "y": 20}, + } + + +def test_v4_generalization_keeps_its_handles_and_points(): + points = [{"x": 80, "y": 300}, {"x": 80, "y": 100}] + inheritance = {"id": "g1", "source": "c-circle", "target": "c-shape", "type": "ClassInheritance", + "sourceHandle": "top", "targetHandle": "bottom", "data": {"points": points}} + out = _class_round_trip( + [_class_node("c-shape", "Shape", 0, 0), _class_node("c-circle", "Circle", 0, 300)], + [inheritance], + ) + + [edge] = out["edges"] + assert (edge["type"], edge["source"], edge["target"]) == ("ClassInheritance", "c-circle", "c-shape") + assert (edge["sourceHandle"], edge["targetHandle"]) == ("top", "bottom") + assert edge["data"]["points"] == points + + +def test_v4_class_colours_round_trip(): + colours = {"fillColor": "#ffeecc", "strokeColor": "#112233", "textColor": "#445566"} + out = _class_round_trip([ + _class_node("c-shape", "Shape", 0, 0, data=dict(colours)), + _class_node("e-kind", "Kind", 300, 0, data={"stereotype": "Enumeration", "fillColor": "#00ff00"}), + _class_node("c-plain", "Plain", 600, 0), + ]) + + data = {n["data"]["name"]: n["data"] for n in out["nodes"]} + assert {key: data["Shape"].get(key) for key in colours} == colours + assert data["Kind"].get("fillColor") == "#00ff00" + assert not {"fillColor", "strokeColor", "textColor"} & set(data["Plain"]) + + +def test_v4_state_machine_round_trip(): + fixture = _load("state_machine_basic.json") + sm = process_state_machine(fixture) + re_emitted = state_machine_object_to_json(sm) + assert re_emitted.get("type") == "StateMachineDiagram" + assert isinstance(re_emitted.get("nodes"), list) + assert isinstance(re_emitted.get("edges"), list) + types_out = _node_types(re_emitted) + # Two named states + an initial node. + assert types_out["State"] == 2 + assert types_out["StateInitialNode"] >= 1 + edges_out = _edge_types(re_emitted) + # Initial transition + Red->Green transition. + assert edges_out["StateTransition"] >= 2 + + +# --------------------------------------------------------------------------- +# Agent diagram round-trip +# --------------------------------------------------------------------------- + +def test_v4_agent_diagram_round_trip(): + fixture = _load("agent_diagram_basic.json") + agent = process_agent_diagram(fixture) + assert agent is not None + assert any(s.name == "Greeting" for s in agent.states) + assert any(i.name == "greet" for i in agent.intents) + # The intent's training utterances come from ``data.training_phrases``. + greet = next(i for i in agent.intents if i.name == "greet") + assert sorted(greet.training_sentences) == ["hello", "hi"] + # The LLM body's system prompt rides on the body row name and lands on + # ``LLMReply.prompt``. + ai_help = next(s for s in agent.states if s.name == "AIHelp") + llm_actions = [a for a in ai_help.body.actions if type(a).__name__ == "LLMReply"] + assert [a.prompt for a in llm_actions] == ["You are a friendly gym assistant."] + # The comment node tethered to Greeting lands on the state metadata. + greeting = next(s for s in agent.states if s.name == "Greeting") + assert greeting.metadata is not None + assert greeting.metadata.description == "Welcomes the user." + + +def test_v4_agent_diagram_full_chain_re_emits_v4_shape(): + """JSON -> Agent metamodel -> generated Python -> JSON: the v4 node / + edge types, the LLM prompt, the training phrases and the comment all + survive the full export/import chain.""" + import tempfile + + from besser.utilities.buml_code_builder.agent_model_builder import ( + agent_model_to_code, + ) + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.agent_diagram_converter import ( + agent_buml_to_json, + ) + + fixture = _load("agent_diagram_basic.json") + agent = process_agent_diagram(fixture) + with tempfile.TemporaryDirectory() as temp_dir: + path = os.path.join(temp_dir, "agent.py") + agent_model_to_code(agent, path) + with open(path, encoding="utf-8") as f: + re_emitted = agent_buml_to_json(f.read()) + + types_out = _node_types(re_emitted) + edges_out = _edge_types(re_emitted) + assert types_out["AgentState"] == 2 + # Intents are off-canvas components (``model.components``), not nodes. + assert types_out["AgentIntent"] == 0 + assert types_out["comment"] == 1 + assert edges_out["CommentLink"] == 1 + + nodes = re_emitted["nodes"] + ai_help = next( + n for n in nodes + if n["type"] == "AgentState" and n["data"]["name"] == "AIHelp" + ) + # The LLM system prompt is emitted on the row's ``system_message``. + assert [(b["system_message"], b["replyType"], b["actionType"]) for b in ai_help["data"]["bodies"]] == [ + ("You are a friendly gym assistant.", "llm", "LLMReplyAction"), + ] + components = re_emitted["components"] + intent = next(c for c in components.values() if c["type"] == "AgentIntent") + assert intent["name"] == "greet" + assert [components[body_id]["name"] for body_id in intent["bodies"]] == ["hi", "hello"] + assert all(components[body_id]["owner"] == intent["id"] for body_id in intent["bodies"]) + comment = next(n for n in nodes if n["type"] == "comment") + assert comment["data"]["name"] == "Welcomes the user." + + +def test_v4_agent_intent_legacy_bodies_fallback(): + """Older fixtures store training utterances under ``data.bodies`` — + the processor must keep accepting that spelling.""" + fixture = _load("agent_diagram_basic.json") + for node in fixture["model"]["nodes"]: + if node.get("type") == "AgentIntent": + node["data"]["bodies"] = node["data"].pop("training_phrases") + agent = process_agent_diagram(fixture) + greet = next(i for i in agent.intents if i.name == "greet") + assert sorted(greet.training_sentences) == ["hello", "hi"] + + +# --------------------------------------------------------------------------- +# Object diagram round-trip (ingest only — there is no metamodel-to-v4 +# emitter for ObjectModel that runs without parsing generated code). +# --------------------------------------------------------------------------- + +def test_v4_object_diagram_ingest(): + cd_fixture = _load("class_diagram_basic.json") + domain_model = process_class_diagram(cd_fixture) + + od_fixture = _load("object_diagram_basic.json") + obj_model = process_object_diagram(od_fixture, domain_model) + assert obj_model is not None + # v4 ``data.name`` is the instance name only; the class comes from ``classId``. + my_book = next(o for o in obj_model.objects if o.name == "myBook") + assert my_book.classifier.name == "Book" + # v4 attribute rows keep name and runtime value in separate fields + # (``ObjectNodeAttribute.value``) — both slots must ingest, typed. + slot_values = {s.attribute.name: s.value.value for s in my_book.slots} + assert slot_values == {"title": "1984", "pages": 328} + + +# --------------------------------------------------------------------------- +# Reference class diagram extraction (generation router) +# --------------------------------------------------------------------------- + +def test_extract_reference_class_diagram_accepts_v4_shape(): + from besser.utilities.web_modeling_editor.backend.services.generation.dispatch import ( + _extract_reference_class_diagram, + ) + + cd_fixture = _load("class_diagram_basic.json") + payload = { + "title": "Objects", + "model": { + "type": "ObjectDiagram", + "nodes": [], + "edges": [], + "referenceDiagramData": { + "title": cd_fixture["title"], + "model": cd_fixture["model"], + }, + }, + } + extracted = _extract_reference_class_diagram(payload["model"]) + assert extracted is not None + assert extracted["title"] == "Library" + # The extracted payload feeds straight into ``process_class_diagram``. + domain_model = process_class_diagram(extracted) + assert any(t.name == "Book" for t in domain_model.types) + + +def test_extract_reference_class_diagram_rejects_v3_shape(): + from besser.utilities.web_modeling_editor.backend.services.generation.dispatch import ( + _extract_reference_class_diagram, + ) + + legacy = { + "referenceDiagramData": { + "title": "Old", + "model": {"elements": {}, "relationships": {}}, + }, + } + assert _extract_reference_class_diagram(legacy) is None + + +# --------------------------------------------------------------------------- +# GUI processor v4 class-model lookups +# --------------------------------------------------------------------------- + +def test_gui_processor_resolves_v4_class_and_method_rows(): + """v4 keeps the class name on ``node.data.name`` and method rows inside + ``data.methods`` (not as top-level nodes) — the GUI processor's lookup + helpers must resolve both.""" + from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.gui_processors.processor import ( + _element_name, + _find_method_row, + ) + + cd_fixture = _load("class_diagram_basic.json") + class_model = cd_fixture["model"] + book_node = next( + n for n in class_model["nodes"] + if (n.get("data") or {}).get("name") == "Book" + ) + assert _element_name(book_node) == "Book" + row = _find_method_row(book_node, "n-book-m-summary") + assert row is not None + assert row["name"] == "summary" + assert _find_method_row(book_node, "missing-id") is None + # Legacy dicts (name at the top level, rows at the top level) keep working. + legacy_el = {"name": "Legacy", "methods": [{"id": "m-1", "name": "+ run()"}]} + assert _element_name(legacy_el) == "Legacy" + assert _find_method_row(legacy_el, "m-1")["name"] == "+ run()" + + +# --------------------------------------------------------------------------- +# NN diagram round-trip +# --------------------------------------------------------------------------- + +def test_v4_nn_diagram_round_trip(): + fixture = _load("nn_diagram_basic.json") + nn = process_nn_diagram(fixture) + re_emitted = nn_model_to_json(nn) + assert re_emitted.get("type") == "NNDiagram" + assert isinstance(re_emitted.get("nodes"), list) + types_out = _node_types(re_emitted) + # Two LinearLayer + one NNContainer. + assert types_out.get("LinearLayer", 0) == 2 + assert types_out.get("NNContainer", 0) >= 1 + edges_out = _edge_types(re_emitted) + assert edges_out.get("NNNext", 0) >= 1 diff --git a/tests/utilities/web_modeling_editor/backend/test_validate_ocl_error_text.py b/tests/utilities/web_modeling_editor/backend/test_validate_ocl_error_text.py index 014e82878..37652c95d 100644 --- a/tests/utilities/web_modeling_editor/backend/test_validate_ocl_error_text.py +++ b/tests/utilities/web_modeling_editor/backend/test_validate_ocl_error_text.py @@ -24,11 +24,13 @@ def _class_diagram(constraint): - return {"title": "Books", "model": {"type": "ClassDiagram", "elements": { - "c1": {"type": "Class", "name": "Book", "attributes": ["a1"], "methods": []}, - "a1": {"type": "ClassAttribute", "name": "+ title: str", "owner": "c1"}, - "k1": {"type": "ClassOCLConstraint", "constraint": constraint}, - }, "relationships": {}}} + return {"title": "Books", "model": {"version": "4.0.0", "type": "ClassDiagram", "nodes": [ + {"id": "c1", "type": "class", "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": {"name": "Book", "methods": [], "attributes": [ + {"id": "a1", "name": "title", "attributeType": "str", "visibility": "public"}]}}, + {"id": "k1", "type": "ClassOCLConstraint", "position": {"x": 0, "y": 200}, "width": 200, "height": 80, + "data": {"name": "", "expression": constraint}}, + ], "edges": []}} @pytest.fixture diff --git a/tests/utilities/web_modeling_editor/backend/test_validate_ocl_evaluation.py b/tests/utilities/web_modeling_editor/backend/test_validate_ocl_evaluation.py index a030b0f55..88ef585a6 100644 --- a/tests/utilities/web_modeling_editor/backend/test_validate_ocl_evaluation.py +++ b/tests/utilities/web_modeling_editor/backend/test_validate_ocl_evaluation.py @@ -16,20 +16,35 @@ def _object_diagram(title, constraint=INVARIANT): return { "title": "Books", "model": { + "version": "4.0.0", "type": "ObjectDiagram", - "elements": { - "o1": {"type": "ObjectName", "name": "b1", "classId": "c1", "className": "Book", - "attributes": ["oa1"], "methods": []}, - "oa1": {"type": "ObjectAttribute", "name": f"+ title: str = {title}", "owner": "o1"}, - }, - "relationships": {}, - "referenceDiagramData": { - "elements": { - "c1": {"type": "Class", "name": "Book", "attributes": ["a1"], "methods": []}, - "a1": {"type": "ClassAttribute", "name": "+ title: str", "owner": "c1"}, - "k1": {"type": "ClassOCLConstraint", "constraint": constraint}, + "nodes": [{ + "id": "o1", "type": "objectName", "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": { + "name": "b1", "classId": "c1", "className": "Book", "methods": [], + "attributes": [{"id": "oa1", "name": "title", "attributeType": "str", "value": title}], }, - "relationships": {}, + }], + "edges": [], + "referenceDiagramData": { + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + { + "id": "c1", "type": "class", "position": {"x": 0, "y": 0}, "width": 200, "height": 100, + "data": { + "name": "Book", "methods": [], + "attributes": [ + {"id": "a1", "name": "title", "attributeType": "str", "visibility": "public"}, + ], + }, + }, + { + "id": "k1", "type": "ClassOCLConstraint", "position": {"x": 0, "y": 200}, + "width": 200, "height": 80, "data": {"name": "", "expression": constraint}, + }, + ], + "edges": [], }, }, } diff --git a/tests/utilities/web_modeling_editor/converters/nn/fixtures/alexnet.json b/tests/utilities/web_modeling_editor/converters/nn/fixtures/alexnet.json index 57ecd072b..a60503b44 100644 --- a/tests/utilities/web_modeling_editor/converters/nn/fixtures/alexnet.json +++ b/tests/utilities/web_modeling_editor/converters/nn/fixtures/alexnet.json @@ -13,19 +13,14 @@ "id": "acb975da-015d-487a-a1d9-dd4e3cc27675", "title": "Class Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "ClassDiagram", "size": { "width": 1400, "height": 740 }, - "elements": {}, - "relationships": {}, - "interactive": { - "elements": {}, - "relationships": {} - }, - "assessments": {} + "nodes": [], + "edges": [] }, "lastUpdate": "2026-04-08T10:49:34.566Z" } @@ -35,19 +30,14 @@ "id": "7c623073-b25c-458a-928c-79c9a51a9dc4", "title": "Object Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "ObjectDiagram", "size": { "width": 1400, "height": 740 }, - "elements": {}, - "relationships": {}, - "interactive": { - "elements": {}, - "relationships": {} - }, - "assessments": {} + "nodes": [], + "edges": [] }, "lastUpdate": "2026-04-08T10:49:34.566Z" } @@ -57,19 +47,14 @@ "id": "92af6fe9-1e42-4159-99bf-baca64982694", "title": "State Machine Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "StateMachineDiagram", "size": { "width": 1400, "height": 740 }, - "elements": {}, - "relationships": {}, - "interactive": { - "elements": {}, - "relationships": {} - }, - "assessments": {} + "nodes": [], + "edges": [] }, "lastUpdate": "2026-04-08T10:49:34.566Z" } @@ -79,19 +64,14 @@ "id": "3ac42918-e78a-4f30-bf0c-2abf18e00f00", "title": "Agent Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "AgentDiagram", "size": { "width": 1400, "height": 740 }, - "elements": {}, - "relationships": {}, - "interactive": { - "elements": {}, - "relationships": {} - }, - "assessments": {} + "nodes": [], + "edges": [] }, "lastUpdate": "2026-04-08T10:49:34.566Z" } @@ -101,2406 +81,640 @@ "id": "a9ead949-1f15-468f-8516-2a0b9716df6f", "title": "NN Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "NNDiagram", "size": { "width": 1520, "height": 800 }, - "interactive": { - "elements": {}, - "relationships": {} - }, - "elements": { - "82874e6b-8bec-4e85-9e37-0c0c44910f7f": { + "nodes": [ + { "id": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "name": "features", "type": "NNContainer", - "owner": null, - "bounds": { + "position": { "x": -740, - "y": -380, + "y": -380 + }, + "width": 1370, + "height": 230, + "measured": { "width": 1370, "height": 230 + }, + "data": { + "name": "features" } }, - "b5dc30d6-d933-4f16-b079-b8486e224360": { + { "id": "b5dc30d6-d933-4f16-b079-b8486e224360", - "name": "Conv2DLayer", "type": "Conv2DLayer", - "owner": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "bounds": { + "position": { "x": -720, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "20962f77-9ee1-4508-b61d-9be747b4f87d", - "bc68711b-32a6-43d9-b78d-ab9b0f8432f2", - "35c7ed4f-858f-49f6-9fcf-6795c6785f4c", - "b8f6b6a6-7844-4234-8e14-f66b72b18766", - "d59a7450-a682-46c2-a3b5-3b0fb260854b", - "9068778f-b9d6-43ef-b512-c74fbc41a5c7", - "dbd875a8-9ae6-464b-a3a2-fd8d55fb89d3" - ], - "methods": [] - }, - "20962f77-9ee1-4508-b61d-9be747b4f87d": { - "id": "20962f77-9ee1-4508-b61d-9be747b4f87d", - "name": "name = f1", - "type": "NameAttributeConv2D", - "owner": "b5dc30d6-d933-4f16-b079-b8486e224360", - "bounds": { - "x": -720, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f1", - "isMandatory": true - }, - "bc68711b-32a6-43d9-b78d-ab9b0f8432f2": { - "id": "bc68711b-32a6-43d9-b78d-ab9b0f8432f2", - "name": "kernel_dim = [11, 11]", - "type": "KernelDimAttributeConv2D", - "owner": "b5dc30d6-d933-4f16-b079-b8486e224360", - "bounds": { - "x": -720, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[11, 11]", - "isMandatory": true - }, - "35c7ed4f-858f-49f6-9fcf-6795c6785f4c": { - "id": "35c7ed4f-858f-49f6-9fcf-6795c6785f4c", - "name": "out_channels = 64", - "type": "OutChannelsAttributeConv2D", - "owner": "b5dc30d6-d933-4f16-b079-b8486e224360", - "bounds": { - "x": -720, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "64", - "isMandatory": true - }, - "b8f6b6a6-7844-4234-8e14-f66b72b18766": { - "id": "b8f6b6a6-7844-4234-8e14-f66b72b18766", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "b5dc30d6-d933-4f16-b079-b8486e224360", - "bounds": { - "x": -720, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "d59a7450-a682-46c2-a3b5-3b0fb260854b": { - "id": "d59a7450-a682-46c2-a3b5-3b0fb260854b", - "name": "in_channels = 3", - "type": "InChannelsAttributeConv2D", - "owner": "b5dc30d6-d933-4f16-b079-b8486e224360", - "bounds": { - "x": -720, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "3", - "isMandatory": false - }, - "9068778f-b9d6-43ef-b512-c74fbc41a5c7": { - "id": "9068778f-b9d6-43ef-b512-c74fbc41a5c7", - "name": "stride_dim = [4, 4]", - "type": "StrideDimAttributeConv2D", - "owner": "b5dc30d6-d933-4f16-b079-b8486e224360", - "bounds": { - "x": -720, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "stride_dim", - "value": "[4, 4]", - "isMandatory": false - }, - "dbd875a8-9ae6-464b-a3a2-fd8d55fb89d3": { - "id": "dbd875a8-9ae6-464b-a3a2-fd8d55fb89d3", - "name": "padding_amount = 2", - "type": "PaddingAmountAttributeConv2D", - "owner": "b5dc30d6-d933-4f16-b079-b8486e224360", - "bounds": { - "x": -720, - "y": -310, - "width": 220, - "height": 20 + "data": { + "name": "Conv2DLayer", + "attributes": { + "name": "f1", + "kernel_dim": "[11, 11]", + "out_channels": "64", + "actv_func": "relu", + "in_channels": "3", + "stride_dim": "[4, 4]", + "padding_amount": "2" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "padding_amount", - "value": "2", - "isMandatory": false + "parentId": "82874e6b-8bec-4e85-9e37-0c0c44910f7f" }, - "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c": { + { "id": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", - "name": "PoolingLayer", "type": "PoolingLayer", - "owner": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "bounds": { + "position": { "x": -580, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "427a1fb9-3d44-4904-a496-a2fa3e3a4d46", - "668751a3-417e-47a0-afbd-6dc6b66eb420", - "78ade167-470f-4a8a-bcaa-4603bb8ae358", - "cd2ec638-4bd2-421f-b2d7-923347a84f5a", - "0a517974-0fee-4ab3-a313-520432132b06" - ], - "methods": [] - }, - "427a1fb9-3d44-4904-a496-a2fa3e3a4d46": { - "id": "427a1fb9-3d44-4904-a496-a2fa3e3a4d46", - "name": "name = f2", - "type": "NameAttributePooling", - "owner": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", - "bounds": { - "x": -580, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f2", - "isMandatory": true - }, - "668751a3-417e-47a0-afbd-6dc6b66eb420": { - "id": "668751a3-417e-47a0-afbd-6dc6b66eb420", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", - "bounds": { - "x": -580, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "78ade167-470f-4a8a-bcaa-4603bb8ae358": { - "id": "78ade167-470f-4a8a-bcaa-4603bb8ae358", - "name": "dimension = 2D", - "type": "DimensionAttributePooling", - "owner": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", - "bounds": { - "x": -580, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "dimension", - "value": "2D", - "isMandatory": true - }, - "cd2ec638-4bd2-421f-b2d7-923347a84f5a": { - "id": "cd2ec638-4bd2-421f-b2d7-923347a84f5a", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributePooling", - "owner": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", - "bounds": { - "x": -580, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": false - }, - "0a517974-0fee-4ab3-a313-520432132b06": { - "id": "0a517974-0fee-4ab3-a313-520432132b06", - "name": "stride_dim = [2, 2]", - "type": "StrideDimAttributePooling", - "owner": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", - "bounds": { - "x": -580, - "y": -310, - "width": 200, - "height": 20 + "data": { + "name": "PoolingLayer", + "attributes": { + "name": "f2", + "pooling_type": "max", + "kernel_dim": "[3, 3]", + "stride_dim": "[2, 2]", + "pooling.dimension": "2D" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "stride_dim", - "value": "[2, 2]", - "isMandatory": false + "parentId": "82874e6b-8bec-4e85-9e37-0c0c44910f7f" }, - "68872556-8ebc-45fa-9974-6b1d9fa5fa7b": { + { "id": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "name": "Conv2DLayer", "type": "Conv2DLayer", - "owner": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "bounds": { + "position": { "x": -430, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "fd8166f0-5b78-431b-96ce-24aa94a0eb33", - "35a3a708-e862-4483-8c5f-927c7e00de23", - "9731748b-2a57-45a4-aa11-f650110d4837", - "8b0422ac-f975-4d22-9ecd-831e86c36d07", - "bb42899f-dc06-4665-b6fe-7b29cdd1f710", - "e6eeb93a-7e85-4f66-b4fb-8f1f201e8a71" - ], - "methods": [] - }, - "fd8166f0-5b78-431b-96ce-24aa94a0eb33": { - "id": "fd8166f0-5b78-431b-96ce-24aa94a0eb33", - "name": "name = f3", - "type": "NameAttributeConv2D", - "owner": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "bounds": { - "x": -430, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f3", - "isMandatory": true - }, - "35a3a708-e862-4483-8c5f-927c7e00de23": { - "id": "35a3a708-e862-4483-8c5f-927c7e00de23", - "name": "kernel_dim = [5, 5]", - "type": "KernelDimAttributeConv2D", - "owner": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "bounds": { - "x": -430, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[5, 5]", - "isMandatory": true - }, - "9731748b-2a57-45a4-aa11-f650110d4837": { - "id": "9731748b-2a57-45a4-aa11-f650110d4837", - "name": "out_channels = 192", - "type": "OutChannelsAttributeConv2D", - "owner": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "bounds": { - "x": -430, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "192", - "isMandatory": true - }, - "8b0422ac-f975-4d22-9ecd-831e86c36d07": { - "id": "8b0422ac-f975-4d22-9ecd-831e86c36d07", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "bounds": { - "x": -430, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "bb42899f-dc06-4665-b6fe-7b29cdd1f710": { - "id": "bb42899f-dc06-4665-b6fe-7b29cdd1f710", - "name": "in_channels = 64", - "type": "InChannelsAttributeConv2D", - "owner": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "bounds": { - "x": -430, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "64", - "isMandatory": false - }, - "e6eeb93a-7e85-4f66-b4fb-8f1f201e8a71": { - "id": "e6eeb93a-7e85-4f66-b4fb-8f1f201e8a71", - "name": "padding_amount = 2", - "type": "PaddingAmountAttributeConv2D", - "owner": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "bounds": { - "x": -430, - "y": -310, - "width": 220, - "height": 20 + "data": { + "name": "Conv2DLayer", + "attributes": { + "name": "f3", + "kernel_dim": "[5, 5]", + "out_channels": "192", + "actv_func": "relu", + "in_channels": "64", + "padding_amount": "2" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "padding_amount", - "value": "2", - "isMandatory": false + "parentId": "82874e6b-8bec-4e85-9e37-0c0c44910f7f" }, - "aba29a03-7ea5-4657-bb55-c707885f1d0d": { + { "id": "aba29a03-7ea5-4657-bb55-c707885f1d0d", - "name": "PoolingLayer", "type": "PoolingLayer", - "owner": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "bounds": { + "position": { "x": -290, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "9e6b291a-709d-474f-b960-1a7106da4c20", - "7bc0d981-9598-40c7-996c-7bbbeca4085e", - "563df1cc-dc10-4823-a435-57e457f0b463", - "bd59629d-7857-45b3-b7b7-ac5e068525a0", - "0b305eac-975e-4bce-bfd9-021f7e275da7" - ], - "methods": [] - }, - "9e6b291a-709d-474f-b960-1a7106da4c20": { - "id": "9e6b291a-709d-474f-b960-1a7106da4c20", - "name": "name = f4", - "type": "NameAttributePooling", - "owner": "aba29a03-7ea5-4657-bb55-c707885f1d0d", - "bounds": { - "x": -290, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f4", - "isMandatory": true - }, - "7bc0d981-9598-40c7-996c-7bbbeca4085e": { - "id": "7bc0d981-9598-40c7-996c-7bbbeca4085e", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "aba29a03-7ea5-4657-bb55-c707885f1d0d", - "bounds": { - "x": -290, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "563df1cc-dc10-4823-a435-57e457f0b463": { - "id": "563df1cc-dc10-4823-a435-57e457f0b463", - "name": "dimension = 2D", - "type": "DimensionAttributePooling", - "owner": "aba29a03-7ea5-4657-bb55-c707885f1d0d", - "bounds": { - "x": -290, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "dimension", - "value": "2D", - "isMandatory": true - }, - "bd59629d-7857-45b3-b7b7-ac5e068525a0": { - "id": "bd59629d-7857-45b3-b7b7-ac5e068525a0", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributePooling", - "owner": "aba29a03-7ea5-4657-bb55-c707885f1d0d", - "bounds": { - "x": -290, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": false - }, - "0b305eac-975e-4bce-bfd9-021f7e275da7": { - "id": "0b305eac-975e-4bce-bfd9-021f7e275da7", - "name": "stride_dim = [2, 2]", - "type": "StrideDimAttributePooling", - "owner": "aba29a03-7ea5-4657-bb55-c707885f1d0d", - "bounds": { - "x": -290, - "y": -310, - "width": 200, - "height": 20 + "data": { + "name": "PoolingLayer", + "attributes": { + "name": "f4", + "pooling_type": "max", + "kernel_dim": "[3, 3]", + "stride_dim": "[2, 2]", + "pooling.dimension": "2D" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "stride_dim", - "value": "[2, 2]", - "isMandatory": false + "parentId": "82874e6b-8bec-4e85-9e37-0c0c44910f7f" }, - "429c3da2-212e-48da-9eb3-6c824f9b5362": { + { "id": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "name": "Conv2DLayer", "type": "Conv2DLayer", - "owner": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "bounds": { + "position": { "x": -150, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "57b9281d-cbcf-4291-bcca-b32015aa3e20", - "4478a6f7-0658-4cd9-b078-8d53e7d43219", - "6d6de93e-607f-4101-9ef7-702e3fb6cdb9", - "288b42bd-029e-4b2e-a94d-590acb360dc8", - "ee275213-7174-4428-8650-240820ba0bfc", - "98e6bf8d-7410-4c70-9463-01c723692577" - ], - "methods": [] - }, - "57b9281d-cbcf-4291-bcca-b32015aa3e20": { - "id": "57b9281d-cbcf-4291-bcca-b32015aa3e20", - "name": "name = f5", - "type": "NameAttributeConv2D", - "owner": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "bounds": { - "x": -150, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f5", - "isMandatory": true - }, - "4478a6f7-0658-4cd9-b078-8d53e7d43219": { - "id": "4478a6f7-0658-4cd9-b078-8d53e7d43219", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "bounds": { - "x": -150, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "6d6de93e-607f-4101-9ef7-702e3fb6cdb9": { - "id": "6d6de93e-607f-4101-9ef7-702e3fb6cdb9", - "name": "out_channels = 384", - "type": "OutChannelsAttributeConv2D", - "owner": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "bounds": { - "x": -150, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "384", - "isMandatory": true - }, - "288b42bd-029e-4b2e-a94d-590acb360dc8": { - "id": "288b42bd-029e-4b2e-a94d-590acb360dc8", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "bounds": { - "x": -150, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "ee275213-7174-4428-8650-240820ba0bfc": { - "id": "ee275213-7174-4428-8650-240820ba0bfc", - "name": "in_channels = 192", - "type": "InChannelsAttributeConv2D", - "owner": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "bounds": { - "x": -150, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "192", - "isMandatory": false - }, - "98e6bf8d-7410-4c70-9463-01c723692577": { - "id": "98e6bf8d-7410-4c70-9463-01c723692577", - "name": "padding_amount = 1", - "type": "PaddingAmountAttributeConv2D", - "owner": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "bounds": { - "x": -150, - "y": -310, - "width": 220, - "height": 20 + "data": { + "name": "Conv2DLayer", + "attributes": { + "name": "f5", + "kernel_dim": "[3, 3]", + "out_channels": "384", + "actv_func": "relu", + "in_channels": "192", + "padding_amount": "1" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "padding_amount", - "value": "1", - "isMandatory": false + "parentId": "82874e6b-8bec-4e85-9e37-0c0c44910f7f" }, - "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96": { + { "id": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "name": "Conv2DLayer", "type": "Conv2DLayer", - "owner": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "bounds": { + "position": { "x": 0, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "5446cba8-b745-4209-bf66-17d660a240ca", - "b03f0378-e59b-4934-91ec-f62a1511120e", - "3ccc5a05-f98b-4629-9aae-057b9ef28263", - "3125960a-8c3f-4715-b1de-ae55984a8c18", - "da5f9eb8-7d50-484a-a836-2f9a86131462", - "53d1f49d-531e-4ef2-b707-8b822b4a27f2" - ], - "methods": [] - }, - "5446cba8-b745-4209-bf66-17d660a240ca": { - "id": "5446cba8-b745-4209-bf66-17d660a240ca", - "name": "name = f6", - "type": "NameAttributeConv2D", - "owner": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "bounds": { - "x": 0, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f6", - "isMandatory": true - }, - "b03f0378-e59b-4934-91ec-f62a1511120e": { - "id": "b03f0378-e59b-4934-91ec-f62a1511120e", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "bounds": { - "x": 0, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "3ccc5a05-f98b-4629-9aae-057b9ef28263": { - "id": "3ccc5a05-f98b-4629-9aae-057b9ef28263", - "name": "out_channels = 256", - "type": "OutChannelsAttributeConv2D", - "owner": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "bounds": { - "x": 0, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "256", - "isMandatory": true - }, - "3125960a-8c3f-4715-b1de-ae55984a8c18": { - "id": "3125960a-8c3f-4715-b1de-ae55984a8c18", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "bounds": { - "x": 0, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "da5f9eb8-7d50-484a-a836-2f9a86131462": { - "id": "da5f9eb8-7d50-484a-a836-2f9a86131462", - "name": "in_channels = 384", - "type": "InChannelsAttributeConv2D", - "owner": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "bounds": { - "x": 0, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "384", - "isMandatory": false - }, - "53d1f49d-531e-4ef2-b707-8b822b4a27f2": { - "id": "53d1f49d-531e-4ef2-b707-8b822b4a27f2", - "name": "padding_amount = 1", - "type": "PaddingAmountAttributeConv2D", - "owner": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "bounds": { - "x": 0, - "y": -310, - "width": 220, - "height": 20 + "data": { + "name": "Conv2DLayer", + "attributes": { + "name": "f6", + "kernel_dim": "[3, 3]", + "out_channels": "256", + "actv_func": "relu", + "in_channels": "384", + "padding_amount": "1" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "padding_amount", - "value": "1", - "isMandatory": false + "parentId": "82874e6b-8bec-4e85-9e37-0c0c44910f7f" }, - "f6b3b33b-4cb0-423b-8e12-a17f92cb008b": { + { "id": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "name": "Conv2DLayer", "type": "Conv2DLayer", - "owner": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "bounds": { + "position": { "x": 170, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "ce2b3039-9736-44b9-8e11-5989db34d1e9", - "24c17d19-76d8-4ba4-8893-714cf9ded204", - "74098b21-09ca-4b81-86fe-48f651c58ca1", - "9214607c-b9b9-4e8c-a121-b93f32797f78", - "3cec0e69-226d-48d5-982d-52bac9af2d54", - "0c69d7f5-d794-48ff-b416-97ca3be90b27" - ], - "methods": [] - }, - "ce2b3039-9736-44b9-8e11-5989db34d1e9": { - "id": "ce2b3039-9736-44b9-8e11-5989db34d1e9", - "name": "name = f7", - "type": "NameAttributeConv2D", - "owner": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "bounds": { - "x": 170, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f7", - "isMandatory": true - }, - "24c17d19-76d8-4ba4-8893-714cf9ded204": { - "id": "24c17d19-76d8-4ba4-8893-714cf9ded204", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "bounds": { - "x": 170, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "74098b21-09ca-4b81-86fe-48f651c58ca1": { - "id": "74098b21-09ca-4b81-86fe-48f651c58ca1", - "name": "out_channels = 256", - "type": "OutChannelsAttributeConv2D", - "owner": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "bounds": { - "x": 170, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "256", - "isMandatory": true - }, - "9214607c-b9b9-4e8c-a121-b93f32797f78": { - "id": "9214607c-b9b9-4e8c-a121-b93f32797f78", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "bounds": { - "x": 170, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "3cec0e69-226d-48d5-982d-52bac9af2d54": { - "id": "3cec0e69-226d-48d5-982d-52bac9af2d54", - "name": "in_channels = 256", - "type": "InChannelsAttributeConv2D", - "owner": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "bounds": { - "x": 170, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "256", - "isMandatory": false - }, - "0c69d7f5-d794-48ff-b416-97ca3be90b27": { - "id": "0c69d7f5-d794-48ff-b416-97ca3be90b27", - "name": "padding_amount = 1", - "type": "PaddingAmountAttributeConv2D", - "owner": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "bounds": { - "x": 170, - "y": -310, - "width": 220, - "height": 20 + "data": { + "name": "Conv2DLayer", + "attributes": { + "name": "f7", + "kernel_dim": "[3, 3]", + "out_channels": "256", + "actv_func": "relu", + "in_channels": "256", + "padding_amount": "1" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "padding_amount", - "value": "1", - "isMandatory": false + "parentId": "82874e6b-8bec-4e85-9e37-0c0c44910f7f" }, - "3903acba-4f59-4f5e-b39e-cb6fd8133d01": { + { "id": "3903acba-4f59-4f5e-b39e-cb6fd8133d01", - "name": "PoolingLayer", "type": "PoolingLayer", - "owner": "82874e6b-8bec-4e85-9e37-0c0c44910f7f", - "bounds": { + "position": { "x": 320, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "811677e4-c5a5-43b0-a74f-56ff959e55b6", - "85e6be8d-cf7c-47c4-ad55-834077fde08f", - "1717835d-4e97-49c4-803a-5faf66960c22", - "deefd977-10b6-4332-8370-0b312f4f53ce", - "b0068001-d277-4bab-9351-4f6eaae1a54b" - ], - "methods": [] - }, - "811677e4-c5a5-43b0-a74f-56ff959e55b6": { - "id": "811677e4-c5a5-43b0-a74f-56ff959e55b6", - "name": "name = f8", - "type": "NameAttributePooling", - "owner": "3903acba-4f59-4f5e-b39e-cb6fd8133d01", - "bounds": { - "x": 320, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f8", - "isMandatory": true - }, - "85e6be8d-cf7c-47c4-ad55-834077fde08f": { - "id": "85e6be8d-cf7c-47c4-ad55-834077fde08f", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "3903acba-4f59-4f5e-b39e-cb6fd8133d01", - "bounds": { - "x": 320, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "1717835d-4e97-49c4-803a-5faf66960c22": { - "id": "1717835d-4e97-49c4-803a-5faf66960c22", - "name": "dimension = 2D", - "type": "DimensionAttributePooling", - "owner": "3903acba-4f59-4f5e-b39e-cb6fd8133d01", - "bounds": { - "x": 320, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "dimension", - "value": "2D", - "isMandatory": true - }, - "deefd977-10b6-4332-8370-0b312f4f53ce": { - "id": "deefd977-10b6-4332-8370-0b312f4f53ce", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributePooling", - "owner": "3903acba-4f59-4f5e-b39e-cb6fd8133d01", - "bounds": { - "x": 320, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": false - }, - "b0068001-d277-4bab-9351-4f6eaae1a54b": { - "id": "b0068001-d277-4bab-9351-4f6eaae1a54b", - "name": "stride_dim = [2, 2]", - "type": "StrideDimAttributePooling", - "owner": "3903acba-4f59-4f5e-b39e-cb6fd8133d01", - "bounds": { - "x": 320, - "y": -310, - "width": 200, - "height": 20 + "data": { + "name": "PoolingLayer", + "attributes": { + "name": "f8", + "pooling_type": "max", + "kernel_dim": "[3, 3]", + "stride_dim": "[2, 2]", + "pooling.dimension": "2D" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "stride_dim", - "value": "[2, 2]", - "isMandatory": false + "parentId": "82874e6b-8bec-4e85-9e37-0c0c44910f7f" }, - "3c885977-837c-4469-8112-4e26f02e7937": { + { "id": "3c885977-837c-4469-8112-4e26f02e7937", - "name": "classifier", "type": "NNContainer", - "owner": null, - "bounds": { + "position": { "x": -590, - "y": -120, + "y": -120 + }, + "width": 840, + "height": 190, + "measured": { "width": 840, "height": 190 + }, + "data": { + "name": "classifier" } }, - "24e6c691-b91a-400d-8cb9-b1105ff3d4c4": { + { "id": "24e6c691-b91a-400d-8cb9-b1105ff3d4c4", - "name": "DropoutLayer", "type": "DropoutLayer", - "owner": "3c885977-837c-4469-8112-4e26f02e7937", - "bounds": { + "position": { "x": -560, - "y": -60, + "y": -60 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "3f58c3e1-9cfd-42fd-90be-9e17e34f09fb", - "5704fe9f-38f9-48aa-abad-673f055b8903" - ], - "methods": [] - }, - "3f58c3e1-9cfd-42fd-90be-9e17e34f09fb": { - "id": "3f58c3e1-9cfd-42fd-90be-9e17e34f09fb", - "name": "name = c1", - "type": "NameAttributeDropout", - "owner": "24e6c691-b91a-400d-8cb9-b1105ff3d4c4", - "bounds": { - "x": -560, - "y": -60, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "c1", - "isMandatory": true - }, - "5704fe9f-38f9-48aa-abad-673f055b8903": { - "id": "5704fe9f-38f9-48aa-abad-673f055b8903", - "name": "rate = 0.5", - "type": "RateAttributeDropout", - "owner": "24e6c691-b91a-400d-8cb9-b1105ff3d4c4", - "bounds": { - "x": -560, - "y": -60, - "width": 160, - "height": 20 + "data": { + "name": "DropoutLayer", + "attributes": { + "name": "c1", + "rate": "0.5" + } }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "rate", - "value": "0.5", - "isMandatory": true + "parentId": "3c885977-837c-4469-8112-4e26f02e7937" }, - "8f9da758-b58b-4fff-84ef-9a0d63234de6": { + { "id": "8f9da758-b58b-4fff-84ef-9a0d63234de6", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "3c885977-837c-4469-8112-4e26f02e7937", - "bounds": { + "position": { "x": -390, - "y": -60, + "y": -60 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "ec123583-b5d4-4368-9bc3-285245b83058", - "ebc0cec1-081e-4948-ac3d-87524abc6bfe", - "315748ed-1d84-4869-b776-a75c3944f3e0", - "9b56d799-3e42-4361-b97d-3e7ef723409e" - ], - "methods": [] - }, - "ec123583-b5d4-4368-9bc3-285245b83058": { - "id": "ec123583-b5d4-4368-9bc3-285245b83058", - "name": "name = c2", - "type": "NameAttributeLinear", - "owner": "8f9da758-b58b-4fff-84ef-9a0d63234de6", - "bounds": { - "x": -390, - "y": -60, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "c2", - "isMandatory": true - }, - "ebc0cec1-081e-4948-ac3d-87524abc6bfe": { - "id": "ebc0cec1-081e-4948-ac3d-87524abc6bfe", - "name": "out_features = 4096", - "type": "OutFeaturesAttributeLinear", - "owner": "8f9da758-b58b-4fff-84ef-9a0d63234de6", - "bounds": { - "x": -390, - "y": -60, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_features", - "value": "4096", - "isMandatory": true - }, - "315748ed-1d84-4869-b776-a75c3944f3e0": { - "id": "315748ed-1d84-4869-b776-a75c3944f3e0", - "name": "in_features = 9216", - "type": "InFeaturesAttributeLinear", - "owner": "8f9da758-b58b-4fff-84ef-9a0d63234de6", - "bounds": { - "x": -390, - "y": -60, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_features", - "value": "9216", - "isMandatory": false - }, - "9b56d799-3e42-4361-b97d-3e7ef723409e": { - "id": "9b56d799-3e42-4361-b97d-3e7ef723409e", - "name": "actv_func = relu", - "type": "ActvFuncAttributeLinear", - "owner": "8f9da758-b58b-4fff-84ef-9a0d63234de6", - "bounds": { - "x": -390, - "y": -60, - "width": 170, - "height": 20 + "data": { + "name": "LinearLayer", + "attributes": { + "name": "c2", + "out_features": "4096", + "in_features": "9216", + "actv_func": "relu" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false + "parentId": "3c885977-837c-4469-8112-4e26f02e7937" }, - "355f6cde-8462-43b6-a5a8-a2367b47a81f": { + { "id": "355f6cde-8462-43b6-a5a8-a2367b47a81f", - "name": "DropoutLayer", "type": "DropoutLayer", - "owner": "3c885977-837c-4469-8112-4e26f02e7937", - "bounds": { + "position": { "x": -210, - "y": -60, + "y": -60 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "ee94f415-29ed-413d-8d5d-2320d28af994", - "85ae12d4-513d-4246-949a-6158ff5af45f" - ], - "methods": [] - }, - "ee94f415-29ed-413d-8d5d-2320d28af994": { - "id": "ee94f415-29ed-413d-8d5d-2320d28af994", - "name": "name = c3", - "type": "NameAttributeDropout", - "owner": "355f6cde-8462-43b6-a5a8-a2367b47a81f", - "bounds": { - "x": -210, - "y": -60, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "c3", - "isMandatory": true - }, - "85ae12d4-513d-4246-949a-6158ff5af45f": { - "id": "85ae12d4-513d-4246-949a-6158ff5af45f", - "name": "rate = 0.5", - "type": "RateAttributeDropout", - "owner": "355f6cde-8462-43b6-a5a8-a2367b47a81f", - "bounds": { - "x": -210, - "y": -60, - "width": 160, - "height": 20 + "data": { + "name": "DropoutLayer", + "attributes": { + "name": "c3", + "rate": "0.5" + } }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "rate", - "value": "0.5", - "isMandatory": true + "parentId": "3c885977-837c-4469-8112-4e26f02e7937" }, - "b26b456a-dd21-46d8-ae5e-953c4c980a85": { + { "id": "b26b456a-dd21-46d8-ae5e-953c4c980a85", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "3c885977-837c-4469-8112-4e26f02e7937", - "bounds": { + "position": { "x": -40, - "y": -60, + "y": -60 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "a6d1fd42-2b57-475e-bdf9-68d5aec7e747", - "a3f5d0e0-e6da-4e08-b595-703e32784f33", - "ae0a33e0-8df2-4f5c-8417-167ab3c4ab19", - "efbf5579-715f-4231-98b3-d1ee460cfbec" - ], - "methods": [] - }, - "a6d1fd42-2b57-475e-bdf9-68d5aec7e747": { - "id": "a6d1fd42-2b57-475e-bdf9-68d5aec7e747", - "name": "name = c4", - "type": "NameAttributeLinear", - "owner": "b26b456a-dd21-46d8-ae5e-953c4c980a85", - "bounds": { - "x": -40, - "y": -60, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "c4", - "isMandatory": true - }, - "a3f5d0e0-e6da-4e08-b595-703e32784f33": { - "id": "a3f5d0e0-e6da-4e08-b595-703e32784f33", - "name": "out_features = 4096", - "type": "OutFeaturesAttributeLinear", - "owner": "b26b456a-dd21-46d8-ae5e-953c4c980a85", - "bounds": { - "x": -40, - "y": -60, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_features", - "value": "4096", - "isMandatory": true - }, - "ae0a33e0-8df2-4f5c-8417-167ab3c4ab19": { - "id": "ae0a33e0-8df2-4f5c-8417-167ab3c4ab19", - "name": "in_features = 4096", - "type": "InFeaturesAttributeLinear", - "owner": "b26b456a-dd21-46d8-ae5e-953c4c980a85", - "bounds": { - "x": -40, - "y": -60, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_features", - "value": "4096", - "isMandatory": false - }, - "efbf5579-715f-4231-98b3-d1ee460cfbec": { - "id": "efbf5579-715f-4231-98b3-d1ee460cfbec", - "name": "actv_func = relu", - "type": "ActvFuncAttributeLinear", - "owner": "b26b456a-dd21-46d8-ae5e-953c4c980a85", - "bounds": { - "x": -40, - "y": -60, - "width": 170, - "height": 20 + "data": { + "name": "LinearLayer", + "attributes": { + "name": "c4", + "out_features": "4096", + "in_features": "4096", + "actv_func": "relu" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false + "parentId": "3c885977-837c-4469-8112-4e26f02e7937" }, - "d84e4a67-bf8a-4843-af31-783a08e96f49": { + { "id": "d84e4a67-bf8a-4843-af31-783a08e96f49", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "3c885977-837c-4469-8112-4e26f02e7937", - "bounds": { + "position": { "x": 120, - "y": -60, + "y": -60 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "5c276f38-d6b8-4d94-a563-ddb0e5248f6c", - "c72a1b58-c417-48b6-9e9f-8f2063d959c6", - "1707beb8-22c6-4486-9c9a-a83651f36970" - ], - "methods": [] - }, - "5c276f38-d6b8-4d94-a563-ddb0e5248f6c": { - "id": "5c276f38-d6b8-4d94-a563-ddb0e5248f6c", - "name": "name = c5", - "type": "NameAttributeLinear", - "owner": "d84e4a67-bf8a-4843-af31-783a08e96f49", - "bounds": { - "x": 120, - "y": -60, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "c5", - "isMandatory": true - }, - "c72a1b58-c417-48b6-9e9f-8f2063d959c6": { - "id": "c72a1b58-c417-48b6-9e9f-8f2063d959c6", - "name": "out_features = 1000", - "type": "OutFeaturesAttributeLinear", - "owner": "d84e4a67-bf8a-4843-af31-783a08e96f49", - "bounds": { - "x": 120, - "y": -60, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_features", - "value": "1000", - "isMandatory": true - }, - "1707beb8-22c6-4486-9c9a-a83651f36970": { - "id": "1707beb8-22c6-4486-9c9a-a83651f36970", - "name": "in_features = 4096", - "type": "InFeaturesAttributeLinear", - "owner": "d84e4a67-bf8a-4843-af31-783a08e96f49", - "bounds": { - "x": 120, - "y": -60, - "width": 190, - "height": 20 + "data": { + "name": "LinearLayer", + "attributes": { + "name": "c5", + "out_features": "1000", + "in_features": "4096" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_features", - "value": "4096", - "isMandatory": false + "parentId": "3c885977-837c-4469-8112-4e26f02e7937" }, - "f27bd4bd-6984-4826-aa9a-00993403695f": { + { "id": "f27bd4bd-6984-4826-aa9a-00993403695f", - "name": "alexnet", "type": "NNContainer", - "owner": null, - "bounds": { + "position": { "x": -600, - "y": 140, + "y": 140 + }, + "width": 810, + "height": 180, + "measured": { "width": 810, "height": 180 + }, + "data": { + "name": "alexnet" } }, - "a015eb20-e375-4c95-a6e2-6cf2d5cf109c": { + { "id": "a015eb20-e375-4c95-a6e2-6cf2d5cf109c", - "name": "features", "type": "NNReference", - "owner": "f27bd4bd-6984-4826-aa9a-00993403695f", - "bounds": { + "position": { "x": -580, - "y": 230, + "y": 230 + }, + "width": 140, + "height": 40, + "measured": { "width": 140, "height": 40 }, - "referencedNN": "features" + "data": { + "name": "features", + "referenceTarget": "features" + }, + "parentId": "f27bd4bd-6984-4826-aa9a-00993403695f" }, - "1174b414-b33b-4f5f-a66e-1fdf674d587f": { + { "id": "1174b414-b33b-4f5f-a66e-1fdf674d587f", - "name": "PoolingLayer", "type": "PoolingLayer", - "owner": "f27bd4bd-6984-4826-aa9a-00993403695f", - "bounds": { + "position": { "x": -380, - "y": 200, + "y": 200 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "0d8f3c3b-5f10-4a49-b417-cedd5bd44f1f", - "614efd84-0777-45b7-98bc-f96213114cb2", - "61b6cbc3-ae6a-4eca-9522-58d881cb71ed", - "b39528de-0edc-4870-bf00-fd823d088cec" - ], - "methods": [] - }, - "0d8f3c3b-5f10-4a49-b417-cedd5bd44f1f": { - "id": "0d8f3c3b-5f10-4a49-b417-cedd5bd44f1f", - "name": "name = p1", - "type": "NameAttributePooling", - "owner": "1174b414-b33b-4f5f-a66e-1fdf674d587f", - "bounds": { - "x": -380, - "y": 200, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "p1", - "isMandatory": true - }, - "614efd84-0777-45b7-98bc-f96213114cb2": { - "id": "614efd84-0777-45b7-98bc-f96213114cb2", - "name": "pooling_type = adaptive_average", - "type": "PoolingTypeAttributePooling", - "owner": "1174b414-b33b-4f5f-a66e-1fdf674d587f", - "bounds": { - "x": -380, - "y": 200, - "width": 300, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "pooling_type", - "value": "adaptive_average", - "isMandatory": true - }, - "61b6cbc3-ae6a-4eca-9522-58d881cb71ed": { - "id": "61b6cbc3-ae6a-4eca-9522-58d881cb71ed", - "name": "dimension = 2D", - "type": "DimensionAttributePooling", - "owner": "1174b414-b33b-4f5f-a66e-1fdf674d587f", - "bounds": { - "x": -380, - "y": 200, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "dimension", - "value": "2D", - "isMandatory": true - }, - "b39528de-0edc-4870-bf00-fd823d088cec": { - "id": "b39528de-0edc-4870-bf00-fd823d088cec", - "name": "output_dim = [6, 6]", - "type": "OutputDimAttributePooling", - "owner": "1174b414-b33b-4f5f-a66e-1fdf674d587f", - "bounds": { - "x": -380, - "y": 200, - "width": 220, - "height": 20 + "data": { + "name": "PoolingLayer", + "attributes": { + "name": "p1", + "pooling_type": "adaptive_average", + "output_dim": "[6, 6]", + "pooling.dimension": "2D" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "output_dim", - "value": "[6, 6]", - "isMandatory": false + "parentId": "f27bd4bd-6984-4826-aa9a-00993403695f" }, - "e3dbae01-2673-4567-917e-b4b452e76fd9": { + { "id": "e3dbae01-2673-4567-917e-b4b452e76fd9", - "name": "FlattenLayer", "type": "FlattenLayer", - "owner": "f27bd4bd-6984-4826-aa9a-00993403695f", - "bounds": { + "position": { "x": -210, - "y": 200, + "y": 200 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "1e42c26d-f6bf-4515-83a9-072d56d2fb48", - "fa4495f5-17c2-47f4-9aec-36aae3ea49ee" - ], - "methods": [] - }, - "1e42c26d-f6bf-4515-83a9-072d56d2fb48": { - "id": "1e42c26d-f6bf-4515-83a9-072d56d2fb48", - "name": "name = f1", - "type": "NameAttributeFlatten", - "owner": "e3dbae01-2673-4567-917e-b4b452e76fd9", - "bounds": { - "x": -210, - "y": 200, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "f1", - "isMandatory": true - }, - "fa4495f5-17c2-47f4-9aec-36aae3ea49ee": { - "id": "fa4495f5-17c2-47f4-9aec-36aae3ea49ee", - "name": "start_dim = 1", - "type": "StartDimAttributeFlatten", - "owner": "e3dbae01-2673-4567-917e-b4b452e76fd9", - "bounds": { - "x": -210, - "y": 200, - "width": 160, - "height": 20 + "data": { + "name": "FlattenLayer", + "attributes": { + "name": "f1", + "start_dim": "1" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "start_dim", - "value": "1", - "isMandatory": false + "parentId": "f27bd4bd-6984-4826-aa9a-00993403695f" }, - "e7e7de00-2174-4379-90e1-98036e29ce1f": { + { "id": "e7e7de00-2174-4379-90e1-98036e29ce1f", - "name": "classifier", "type": "NNReference", - "owner": "f27bd4bd-6984-4826-aa9a-00993403695f", - "bounds": { + "position": { "x": -30, - "y": 230, + "y": 230 + }, + "width": 140, + "height": 40, + "measured": { "width": 140, "height": 40 }, - "referencedNN": "classifier" + "data": { + "name": "classifier", + "referenceTarget": "classifier" + }, + "parentId": "f27bd4bd-6984-4826-aa9a-00993403695f" } - }, - "relationships": { - "67919972-f826-4fd6-b390-80f8346d710a": { + ], + "edges": [ + { "id": "67919972-f826-4fd6-b390-80f8346d710a", - "name": "next", + "source": "24e6c691-b91a-400d-8cb9-b1105ff3d4c4", + "target": "8f9da758-b58b-4fff-84ef-9a0d63234de6", "type": "NNNext", - "owner": null, - "bounds": { - "x": -450, - "y": -15, - "width": 60, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 60, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "24e6c691-b91a-400d-8cb9-b1105ff3d4c4", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "8f9da758-b58b-4fff-84ef-9a0d63234de6", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "0b02fcde-6643-438a-8907-6f6c8ff20695": { + { "id": "0b02fcde-6643-438a-8907-6f6c8ff20695", - "name": "next", + "source": "8f9da758-b58b-4fff-84ef-9a0d63234de6", + "target": "355f6cde-8462-43b6-a5a8-a2367b47a81f", "type": "NNNext", - "owner": null, - "bounds": { - "x": -280, - "y": -15, - "width": 70, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 70, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "8f9da758-b58b-4fff-84ef-9a0d63234de6", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "355f6cde-8462-43b6-a5a8-a2367b47a81f", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "4b647132-426a-4cc5-9047-7390677ac550": { + { "id": "4b647132-426a-4cc5-9047-7390677ac550", - "name": "next", + "source": "355f6cde-8462-43b6-a5a8-a2367b47a81f", + "target": "b26b456a-dd21-46d8-ae5e-953c4c980a85", "type": "NNNext", - "owner": null, - "bounds": { - "x": -100, - "y": -15, - "width": 60, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 60, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "355f6cde-8462-43b6-a5a8-a2367b47a81f", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "b26b456a-dd21-46d8-ae5e-953c4c980a85", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "149cd99c-43ad-4334-be2b-bdc3ade50be3": { + { "id": "149cd99c-43ad-4334-be2b-bdc3ade50be3", - "name": "next", + "source": "b26b456a-dd21-46d8-ae5e-953c4c980a85", + "target": "d84e4a67-bf8a-4843-af31-783a08e96f49", "type": "NNNext", - "owner": null, - "bounds": { - "x": 70, - "y": -15, - "width": 50, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 50, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "b26b456a-dd21-46d8-ae5e-953c4c980a85", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "d84e4a67-bf8a-4843-af31-783a08e96f49", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "e3fb9ed8-615d-48cf-9c90-2e29c093d49b": { + { "id": "e3fb9ed8-615d-48cf-9c90-2e29c093d49b", - "name": "next", + "source": "a015eb20-e375-4c95-a6e2-6cf2d5cf109c", + "target": "1174b414-b33b-4f5f-a66e-1fdf674d587f", "type": "NNNext", - "owner": null, - "bounds": { - "x": -440, - "y": 240, - "width": 60, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 60, - "y": 10 - } - ], - "source": { - "direction": "Downright", - "element": "a015eb20-e375-4c95-a6e2-6cf2d5cf109c", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "1174b414-b33b-4f5f-a66e-1fdf674d587f", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Downright", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "493b5bbd-1413-417d-9204-f1b872a5faa9": { + { "id": "493b5bbd-1413-417d-9204-f1b872a5faa9", - "name": "next", + "source": "1174b414-b33b-4f5f-a66e-1fdf674d587f", + "target": "e3dbae01-2673-4567-917e-b4b452e76fd9", "type": "NNNext", - "owner": null, - "bounds": { - "x": -270, - "y": 245, - "width": 60, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 60, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "1174b414-b33b-4f5f-a66e-1fdf674d587f", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "e3dbae01-2673-4567-917e-b4b452e76fd9", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "d8a8c565-2ac8-4439-b39e-f9d41dff8ba4": { + { "id": "d8a8c565-2ac8-4439-b39e-f9d41dff8ba4", - "name": "next", + "source": "e3dbae01-2673-4567-917e-b4b452e76fd9", + "target": "e7e7de00-2174-4379-90e1-98036e29ce1f", "type": "NNNext", - "owner": null, - "bounds": { - "x": -100, - "y": 240, - "width": 70, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 70, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "e3dbae01-2673-4567-917e-b4b452e76fd9", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Downleft", - "element": "e7e7de00-2174-4379-90e1-98036e29ce1f", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Downleft", + "data": { + "name": "next", + "points": [] + } }, - "4aeb80be-1189-411f-8432-9e2b0139598f": { + { "id": "4aeb80be-1189-411f-8432-9e2b0139598f", - "name": "next", + "source": "b5dc30d6-d933-4f16-b079-b8486e224360", + "target": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", "type": "NNNext", - "owner": null, - "bounds": { - "x": -610, - "y": -265, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "b5dc30d6-d933-4f16-b079-b8486e224360", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "20a91456-6474-466c-af4d-a5b8c5a0eb78": { + { "id": "20a91456-6474-466c-af4d-a5b8c5a0eb78", - "name": "next", + "source": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", + "target": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", "type": "NNNext", - "owner": null, - "bounds": { - "x": -470, - "y": -265, - "width": 40, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 40, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "fe4ffcd2-cdfa-4f76-aef2-2150fe47f87c", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "62a12256-6a4b-47aa-874a-0c150b0a8d52": { + { "id": "62a12256-6a4b-47aa-874a-0c150b0a8d52", - "name": "next", + "source": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", + "target": "aba29a03-7ea5-4657-bb55-c707885f1d0d", "type": "NNNext", - "owner": null, - "bounds": { - "x": -320, - "y": -265, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "68872556-8ebc-45fa-9974-6b1d9fa5fa7b", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "aba29a03-7ea5-4657-bb55-c707885f1d0d", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "3dbddbed-c3ef-4b50-a374-58924877552c": { + { "id": "3dbddbed-c3ef-4b50-a374-58924877552c", - "name": "next", + "source": "aba29a03-7ea5-4657-bb55-c707885f1d0d", + "target": "429c3da2-212e-48da-9eb3-6c824f9b5362", "type": "NNNext", - "owner": null, - "bounds": { - "x": -180, - "y": -265, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "aba29a03-7ea5-4657-bb55-c707885f1d0d", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "19ec6c9c-3b6f-46c3-a9a4-cc37725f7287": { + { "id": "19ec6c9c-3b6f-46c3-a9a4-cc37725f7287", - "name": "next", + "source": "429c3da2-212e-48da-9eb3-6c824f9b5362", + "target": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", "type": "NNNext", - "owner": null, - "bounds": { - "x": -40, - "y": -265, - "width": 40, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 40, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "429c3da2-212e-48da-9eb3-6c824f9b5362", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "810f791c-c473-4213-9e57-f6cb91062d8e": { + { "id": "810f791c-c473-4213-9e57-f6cb91062d8e", - "name": "next", + "source": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", + "target": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", "type": "NNNext", - "owner": null, - "bounds": { - "x": 110, - "y": -265, - "width": 60, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 60, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "9912f3eb-90ad-45f7-a3ed-30f6a4e0ea96", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "46fd52a8-5ee4-4d6f-9ab7-6a6a8f898ea0": { + { "id": "46fd52a8-5ee4-4d6f-9ab7-6a6a8f898ea0", - "name": "next", + "source": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", + "target": "3903acba-4f59-4f5e-b39e-cb6fd8133d01", "type": "NNNext", - "owner": null, - "bounds": { - "x": 280, - "y": -265, - "width": 40, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 40, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "f6b3b33b-4cb0-423b-8e12-a17f92cb008b", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "3903acba-4f59-4f5e-b39e-cb6fd8133d01", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } } - }, - "assessments": {} + ] }, "lastUpdate": "2026-04-10T08:54:21.631Z" } @@ -2510,19 +724,14 @@ "id": "8c65c53a-1961-4fac-85da-271169d789e4", "title": "User Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "UserDiagram", "size": { "width": 1400, "height": 740 }, - "elements": {}, - "relationships": {}, - "interactive": { - "elements": {}, - "relationships": {} - }, - "assessments": {} + "nodes": [], + "edges": [] }, "lastUpdate": "2026-04-08T10:49:34.566Z" } @@ -2560,4 +769,4 @@ }, "exportedAt": "2026-04-10T08:54:51.454Z", "version": "2.0.0" -} \ No newline at end of file +} diff --git a/tests/utilities/web_modeling_editor/converters/nn/fixtures/cnn_rnn.json b/tests/utilities/web_modeling_editor/converters/nn/fixtures/cnn_rnn.json index a1edf32dd..545c187aa 100644 --- a/tests/utilities/web_modeling_editor/converters/nn/fixtures/cnn_rnn.json +++ b/tests/utilities/web_modeling_editor/converters/nn/fixtures/cnn_rnn.json @@ -1,1904 +1,574 @@ { "project": { - "id": "project_1789136775323_fiqcphobm", + "id": "project_1775817484154_z6sfmy78u", "type": "Project", "name": "test", "description": "New project", "owner": "User", - "createdAt": "2026-09-11T14:26:15.323Z", + "createdAt": "2026-04-10T10:38:04.154Z", "currentDiagramType": "NNDiagram", "diagrams": { + "ClassDiagram": [ + { + "id": "acb975da-015d-487a-a1d9-dd4e3cc27675", + "title": "Class Diagram", + "model": { + "version": "4.0.0", + "type": "ClassDiagram", + "size": { + "width": 1400, + "height": 740 + }, + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], + "ObjectDiagram": [ + { + "id": "7c623073-b25c-458a-928c-79c9a51a9dc4", + "title": "Object Diagram", + "model": { + "version": "4.0.0", + "type": "ObjectDiagram", + "size": { + "width": 1400, + "height": 740 + }, + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], + "StateMachineDiagram": [ + { + "id": "92af6fe9-1e42-4159-99bf-baca64982694", + "title": "State Machine Diagram", + "model": { + "version": "4.0.0", + "type": "StateMachineDiagram", + "size": { + "width": 1400, + "height": 740 + }, + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], + "AgentDiagram": [ + { + "id": "3ac42918-e78a-4f30-bf0c-2abf18e00f00", + "title": "Agent Diagram", + "model": { + "version": "4.0.0", + "type": "AgentDiagram", + "size": { + "width": 1400, + "height": 740 + }, + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], "NNDiagram": [ { "id": "a9ead949-1f15-468f-8516-2a0b9716df6f", "title": "NN Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "NNDiagram", "size": { "width": 1720, "height": 800 }, - "interactive": { - "elements": {}, - "relationships": {} - }, - "elements": { - "01face79-fc65-4b0e-8ae7-73aff2392dd6": { + "nodes": [ + { "id": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "name": "cnn-rnn", "type": "NNContainer", - "owner": null, - "bounds": { + "position": { "x": -760, - "y": -380, + "y": -380 + }, + "width": 1600, + "height": 200, + "measured": { "width": 1600, "height": 200 + }, + "data": { + "name": "cnn-rnn" } }, - "27dddc55-125d-4391-a5ca-2468e04aba0a": { + { "id": "27dddc55-125d-4391-a5ca-2468e04aba0a", - "name": "EmbeddingLayer", "type": "EmbeddingLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": -740, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "a57d9dee-cb09-4bbf-af31-4a91986fb0ff", - "7a1fbae4-4259-474d-a36b-ee5a2d45db69", - "a0cf9070-17c0-4044-97ac-8c15887295d5" - ], - "methods": [] - }, - "a57d9dee-cb09-4bbf-af31-4a91986fb0ff": { - "id": "a57d9dee-cb09-4bbf-af31-4a91986fb0ff", - "name": "name = l1", - "type": "NameAttributeEmbedding", - "owner": "27dddc55-125d-4391-a5ca-2468e04aba0a", - "bounds": { - "x": -740, - "y": -310, - "width": 240, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l1", - "isMandatory": true - }, - "7a1fbae4-4259-474d-a36b-ee5a2d45db69": { - "id": "7a1fbae4-4259-474d-a36b-ee5a2d45db69", - "name": "num_embeddings = 5000", - "type": "NumEmbeddingsAttributeEmbedding", - "owner": "27dddc55-125d-4391-a5ca-2468e04aba0a", - "bounds": { - "x": -740, - "y": -310, - "width": 240, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "num_embeddings", - "value": "5000", - "isMandatory": true - }, - "a0cf9070-17c0-4044-97ac-8c15887295d5": { - "id": "a0cf9070-17c0-4044-97ac-8c15887295d5", - "name": "embedding_dim = 50", - "type": "EmbeddingDimAttributeEmbedding", - "owner": "27dddc55-125d-4391-a5ca-2468e04aba0a", - "bounds": { - "x": -740, - "y": -310, - "width": 220, - "height": 20 + "data": { + "name": "EmbeddingLayer", + "attributes": { + "name": "l1", + "num_embeddings": "5000", + "embedding_dim": "50" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "embedding_dim", - "value": "50", - "isMandatory": true + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "08942933-04d5-4966-a5d6-e15b7b81b295": { + { "id": "08942933-04d5-4966-a5d6-e15b7b81b295", - "name": "DropoutLayer", "type": "DropoutLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": -610, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "bf53054c-e229-4a6c-b2b5-38613dca8b00", - "2fa46af0-1c72-4830-951f-35e8a2728a6a" - ], - "methods": [] - }, - "bf53054c-e229-4a6c-b2b5-38613dca8b00": { - "id": "bf53054c-e229-4a6c-b2b5-38613dca8b00", - "name": "name = l2", - "type": "NameAttributeDropout", - "owner": "08942933-04d5-4966-a5d6-e15b7b81b295", - "bounds": { - "x": -610, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l2", - "isMandatory": true - }, - "2fa46af0-1c72-4830-951f-35e8a2728a6a": { - "id": "2fa46af0-1c72-4830-951f-35e8a2728a6a", - "name": "rate = 0.5", - "type": "RateAttributeDropout", - "owner": "08942933-04d5-4966-a5d6-e15b7b81b295", - "bounds": { - "x": -610, - "y": -310, - "width": 160, - "height": 20 + "data": { + "name": "DropoutLayer", + "attributes": { + "name": "l2", + "rate": "0.5" + } }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "rate", - "value": "0.5", - "isMandatory": true + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "52c1d29c-2ce1-401f-a1d0-404045928309": { + { "id": "52c1d29c-2ce1-401f-a1d0-404045928309", - "name": "Conv1DLayer", "type": "Conv1DLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": -480, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "ccf4e1a1-8f69-4c7c-9d3c-dbb9ca0ae2f2", - "de4a0f75-2153-4080-b961-2f82e6c734d0", - "19a54474-40bc-4ddf-adf5-fcda8856d956", - "dbcf0e2f-9069-43ab-8748-354a8120c482", - "f1baf613-7efa-403f-81a6-c977f51a4f6c", - "cbb4c7f7-7a8d-47c7-b4a6-4078cee87489", - "0e056377-131a-4320-b3e4-176c35151600" - ], - "methods": [] - }, - "ccf4e1a1-8f69-4c7c-9d3c-dbb9ca0ae2f2": { - "id": "ccf4e1a1-8f69-4c7c-9d3c-dbb9ca0ae2f2", - "name": "name = l3", - "type": "NameAttributeConv1D", - "owner": "52c1d29c-2ce1-401f-a1d0-404045928309", - "bounds": { - "x": -480, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l3", - "isMandatory": true - }, - "de4a0f75-2153-4080-b961-2f82e6c734d0": { - "id": "de4a0f75-2153-4080-b961-2f82e6c734d0", - "name": "kernel_dim = [4]", - "type": "KernelDimAttributeConv1D", - "owner": "52c1d29c-2ce1-401f-a1d0-404045928309", - "bounds": { - "x": -480, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "kernel_dim", - "value": "[4]", - "isMandatory": true - }, - "19a54474-40bc-4ddf-adf5-fcda8856d956": { - "id": "19a54474-40bc-4ddf-adf5-fcda8856d956", - "name": "out_channels = 200", - "type": "OutChannelsAttributeConv1D", - "owner": "52c1d29c-2ce1-401f-a1d0-404045928309", - "bounds": { - "x": -480, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "out_channels", - "value": "200", - "isMandatory": true - }, - "dbcf0e2f-9069-43ab-8748-354a8120c482": { - "id": "dbcf0e2f-9069-43ab-8748-354a8120c482", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv1D", - "owner": "52c1d29c-2ce1-401f-a1d0-404045928309", - "bounds": { - "x": -480, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "f1baf613-7efa-403f-81a6-c977f51a4f6c": { - "id": "f1baf613-7efa-403f-81a6-c977f51a4f6c", - "name": "in_channels = 50", - "type": "InChannelsAttributeConv1D", - "owner": "52c1d29c-2ce1-401f-a1d0-404045928309", - "bounds": { - "x": -480, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "in_channels", - "value": "50", - "isMandatory": false - }, - "cbb4c7f7-7a8d-47c7-b4a6-4078cee87489": { - "id": "cbb4c7f7-7a8d-47c7-b4a6-4078cee87489", - "name": "input_reused = true", - "type": "InputReusedAttributeConv1D", - "owner": "52c1d29c-2ce1-401f-a1d0-404045928309", - "bounds": { - "x": -480, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "bool", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "input_reused", - "value": "true", - "isMandatory": false - }, - "0e056377-131a-4320-b3e4-176c35151600": { - "id": "0e056377-131a-4320-b3e4-176c35151600", - "name": "name_module_input = l2", - "type": "NameModuleInputAttributeConv1D", - "owner": "52c1d29c-2ce1-401f-a1d0-404045928309", - "bounds": { - "x": -480, - "y": -310, - "width": 240, - "height": 20 + "data": { + "name": "Conv1DLayer", + "attributes": { + "name": "l3", + "kernel_dim": "[4]", + "out_channels": "200", + "actv_func": "relu", + "in_channels": "50", + "input_reused": "true", + "name_module_input": "l2" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name_module_input", - "value": "l2", - "isMandatory": false + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "c2036b06-8920-4075-a35a-54a51393ed33": { + { "id": "c2036b06-8920-4075-a35a-54a51393ed33", - "name": "PoolingLayer", "type": "PoolingLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": -350, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "9de9dd29-d021-4fa4-9e98-2ebc5d54994b", - "22659507-7fce-4c35-85a2-b7ee51b3e3d1", - "72d73721-0458-426b-b778-65819e154f0c", - "0774a2ed-d8f6-4d0c-ba43-5b682599ca25" - ], - "methods": [] - }, - "9de9dd29-d021-4fa4-9e98-2ebc5d54994b": { - "id": "9de9dd29-d021-4fa4-9e98-2ebc5d54994b", - "name": "name = l4", - "type": "NameAttributePooling", - "owner": "c2036b06-8920-4075-a35a-54a51393ed33", - "bounds": { - "x": -350, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l4", - "isMandatory": true - }, - "22659507-7fce-4c35-85a2-b7ee51b3e3d1": { - "id": "22659507-7fce-4c35-85a2-b7ee51b3e3d1", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "c2036b06-8920-4075-a35a-54a51393ed33", - "bounds": { - "x": -350, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "72d73721-0458-426b-b778-65819e154f0c": { - "id": "72d73721-0458-426b-b778-65819e154f0c", - "name": "dimension = 1D", - "type": "DimensionAttributePooling", - "owner": "c2036b06-8920-4075-a35a-54a51393ed33", - "bounds": { - "x": -350, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "dimension", - "value": "1D", - "isMandatory": true - }, - "0774a2ed-d8f6-4d0c-ba43-5b682599ca25": { - "id": "0774a2ed-d8f6-4d0c-ba43-5b682599ca25", - "name": "kernel_dim = [2]", - "type": "KernelDimAttributePooling", - "owner": "c2036b06-8920-4075-a35a-54a51393ed33", - "bounds": { - "x": -350, - "y": -310, - "width": 180, - "height": 20 + "data": { + "name": "PoolingLayer", + "attributes": { + "name": "l4", + "pooling_type": "max", + "kernel_dim": "[2]", + "pooling.dimension": "1D" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "kernel_dim", - "value": "[2]", - "isMandatory": false + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "3c7d70df-1d1d-48a0-93e9-623ac5292ff5": { + { "id": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "name": "Conv1DLayer", "type": "Conv1DLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": -220, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "fd4fb9bb-841e-4e7b-8682-bfff9d3d4855", - "06798207-de1c-4642-a62e-43253c835c8f", - "2dd970b9-60b8-453b-8b00-1c57de44f74d", - "e50a7b65-513e-4cb1-b02c-553a3d835a5c", - "985e1f68-1df1-42ff-ae0f-ce020f699416", - "5216fec4-c6f7-4b2a-bde3-0b3e3c88ae25", - "e63c8b09-160d-473c-aa18-7a5b7977b666" - ], - "methods": [] - }, - "fd4fb9bb-841e-4e7b-8682-bfff9d3d4855": { - "id": "fd4fb9bb-841e-4e7b-8682-bfff9d3d4855", - "name": "name = l5", - "type": "NameAttributeConv1D", - "owner": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "bounds": { - "x": -220, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l5", - "isMandatory": true - }, - "06798207-de1c-4642-a62e-43253c835c8f": { - "id": "06798207-de1c-4642-a62e-43253c835c8f", - "name": "kernel_dim = [5]", - "type": "KernelDimAttributeConv1D", - "owner": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "bounds": { - "x": -220, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "kernel_dim", - "value": "[5]", - "isMandatory": true - }, - "2dd970b9-60b8-453b-8b00-1c57de44f74d": { - "id": "2dd970b9-60b8-453b-8b00-1c57de44f74d", - "name": "out_channels = 200", - "type": "OutChannelsAttributeConv1D", - "owner": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "bounds": { - "x": -220, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "out_channels", - "value": "200", - "isMandatory": true - }, - "e50a7b65-513e-4cb1-b02c-553a3d835a5c": { - "id": "e50a7b65-513e-4cb1-b02c-553a3d835a5c", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv1D", - "owner": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "bounds": { - "x": -220, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "985e1f68-1df1-42ff-ae0f-ce020f699416": { - "id": "985e1f68-1df1-42ff-ae0f-ce020f699416", - "name": "in_channels = 50", - "type": "InChannelsAttributeConv1D", - "owner": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "bounds": { - "x": -220, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "in_channels", - "value": "50", - "isMandatory": false - }, - "5216fec4-c6f7-4b2a-bde3-0b3e3c88ae25": { - "id": "5216fec4-c6f7-4b2a-bde3-0b3e3c88ae25", - "name": "input_reused = true", - "type": "InputReusedAttributeConv1D", - "owner": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "bounds": { - "x": -220, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "bool", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "input_reused", - "value": "true", - "isMandatory": false - }, - "e63c8b09-160d-473c-aa18-7a5b7977b666": { - "id": "e63c8b09-160d-473c-aa18-7a5b7977b666", - "name": "name_module_input = l2", - "type": "NameModuleInputAttributeConv1D", - "owner": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "bounds": { - "x": -220, - "y": -310, - "width": 240, - "height": 20 + "data": { + "name": "Conv1DLayer", + "attributes": { + "name": "l5", + "kernel_dim": "[5]", + "out_channels": "200", + "actv_func": "relu", + "in_channels": "50", + "input_reused": "true", + "name_module_input": "l2" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name_module_input", - "value": "l2", - "isMandatory": false + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "843e5eb8-7ec3-4c84-9fdc-399904fc05fe": { + { "id": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", - "name": "TensorOp", "type": "TensorOp", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": 40, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "01028517-5e03-4c5a-b4f2-430c04faf2cb", - "9f10acd2-163b-4b2e-b1e6-1cb829a30dc0", - "96554cb5-2e11-4581-a9a0-e0b948e77860", - "979eafff-257c-4752-bddf-b70ba890c314" - ], - "methods": [] - }, - "01028517-5e03-4c5a-b4f2-430c04faf2cb": { - "id": "01028517-5e03-4c5a-b4f2-430c04faf2cb", - "name": "name = op1", - "type": "NameAttributeTensorOp", - "owner": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", - "bounds": { - "x": 40, - "y": -310, - "width": 230, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "op1", - "isMandatory": true - }, - "9f10acd2-163b-4b2e-b1e6-1cb829a30dc0": { - "id": "9f10acd2-163b-4b2e-b1e6-1cb829a30dc0", - "name": "tns_type = concatenate", - "type": "TnsTypeAttributeTensorOp", - "owner": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", - "bounds": { - "x": 40, - "y": -310, - "width": 230, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "tns_type", - "value": "concatenate", - "isMandatory": true - }, - "96554cb5-2e11-4581-a9a0-e0b948e77860": { - "id": "96554cb5-2e11-4581-a9a0-e0b948e77860", - "name": "concatenate_dim = -1", - "type": "ConcatenateDimAttributeTensorOp", - "owner": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", - "bounds": { - "x": 40, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "concatenate_dim", - "value": "-1", - "isMandatory": false - }, - "979eafff-257c-4752-bddf-b70ba890c314": { - "id": "979eafff-257c-4752-bddf-b70ba890c314", - "name": "layers_of_tensors = ['l4', 'l6']", - "type": "LayersOfTensorsAttributeTensorOp", - "owner": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", - "bounds": { - "x": 40, - "y": -310, - "width": 270, - "height": 20 + "data": { + "name": "TensorOp", + "attributes": { + "name": "op1", + "tns_type": "concatenate", + "concatenate_dim": "-1", + "layers_of_tensors": "['l4', 'l6']" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "layers_of_tensors", - "value": "['l4', 'l6']", - "isMandatory": false + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "7fcd1fc2-5eef-455f-b341-d122bfc766c2": { + { "id": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": 430, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "b1fbf642-3803-49ab-8c5b-173ba6dea462", - "f070d97f-5de3-43c3-aece-f94ad206d3bb", - "f3d0b11d-1421-454b-902e-d92c7ca151ea", - "4a705416-1806-4282-95fb-81dd55e616bb", - "89a71c80-bb10-42d0-87c6-84b3cd4e5f15" - ], - "methods": [] - }, - "b1fbf642-3803-49ab-8c5b-173ba6dea462": { - "id": "b1fbf642-3803-49ab-8c5b-173ba6dea462", - "name": "name = l9", - "type": "NameAttributeLinear", - "owner": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", - "bounds": { - "x": 430, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l9", - "isMandatory": true - }, - "f070d97f-5de3-43c3-aece-f94ad206d3bb": { - "id": "f070d97f-5de3-43c3-aece-f94ad206d3bb", - "name": "out_features = 400", - "type": "OutFeaturesAttributeLinear", - "owner": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", - "bounds": { - "x": 430, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "out_features", - "value": "400", - "isMandatory": true - }, - "f3d0b11d-1421-454b-902e-d92c7ca151ea": { - "id": "f3d0b11d-1421-454b-902e-d92c7ca151ea", - "name": "actv_func = relu", - "type": "ActvFuncAttributeLinear", - "owner": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", - "bounds": { - "x": 430, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "4a705416-1806-4282-95fb-81dd55e616bb": { - "id": "4a705416-1806-4282-95fb-81dd55e616bb", - "name": "in_features = 100", - "type": "InFeaturesAttributeLinear", - "owner": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", - "bounds": { - "x": 430, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "in_features", - "value": "100", - "isMandatory": false - }, - "89a71c80-bb10-42d0-87c6-84b3cd4e5f15": { - "id": "89a71c80-bb10-42d0-87c6-84b3cd4e5f15", - "name": "name_module_input = l8", - "type": "NameModuleInputAttributeLinear", - "owner": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", - "bounds": { - "x": 430, - "y": -310, - "width": 240, - "height": 20 + "data": { + "name": "LinearLayer", + "attributes": { + "name": "l9", + "out_features": "400", + "actv_func": "relu", + "in_features": "100", + "name_module_input": "l8" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name_module_input", - "value": "l8", - "isMandatory": false + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "d1a37961-c94a-419a-b335-ed3d97821bea": { + { "id": "d1a37961-c94a-419a-b335-ed3d97821bea", - "name": "DropoutLayer", "type": "DropoutLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": 560, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "cf7a9bf6-7699-4531-9c55-b78eabe09878", - "8b9ae3bd-f39c-428c-94ea-e236a565f9a7" - ], - "methods": [] - }, - "cf7a9bf6-7699-4531-9c55-b78eabe09878": { - "id": "cf7a9bf6-7699-4531-9c55-b78eabe09878", - "name": "name = l10", - "type": "NameAttributeDropout", - "owner": "d1a37961-c94a-419a-b335-ed3d97821bea", - "bounds": { - "x": 560, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l10", - "isMandatory": true - }, - "8b9ae3bd-f39c-428c-94ea-e236a565f9a7": { - "id": "8b9ae3bd-f39c-428c-94ea-e236a565f9a7", - "name": "rate = 0.1", - "type": "RateAttributeDropout", - "owner": "d1a37961-c94a-419a-b335-ed3d97821bea", - "bounds": { - "x": 560, - "y": -310, - "width": 160, - "height": 20 + "data": { + "name": "DropoutLayer", + "attributes": { + "name": "l10", + "rate": "0.1" + } }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "rate", - "value": "0.1", - "isMandatory": true + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "db825386-c3b1-400d-b528-2d383c96a74e": { + { "id": "db825386-c3b1-400d-b528-2d383c96a74e", - "name": "PoolingLayer", "type": "PoolingLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": -90, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "292e067f-3c45-4275-9157-7d333254e8b4", - "e9130b24-4684-40e4-9442-66709268db06", - "821c2315-71ed-40d1-bef7-9a89dc3b8202", - "72d49255-3413-4bdd-bbd8-f1a8e0aaa0d4" - ], - "methods": [] - }, - "292e067f-3c45-4275-9157-7d333254e8b4": { - "id": "292e067f-3c45-4275-9157-7d333254e8b4", - "name": "name = l6", - "type": "NameAttributePooling", - "owner": "db825386-c3b1-400d-b528-2d383c96a74e", - "bounds": { - "x": -90, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l6", - "isMandatory": true - }, - "e9130b24-4684-40e4-9442-66709268db06": { - "id": "e9130b24-4684-40e4-9442-66709268db06", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "db825386-c3b1-400d-b528-2d383c96a74e", - "bounds": { - "x": -90, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "821c2315-71ed-40d1-bef7-9a89dc3b8202": { - "id": "821c2315-71ed-40d1-bef7-9a89dc3b8202", - "name": "dimension = 1D", - "type": "DimensionAttributePooling", - "owner": "db825386-c3b1-400d-b528-2d383c96a74e", - "bounds": { - "x": -90, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "dimension", - "value": "1D", - "isMandatory": true - }, - "72d49255-3413-4bdd-bbd8-f1a8e0aaa0d4": { - "id": "72d49255-3413-4bdd-bbd8-f1a8e0aaa0d4", - "name": "kernel_dim = [2]", - "type": "KernelDimAttributePooling", - "owner": "db825386-c3b1-400d-b528-2d383c96a74e", - "bounds": { - "x": -90, - "y": -310, - "width": 180, - "height": 20 + "data": { + "name": "PoolingLayer", + "attributes": { + "name": "l6", + "pooling_type": "max", + "kernel_dim": "[2]", + "pooling.dimension": "1D" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "kernel_dim", - "value": "[2]", - "isMandatory": false + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "4be31f35-aeaf-4c07-bad8-959b3ef0235b": { + { "id": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", - "name": "GRULayer", "type": "GRULayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": 300, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "27e0fc7f-ba5e-428c-bde1-9f8ef80a1a24", - "06eb913e-4549-4a01-8253-720b6cf397c3", - "f92c8e01-07a1-4fb6-9bca-794bc167e237", - "c16170c8-dc80-45a8-91ef-3a844d44326b", - "ff0a9070-739e-408d-8641-886e2e3b0c86" - ], - "methods": [] - }, - "27e0fc7f-ba5e-428c-bde1-9f8ef80a1a24": { - "id": "27e0fc7f-ba5e-428c-bde1-9f8ef80a1a24", - "name": "name = l8", - "type": "NameAttributeGRU", - "owner": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", - "bounds": { - "x": 300, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l8", - "isMandatory": true - }, - "06eb913e-4549-4a01-8253-720b6cf397c3": { - "id": "06eb913e-4549-4a01-8253-720b6cf397c3", - "name": "hidden_size = 100", - "type": "HiddenSizeAttributeGRU", - "owner": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", - "bounds": { - "x": 300, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "hidden_size", - "value": "100", - "isMandatory": true - }, - "f92c8e01-07a1-4fb6-9bca-794bc167e237": { - "id": "f92c8e01-07a1-4fb6-9bca-794bc167e237", - "name": "input_size = 400", - "type": "InputSizeAttributeGRU", - "owner": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", - "bounds": { - "x": 300, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "input_size", - "value": "400", - "isMandatory": false - }, - "c16170c8-dc80-45a8-91ef-3a844d44326b": { - "id": "c16170c8-dc80-45a8-91ef-3a844d44326b", - "name": "return_type = last", - "type": "ReturnTypeAttributeGRU", - "owner": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", - "bounds": { - "x": 300, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "return_type", - "value": "last", - "isMandatory": false - }, - "ff0a9070-739e-408d-8641-886e2e3b0c86": { - "id": "ff0a9070-739e-408d-8641-886e2e3b0c86", - "name": "batch_first = true", - "type": "BatchFirstAttributeGRU", - "owner": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", - "bounds": { - "x": 300, - "y": -310, - "width": 190, - "height": 20 + "data": { + "name": "GRULayer", + "attributes": { + "name": "l8", + "hidden_size": "100", + "input_size": "400", + "return_type": "last", + "batch_first": "true" + } }, - "code": "", - "visibility": "public", - "attributeType": "bool", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "batch_first", - "value": "true", - "isMandatory": false + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "13d1b075-1b23-420c-977d-b159c5bb8da9": { + { "id": "13d1b075-1b23-420c-977d-b159c5bb8da9", - "name": "DropoutLayer", "type": "DropoutLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": 170, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "dd8c9291-2404-4bd5-b029-149ca1792d28", - "596f1c29-2600-40e3-8199-0a35a02b4226" - ], - "methods": [] - }, - "dd8c9291-2404-4bd5-b029-149ca1792d28": { - "id": "dd8c9291-2404-4bd5-b029-149ca1792d28", - "name": "name = l7", - "type": "NameAttributeDropout", - "owner": "13d1b075-1b23-420c-977d-b159c5bb8da9", - "bounds": { - "x": 170, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l7", - "isMandatory": true - }, - "596f1c29-2600-40e3-8199-0a35a02b4226": { - "id": "596f1c29-2600-40e3-8199-0a35a02b4226", - "name": "rate = 0.15", - "type": "RateAttributeDropout", - "owner": "13d1b075-1b23-420c-977d-b159c5bb8da9", - "bounds": { - "x": 170, - "y": -310, - "width": 160, - "height": 20 + "data": { + "name": "DropoutLayer", + "attributes": { + "name": "l7", + "rate": "0.15" + } }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "rate", - "value": "0.15", - "isMandatory": true + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" }, - "b6081db7-5d5e-479c-8ce6-c6e89c403db3": { + { "id": "b6081db7-5d5e-479c-8ce6-c6e89c403db3", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "01face79-fc65-4b0e-8ae7-73aff2392dd6", - "bounds": { + "position": { "x": 700, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "e1767a69-407f-48dd-87a0-1b5db8866d22", - "460a2d3f-db59-479d-bf15-59e7d6ae89aa", - "dfa6a1ba-fcd1-446b-9941-a5b315a75e96", - "530a95fa-1b46-4281-8235-c1e527be4443" - ], - "methods": [] - }, - "e1767a69-407f-48dd-87a0-1b5db8866d22": { - "id": "e1767a69-407f-48dd-87a0-1b5db8866d22", - "name": "name = l11", - "type": "NameAttributeLinear", - "owner": "b6081db7-5d5e-479c-8ce6-c6e89c403db3", - "bounds": { - "x": 700, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l11", - "isMandatory": true - }, - "460a2d3f-db59-479d-bf15-59e7d6ae89aa": { - "id": "460a2d3f-db59-479d-bf15-59e7d6ae89aa", - "name": "out_features = 1", - "type": "OutFeaturesAttributeLinear", - "owner": "b6081db7-5d5e-479c-8ce6-c6e89c403db3", - "bounds": { - "x": 700, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "out_features", - "value": "1", - "isMandatory": true - }, - "dfa6a1ba-fcd1-446b-9941-a5b315a75e96": { - "id": "dfa6a1ba-fcd1-446b-9941-a5b315a75e96", - "name": "actv_func = sigmoid", - "type": "ActvFuncAttributeLinear", - "owner": "b6081db7-5d5e-479c-8ce6-c6e89c403db3", - "bounds": { - "x": 700, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "actv_func", - "value": "sigmoid", - "isMandatory": false - }, - "530a95fa-1b46-4281-8235-c1e527be4443": { - "id": "530a95fa-1b46-4281-8235-c1e527be4443", - "name": "in_features = 400", - "type": "InFeaturesAttributeLinear", - "owner": "b6081db7-5d5e-479c-8ce6-c6e89c403db3", - "bounds": { - "x": 700, - "y": -310, - "width": 180, - "height": 20 + "data": { + "name": "LinearLayer", + "attributes": { + "name": "l11", + "out_features": "1", + "actv_func": "sigmoid", + "in_features": "400" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "in_features", - "value": "400", - "isMandatory": false + "parentId": "01face79-fc65-4b0e-8ae7-73aff2392dd6" } - }, - "relationships": { - "3cf3681d-7554-4ff2-b896-65427209c3fd": { + ], + "edges": [ + { "id": "3cf3681d-7554-4ff2-b896-65427209c3fd", - "name": "next", + "source": "27dddc55-125d-4391-a5ca-2468e04aba0a", + "target": "08942933-04d5-4966-a5d6-e15b7b81b295", "type": "NNNext", - "owner": null, - "bounds": { - "x": -630, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "27dddc55-125d-4391-a5ca-2468e04aba0a", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "08942933-04d5-4966-a5d6-e15b7b81b295", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "a7fb9bd2-a7d6-42ca-af46-e5fb61be47e9": { + { "id": "a7fb9bd2-a7d6-42ca-af46-e5fb61be47e9", - "name": "next", + "source": "08942933-04d5-4966-a5d6-e15b7b81b295", + "target": "52c1d29c-2ce1-401f-a1d0-404045928309", "type": "NNNext", - "owner": null, - "bounds": { - "x": -500, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "08942933-04d5-4966-a5d6-e15b7b81b295", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "52c1d29c-2ce1-401f-a1d0-404045928309", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "a2d227ea-0f2c-4789-9fb9-7c8b9a664973": { + { "id": "a2d227ea-0f2c-4789-9fb9-7c8b9a664973", - "name": "next", + "source": "52c1d29c-2ce1-401f-a1d0-404045928309", + "target": "c2036b06-8920-4075-a35a-54a51393ed33", "type": "NNNext", - "owner": null, - "bounds": { - "x": -370, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "52c1d29c-2ce1-401f-a1d0-404045928309", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "c2036b06-8920-4075-a35a-54a51393ed33", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "6fe01ecd-1188-4bf5-b367-f41278865626": { + { "id": "6fe01ecd-1188-4bf5-b367-f41278865626", - "name": "next", + "source": "c2036b06-8920-4075-a35a-54a51393ed33", + "target": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", "type": "NNNext", - "owner": null, - "bounds": { - "x": -240, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "c2036b06-8920-4075-a35a-54a51393ed33", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "defea85a-0ac8-40f2-9948-e3bcd96e9ccc": { + { "id": "defea85a-0ac8-40f2-9948-e3bcd96e9ccc", - "name": "next", + "source": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", + "target": "db825386-c3b1-400d-b528-2d383c96a74e", "type": "NNNext", - "owner": null, - "bounds": { - "x": -110, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "3c7d70df-1d1d-48a0-93e9-623ac5292ff5", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "db825386-c3b1-400d-b528-2d383c96a74e", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "e68f5547-ff1b-458b-99b3-76dfd75ef529": { + { "id": "e68f5547-ff1b-458b-99b3-76dfd75ef529", - "name": "next", + "source": "db825386-c3b1-400d-b528-2d383c96a74e", + "target": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", "type": "NNNext", - "owner": null, - "bounds": { - "x": 20, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "db825386-c3b1-400d-b528-2d383c96a74e", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "e64da548-678f-4f71-a5ac-c5c6e6f43de9": { + { "id": "e64da548-678f-4f71-a5ac-c5c6e6f43de9", - "name": "next", + "source": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", + "target": "13d1b075-1b23-420c-977d-b159c5bb8da9", "type": "NNNext", - "owner": null, - "bounds": { - "x": 150, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "843e5eb8-7ec3-4c84-9fdc-399904fc05fe", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "13d1b075-1b23-420c-977d-b159c5bb8da9", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "ecee9333-2b12-463d-9ec7-6baf8b098233": { + { "id": "ecee9333-2b12-463d-9ec7-6baf8b098233", - "name": "next", + "source": "13d1b075-1b23-420c-977d-b159c5bb8da9", + "target": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", "type": "NNNext", - "owner": null, - "bounds": { - "x": 280, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "13d1b075-1b23-420c-977d-b159c5bb8da9", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "bbf4c518-33f9-4d09-929e-19269347abaf": { + { "id": "bbf4c518-33f9-4d09-929e-19269347abaf", - "name": "next", + "source": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", + "target": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", "type": "NNNext", - "owner": null, - "bounds": { - "x": 410, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "4be31f35-aeaf-4c07-bad8-959b3ef0235b", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "f3548ef6-3170-407d-af56-3765429e8afd": { + { "id": "f3548ef6-3170-407d-af56-3765429e8afd", - "name": "next", + "source": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", + "target": "d1a37961-c94a-419a-b335-ed3d97821bea", "type": "NNNext", - "owner": null, - "bounds": { - "x": 540, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "7fcd1fc2-5eef-455f-b341-d122bfc766c2", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "d1a37961-c94a-419a-b335-ed3d97821bea", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "7760e04a-e3be-4cd8-b5e0-8f31526d4d67": { + { "id": "7760e04a-e3be-4cd8-b5e0-8f31526d4d67", - "name": "next", + "source": "d1a37961-c94a-419a-b335-ed3d97821bea", + "target": "b6081db7-5d5e-479c-8ce6-c6e89c403db3", "type": "NNNext", - "owner": null, - "bounds": { - "x": 670, - "y": -265, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "d1a37961-c94a-419a-b335-ed3d97821bea", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "b6081db7-5d5e-479c-8ce6-c6e89c403db3", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } } + ] + }, + "lastUpdate": "2026-04-10T11:11:08.545Z" + } + ], + "UserDiagram": [ + { + "id": "8c65c53a-1961-4fac-85da-271169d789e4", + "title": "User Diagram", + "model": { + "version": "4.0.0", + "type": "UserDiagram", + "size": { + "width": 1400, + "height": 740 }, - "assessments": {} + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], + "QuantumCircuitDiagram": [ + { + "id": "a5305903-0441-43cb-a268-052815a4d17e", + "title": "Quantum Circuit", + "model": { + "cols": [], + "gates": [], + "gateMetadata": {}, + "initialStates": [], + "version": "1.0.0" }, - "lastUpdate": "2026-09-11T14:26:45.637Z" + "lastUpdate": "2026-04-08T10:49:34.566Z" } ] }, "settings": { "defaultDiagramType": "ClassDiagram", "autoSave": true, - "collaborationEnabled": false, - "perspectives": { - "ClassDiagram": true, - "ObjectDiagram": true, - "StateMachineDiagram": true, - "AgentDiagram": true, - "UserDiagram": true, - "GUINoCodeDiagram": true, - "QuantumCircuitDiagram": true, - "NNDiagram": true, - "BPMN": true - } + "collaborationEnabled": false }, "currentDiagramIndices": { "ClassDiagram": 0, @@ -1907,12 +577,10 @@ "AgentDiagram": 0, "NNDiagram": 0, "UserDiagram": 0, - "GUINoCodeDiagram": 0, - "QuantumCircuitDiagram": 0, - "BPMN": 0 + "QuantumCircuitDiagram": 0 }, - "schemaVersion": 4 + "schemaVersion": 3 }, - "exportedAt": "2026-09-11T14:26:59.477Z", + "exportedAt": "2026-04-10T11:15:15.936Z", "version": "2.0.0" -} \ No newline at end of file +} diff --git a/tests/utilities/web_modeling_editor/converters/nn/fixtures/lstm.json b/tests/utilities/web_modeling_editor/converters/nn/fixtures/lstm.json index 6112ab94f..f4465d64a 100644 --- a/tests/utilities/web_modeling_editor/converters/nn/fixtures/lstm.json +++ b/tests/utilities/web_modeling_editor/converters/nn/fixtures/lstm.json @@ -1,1264 +1,398 @@ { "project": { - "id": "project_1789137281339_7g9z6kwoj", + "id": "project_1775817484154_z6sfmy78u", "type": "Project", "name": "test", "description": "New project", "owner": "User", - "createdAt": "2026-09-11T14:34:41.339Z", + "createdAt": "2026-04-10T10:38:04.154Z", "currentDiagramType": "NNDiagram", "diagrams": { + "ClassDiagram": [ + { + "id": "acb975da-015d-487a-a1d9-dd4e3cc27675", + "title": "Class Diagram", + "model": { + "version": "4.0.0", + "type": "ClassDiagram", + "size": { + "width": 1400, + "height": 740 + }, + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], + "ObjectDiagram": [ + { + "id": "7c623073-b25c-458a-928c-79c9a51a9dc4", + "title": "Object Diagram", + "model": { + "version": "4.0.0", + "type": "ObjectDiagram", + "size": { + "width": 1400, + "height": 740 + }, + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], + "StateMachineDiagram": [ + { + "id": "92af6fe9-1e42-4159-99bf-baca64982694", + "title": "State Machine Diagram", + "model": { + "version": "4.0.0", + "type": "StateMachineDiagram", + "size": { + "width": 1400, + "height": 740 + }, + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], + "AgentDiagram": [ + { + "id": "3ac42918-e78a-4f30-bf0c-2abf18e00f00", + "title": "Agent Diagram", + "model": { + "version": "4.0.0", + "type": "AgentDiagram", + "size": { + "width": 1400, + "height": 740 + }, + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], "NNDiagram": [ { "id": "a9ead949-1f15-468f-8516-2a0b9716df6f", "title": "NN Diagram", "model": { - "version": "3.0.0", + "version": "4.0.0", "type": "NNDiagram", "size": { "width": 1020, "height": 780 }, - "interactive": { - "elements": {}, - "relationships": {} - }, - "elements": { - "90295e37-f91c-4880-8924-d4d78c99d4b7": { + "nodes": [ + { "id": "90295e37-f91c-4880-8924-d4d78c99d4b7", - "name": "lstm", "type": "NNContainer", - "owner": null, - "bounds": { + "position": { "x": -490, - "y": -370, + "y": -370 + }, + "width": 890, + "height": 190, + "measured": { "width": 890, "height": 190 + }, + "data": { + "name": "lstm" } }, - "22978aef-63f0-4386-b7cd-3c72441570da": { + { "id": "22978aef-63f0-4386-b7cd-3c72441570da", - "name": "EmbeddingLayer", "type": "EmbeddingLayer", - "owner": "90295e37-f91c-4880-8924-d4d78c99d4b7", - "bounds": { + "position": { "x": -460, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "65d59643-67b3-4ff6-977a-9c5e6084ac4e", - "42a9dc8d-fb8e-469a-8c8f-b77985d5ac0c", - "63608404-282e-4a2b-a6b9-79ccb1199e6a" - ], - "methods": [] - }, - "65d59643-67b3-4ff6-977a-9c5e6084ac4e": { - "id": "65d59643-67b3-4ff6-977a-9c5e6084ac4e", - "name": "name = l1", - "type": "NameAttributeEmbedding", - "owner": "22978aef-63f0-4386-b7cd-3c72441570da", - "bounds": { - "x": -460, - "y": -310, - "width": 240, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l1", - "isMandatory": true - }, - "42a9dc8d-fb8e-469a-8c8f-b77985d5ac0c": { - "id": "42a9dc8d-fb8e-469a-8c8f-b77985d5ac0c", - "name": "num_embeddings = 10000", - "type": "NumEmbeddingsAttributeEmbedding", - "owner": "22978aef-63f0-4386-b7cd-3c72441570da", - "bounds": { - "x": -460, - "y": -310, - "width": 250, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "num_embeddings", - "value": "10000", - "isMandatory": true - }, - "63608404-282e-4a2b-a6b9-79ccb1199e6a": { - "id": "63608404-282e-4a2b-a6b9-79ccb1199e6a", - "name": "embedding_dim = 326", - "type": "EmbeddingDimAttributeEmbedding", - "owner": "22978aef-63f0-4386-b7cd-3c72441570da", - "bounds": { - "x": -460, - "y": -310, - "width": 220, - "height": 20 + "data": { + "name": "EmbeddingLayer", + "attributes": { + "name": "l1", + "num_embeddings": "10000", + "embedding_dim": "326" + } }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "embedding_dim", - "value": "326", - "isMandatory": true + "parentId": "90295e37-f91c-4880-8924-d4d78c99d4b7" }, - "230c2136-ba70-43f4-a51c-3a0fc3f9a33b": { + { "id": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "name": "LSTMLayer", "type": "LSTMLayer", - "owner": "90295e37-f91c-4880-8924-d4d78c99d4b7", - "bounds": { + "position": { "x": -320, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "54af6072-7d26-4c19-a872-14ad82b9e1e6", - "43ec8938-f7c9-4d9c-a7a3-5e74c3911d5d", - "bd2b52d0-9054-43ae-bcf5-00d543c70e34", - "0aa522e2-d8c0-41e0-a0ba-6c214cf23856", - "bcd3c69d-f6b3-42a7-a4dd-1c1972942f08", - "b9273a55-5607-43fb-a212-b56659fd4f5c", - "b568e0c4-41af-4ce6-91ac-d29f6d411dae" - ], - "methods": [] - }, - "54af6072-7d26-4c19-a872-14ad82b9e1e6": { - "id": "54af6072-7d26-4c19-a872-14ad82b9e1e6", - "name": "name = l2", - "type": "NameAttributeLSTM", - "owner": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "bounds": { - "x": -320, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l2", - "isMandatory": true - }, - "43ec8938-f7c9-4d9c-a7a3-5e74c3911d5d": { - "id": "43ec8938-f7c9-4d9c-a7a3-5e74c3911d5d", - "name": "hidden_size = 40", - "type": "HiddenSizeAttributeLSTM", - "owner": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "bounds": { - "x": -320, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "hidden_size", - "value": "40", - "isMandatory": true - }, - "bd2b52d0-9054-43ae-bcf5-00d543c70e34": { - "id": "bd2b52d0-9054-43ae-bcf5-00d543c70e34", - "name": "return_type = full", - "type": "ReturnTypeAttributeLSTM", - "owner": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "bounds": { - "x": -320, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "return_type", - "value": "full", - "isMandatory": false - }, - "0aa522e2-d8c0-41e0-a0ba-6c214cf23856": { - "id": "0aa522e2-d8c0-41e0-a0ba-6c214cf23856", - "name": "input_size = 326", - "type": "InputSizeAttributeLSTM", - "owner": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "bounds": { - "x": -320, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "input_size", - "value": "326", - "isMandatory": false - }, - "bcd3c69d-f6b3-42a7-a4dd-1c1972942f08": { - "id": "bcd3c69d-f6b3-42a7-a4dd-1c1972942f08", - "name": "dropout = 0.5", - "type": "DropoutAttributeLSTM", - "owner": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "bounds": { - "x": -320, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "dropout", - "value": "0.5", - "isMandatory": false - }, - "b9273a55-5607-43fb-a212-b56659fd4f5c": { - "id": "b9273a55-5607-43fb-a212-b56659fd4f5c", - "name": "bidirectional = true", - "type": "BidirectionalAttributeLSTM", - "owner": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "bounds": { - "x": -320, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "bool", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "bidirectional", - "value": "true", - "isMandatory": false - }, - "b568e0c4-41af-4ce6-91ac-d29f6d411dae": { - "id": "b568e0c4-41af-4ce6-91ac-d29f6d411dae", - "name": "batch_first = true", - "type": "BatchFirstAttributeLSTM", - "owner": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "bounds": { - "x": -320, - "y": -310, - "width": 190, - "height": 20 + "data": { + "name": "LSTMLayer", + "attributes": { + "name": "l2", + "hidden_size": "40", + "return_type": "full", + "input_size": "326", + "dropout": "0.5", + "bidirectional": "true", + "batch_first": "true" + } }, - "code": "", - "visibility": "public", - "attributeType": "bool", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "batch_first", - "value": "true", - "isMandatory": false + "parentId": "90295e37-f91c-4880-8924-d4d78c99d4b7" }, - "29f79d1a-bb72-4e16-b43c-74141ee4085d": { + { "id": "29f79d1a-bb72-4e16-b43c-74141ee4085d", - "name": "DropoutLayer", "type": "DropoutLayer", - "owner": "90295e37-f91c-4880-8924-d4d78c99d4b7", - "bounds": { + "position": { "x": -190, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "9d5946eb-457f-40be-8d5c-18cfbbb773b4", - "23f84f8b-16e0-413c-9e07-959909549f16", - "82ff7c5e-af17-4efb-9b6d-65ac41d1afa9" - ], - "methods": [] - }, - "9d5946eb-457f-40be-8d5c-18cfbbb773b4": { - "id": "9d5946eb-457f-40be-8d5c-18cfbbb773b4", - "name": "name = l3", - "type": "NameAttributeDropout", - "owner": "29f79d1a-bb72-4e16-b43c-74141ee4085d", - "bounds": { - "x": -190, - "y": -310, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l3", - "isMandatory": true - }, - "23f84f8b-16e0-413c-9e07-959909549f16": { - "id": "23f84f8b-16e0-413c-9e07-959909549f16", - "name": "rate = 0.2", - "type": "RateAttributeDropout", - "owner": "29f79d1a-bb72-4e16-b43c-74141ee4085d", - "bounds": { - "x": -190, - "y": -310, - "width": 160, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "rate", - "value": "0.2", - "isMandatory": true - }, - "82ff7c5e-af17-4efb-9b6d-65ac41d1afa9": { - "id": "82ff7c5e-af17-4efb-9b6d-65ac41d1afa9", - "name": "name_module_input = l2", - "type": "NameModuleInputAttributeDropout", - "owner": "29f79d1a-bb72-4e16-b43c-74141ee4085d", - "bounds": { - "x": -190, - "y": -310, - "width": 240, - "height": 20 + "data": { + "name": "DropoutLayer", + "attributes": { + "name": "l3", + "rate": "0.2", + "name_module_input": "l2" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name_module_input", - "value": "l2", - "isMandatory": false + "parentId": "90295e37-f91c-4880-8924-d4d78c99d4b7" }, - "99723b0a-7145-4193-a316-624e28dfc76d": { + { "id": "99723b0a-7145-4193-a316-624e28dfc76d", - "name": "LSTMLayer", "type": "LSTMLayer", - "owner": "90295e37-f91c-4880-8924-d4d78c99d4b7", - "bounds": { + "position": { "x": -50, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "f62cc7d1-55be-4693-bad2-053e504656d1", - "fc8bd2d5-32a2-4434-bd60-0b4811f01468", - "325612cb-6b8d-481b-9235-ffeb4360d73b", - "9ce051a3-f712-4a3f-beda-ed41d8cb77b6", - "4cda0910-f668-4a55-a4af-4fbdcf417b9b", - "32376196-b191-4b63-b529-5a32882d26f5" - ], - "methods": [] - }, - "f62cc7d1-55be-4693-bad2-053e504656d1": { - "id": "f62cc7d1-55be-4693-bad2-053e504656d1", - "name": "name = l4", - "type": "NameAttributeLSTM", - "owner": "99723b0a-7145-4193-a316-624e28dfc76d", - "bounds": { - "x": -50, - "y": -310, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l4", - "isMandatory": true - }, - "fc8bd2d5-32a2-4434-bd60-0b4811f01468": { - "id": "fc8bd2d5-32a2-4434-bd60-0b4811f01468", - "name": "hidden_size = 40", - "type": "HiddenSizeAttributeLSTM", - "owner": "99723b0a-7145-4193-a316-624e28dfc76d", - "bounds": { - "x": -50, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "hidden_size", - "value": "40", - "isMandatory": true - }, - "325612cb-6b8d-481b-9235-ffeb4360d73b": { - "id": "325612cb-6b8d-481b-9235-ffeb4360d73b", - "name": "return_type = last", - "type": "ReturnTypeAttributeLSTM", - "owner": "99723b0a-7145-4193-a316-624e28dfc76d", - "bounds": { - "x": -50, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "return_type", - "value": "last", - "isMandatory": false - }, - "9ce051a3-f712-4a3f-beda-ed41d8cb77b6": { - "id": "9ce051a3-f712-4a3f-beda-ed41d8cb77b6", - "name": "input_size = 80", - "type": "InputSizeAttributeLSTM", - "owner": "99723b0a-7145-4193-a316-624e28dfc76d", - "bounds": { - "x": -50, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "input_size", - "value": "80", - "isMandatory": false - }, - "4cda0910-f668-4a55-a4af-4fbdcf417b9b": { - "id": "4cda0910-f668-4a55-a4af-4fbdcf417b9b", - "name": "dropout = 0.2", - "type": "DropoutAttributeLSTM", - "owner": "99723b0a-7145-4193-a316-624e28dfc76d", - "bounds": { - "x": -50, - "y": -310, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "dropout", - "value": "0.2", - "isMandatory": false - }, - "32376196-b191-4b63-b529-5a32882d26f5": { - "id": "32376196-b191-4b63-b529-5a32882d26f5", - "name": "batch_first = true", - "type": "BatchFirstAttributeLSTM", - "owner": "99723b0a-7145-4193-a316-624e28dfc76d", - "bounds": { - "x": -50, - "y": -310, - "width": 190, - "height": 20 + "data": { + "name": "LSTMLayer", + "attributes": { + "name": "l4", + "hidden_size": "40", + "return_type": "last", + "input_size": "80", + "dropout": "0.2", + "batch_first": "true" + } }, - "code": "", - "visibility": "public", - "attributeType": "bool", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "batch_first", - "value": "true", - "isMandatory": false + "parentId": "90295e37-f91c-4880-8924-d4d78c99d4b7" }, - "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa": { + { "id": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "90295e37-f91c-4880-8924-d4d78c99d4b7", - "bounds": { + "position": { "x": 90, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "887726cc-8d65-4178-8f83-608f02ba2e26", - "eebd0855-00a2-4cdc-8e18-e4f61cd4bc59", - "e66fdfde-9bbb-402b-bec9-27dd6b8f07c0", - "2c333e44-44b9-4645-8034-3034c134a747", - "03e66f73-a2a3-40df-9e40-cde4c4e431c0" - ], - "methods": [] - }, - "887726cc-8d65-4178-8f83-608f02ba2e26": { - "id": "887726cc-8d65-4178-8f83-608f02ba2e26", - "name": "name = l5", - "type": "NameAttributeLinear", - "owner": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", - "bounds": { - "x": 90, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l5", - "isMandatory": true - }, - "eebd0855-00a2-4cdc-8e18-e4f61cd4bc59": { - "id": "eebd0855-00a2-4cdc-8e18-e4f61cd4bc59", - "name": "out_features = 40", - "type": "OutFeaturesAttributeLinear", - "owner": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", - "bounds": { - "x": 90, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "out_features", - "value": "40", - "isMandatory": true - }, - "e66fdfde-9bbb-402b-bec9-27dd6b8f07c0": { - "id": "e66fdfde-9bbb-402b-bec9-27dd6b8f07c0", - "name": "in_features = 40", - "type": "InFeaturesAttributeLinear", - "owner": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", - "bounds": { - "x": 90, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "in_features", - "value": "40", - "isMandatory": false - }, - "2c333e44-44b9-4645-8034-3034c134a747": { - "id": "2c333e44-44b9-4645-8034-3034c134a747", - "name": "actv_func = relu", - "type": "ActvFuncAttributeLinear", - "owner": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", - "bounds": { - "x": 90, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "03e66f73-a2a3-40df-9e40-cde4c4e431c0": { - "id": "03e66f73-a2a3-40df-9e40-cde4c4e431c0", - "name": "name_module_input = l4", - "type": "NameModuleInputAttributeLinear", - "owner": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", - "bounds": { - "x": 90, - "y": -310, - "width": 240, - "height": 20 + "data": { + "name": "LinearLayer", + "attributes": { + "name": "l5", + "out_features": "40", + "in_features": "40", + "actv_func": "relu", + "name_module_input": "l4" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name_module_input", - "value": "l4", - "isMandatory": false + "parentId": "90295e37-f91c-4880-8924-d4d78c99d4b7" }, - "4582f578-1508-4643-a942-86bec6e891e6": { + { "id": "4582f578-1508-4643-a942-86bec6e891e6", - "name": "LinearLayer", "type": "LinearLayer", - "owner": "90295e37-f91c-4880-8924-d4d78c99d4b7", - "bounds": { + "position": { "x": 230, - "y": -310, + "y": -310 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "4831d6ba-3275-4b4e-8848-c7c01d392277", - "2ed8d13d-f374-45a9-a040-45731d8b5c1a", - "7613b883-5671-4b60-9482-1b25e10eab31", - "17324133-94ba-408a-bbf5-a8019d34c6a5" - ], - "methods": [] - }, - "4831d6ba-3275-4b4e-8848-c7c01d392277": { - "id": "4831d6ba-3275-4b4e-8848-c7c01d392277", - "name": "name = l6", - "type": "NameAttributeLinear", - "owner": "4582f578-1508-4643-a942-86bec6e891e6", - "bounds": { - "x": 230, - "y": -310, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "name", - "value": "l6", - "isMandatory": true - }, - "2ed8d13d-f374-45a9-a040-45731d8b5c1a": { - "id": "2ed8d13d-f374-45a9-a040-45731d8b5c1a", - "name": "out_features = 2", - "type": "OutFeaturesAttributeLinear", - "owner": "4582f578-1508-4643-a942-86bec6e891e6", - "bounds": { - "x": 230, - "y": -310, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "out_features", - "value": "2", - "isMandatory": true - }, - "7613b883-5671-4b60-9482-1b25e10eab31": { - "id": "7613b883-5671-4b60-9482-1b25e10eab31", - "name": "in_features = 40", - "type": "InFeaturesAttributeLinear", - "owner": "4582f578-1508-4643-a942-86bec6e891e6", - "bounds": { - "x": 230, - "y": -310, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "in_features", - "value": "40", - "isMandatory": false - }, - "17324133-94ba-408a-bbf5-a8019d34c6a5": { - "id": "17324133-94ba-408a-bbf5-a8019d34c6a5", - "name": "actv_func = softmax", - "type": "ActvFuncAttributeLinear", - "owner": "4582f578-1508-4643-a942-86bec6e891e6", - "bounds": { - "x": 230, - "y": -310, - "width": 200, - "height": 20 + "data": { + "name": "LinearLayer", + "attributes": { + "name": "l6", + "out_features": "2", + "in_features": "40", + "actv_func": "softmax" + } }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "actv_func", - "value": "softmax", - "isMandatory": false + "parentId": "90295e37-f91c-4880-8924-d4d78c99d4b7" }, - "185d11ea-6a90-47c0-aa52-38846c717cbe": { + { "id": "185d11ea-6a90-47c0-aa52-38846c717cbe", - "name": "Configuration", "type": "Configuration", - "owner": null, - "bounds": { + "position": { "x": -300, - "y": 40, + "y": 40 + }, + "width": 110, + "height": 110, + "measured": { "width": 110, "height": 110 }, - "attributes": [ - "53581a0a-e53f-46ea-8fea-490b2ccb41f2", - "7fe99709-fb83-4b74-9fd2-1b30638887ed", - "396296bb-f822-4ec4-8ee0-d8335d253473", - "b6b410e3-d725-40e5-b348-ba034d52cd64", - "792f60ca-823e-410e-b39c-36afd58b73d5", - "b393e978-9c22-41dd-b1ef-e8a662d18154" - ], - "methods": [] - }, - "53581a0a-e53f-46ea-8fea-490b2ccb41f2": { - "id": "53581a0a-e53f-46ea-8fea-490b2ccb41f2", - "name": "batch_size = 32", - "type": "BatchSizeAttributeConfiguration", - "owner": "185d11ea-6a90-47c0-aa52-38846c717cbe", - "bounds": { - "x": -300, - "y": 40, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "batch_size", - "value": "32", - "isMandatory": true - }, - "7fe99709-fb83-4b74-9fd2-1b30638887ed": { - "id": "7fe99709-fb83-4b74-9fd2-1b30638887ed", - "name": "epochs = 10", - "type": "EpochsAttributeConfiguration", - "owner": "185d11ea-6a90-47c0-aa52-38846c717cbe", - "bounds": { - "x": -300, - "y": 40, - "width": 160, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "epochs", - "value": "10", - "isMandatory": true - }, - "396296bb-f822-4ec4-8ee0-d8335d253473": { - "id": "396296bb-f822-4ec4-8ee0-d8335d253473", - "name": "learning_rate = 0.001", - "type": "LearningRateAttributeConfiguration", - "owner": "185d11ea-6a90-47c0-aa52-38846c717cbe", - "bounds": { - "x": -300, - "y": 40, - "width": 230, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "learning_rate", - "value": "0.001", - "isMandatory": true - }, - "b6b410e3-d725-40e5-b348-ba034d52cd64": { - "id": "b6b410e3-d725-40e5-b348-ba034d52cd64", - "name": "optimizer = adam", - "type": "OptimizerAttributeConfiguration", - "owner": "185d11ea-6a90-47c0-aa52-38846c717cbe", - "bounds": { - "x": -300, - "y": 40, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "optimizer", - "value": "adam", - "isMandatory": true - }, - "792f60ca-823e-410e-b39c-36afd58b73d5": { - "id": "792f60ca-823e-410e-b39c-36afd58b73d5", - "name": "loss_function = crossentropy", - "type": "LossFunctionAttributeConfiguration", - "owner": "185d11ea-6a90-47c0-aa52-38846c717cbe", - "bounds": { - "x": -300, - "y": 40, - "width": 270, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "loss_function", - "value": "crossentropy", - "isMandatory": true - }, - "b393e978-9c22-41dd-b1ef-e8a662d18154": { - "id": "b393e978-9c22-41dd-b1ef-e8a662d18154", - "name": "metrics = [accuracy]", - "type": "MetricsAttributeConfiguration", - "owner": "185d11ea-6a90-47c0-aa52-38846c717cbe", - "bounds": { - "x": -300, - "y": 40, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "isId": false, - "isExternalId": false, - "attributeName": "metrics", - "value": "[accuracy]", - "isMandatory": true + "data": { + "name": "Configuration", + "attributes": { + "batch_size": "32", + "epochs": "10", + "learning_rate": "0.001", + "optimizer": "adam", + "loss_function": "crossentropy", + "metrics": "[accuracy]" + } + } } - }, - "relationships": { - "42b5ccaf-67fc-4428-8baa-39882330286c": { + ], + "edges": [ + { "id": "42b5ccaf-67fc-4428-8baa-39882330286c", - "name": "next", + "source": "22978aef-63f0-4386-b7cd-3c72441570da", + "target": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", "type": "NNNext", - "owner": null, - "bounds": { - "x": -350, - "y": -265, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "22978aef-63f0-4386-b7cd-3c72441570da", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "0be6f4d2-4a34-4882-83d1-634a89ce18bc": { + { "id": "0be6f4d2-4a34-4882-83d1-634a89ce18bc", - "name": "next", + "source": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", + "target": "29f79d1a-bb72-4e16-b43c-74141ee4085d", "type": "NNNext", - "owner": null, - "bounds": { - "x": -210, - "y": -265, - "width": 20, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 20, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "230c2136-ba70-43f4-a51c-3a0fc3f9a33b", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "29f79d1a-bb72-4e16-b43c-74141ee4085d", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "4738037f-f140-4662-9257-dcf969bc1e52": { + { "id": "4738037f-f140-4662-9257-dcf969bc1e52", - "name": "next", + "source": "29f79d1a-bb72-4e16-b43c-74141ee4085d", + "target": "99723b0a-7145-4193-a316-624e28dfc76d", "type": "NNNext", - "owner": null, - "bounds": { - "x": -80, - "y": -265, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "29f79d1a-bb72-4e16-b43c-74141ee4085d", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "99723b0a-7145-4193-a316-624e28dfc76d", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "64797139-125b-477b-a24e-971feb202fec": { + { "id": "64797139-125b-477b-a24e-971feb202fec", - "name": "next", + "source": "99723b0a-7145-4193-a316-624e28dfc76d", + "target": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", "type": "NNNext", - "owner": null, - "bounds": { - "x": 60, - "y": -265, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "99723b0a-7145-4193-a316-624e28dfc76d", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "682db46c-7da9-4425-868b-31a4c4ad69da": { + { "id": "682db46c-7da9-4425-868b-31a4c4ad69da", - "name": "next", + "source": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", + "target": "4582f578-1508-4643-a942-86bec6e891e6", "type": "NNNext", - "owner": null, - "bounds": { - "x": 200, - "y": -265, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "bc8fa1c6-205d-41a5-bdd3-77ce5b45f4aa", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "4582f578-1508-4643-a942-86bec6e891e6", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "5f7691e2-bf8f-429a-bc54-f11e6ef2fc71": { + { "id": "5f7691e2-bf8f-429a-bc54-f11e6ef2fc71", - "name": "", + "source": "90295e37-f91c-4880-8924-d4d78c99d4b7", + "target": "185d11ea-6a90-47c0-aa52-38846c717cbe", "type": "NNComposition", - "owner": null, - "bounds": { - "x": -250, - "y": -180, - "width": 10, - "height": 220 - }, - "path": [ - { - "x": 5, - "y": 0 - }, - { - "x": 5, - "y": 220 - } - ], - "source": { - "direction": "Bottomleft", - "element": "90295e37-f91c-4880-8924-d4d78c99d4b7", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Up", - "element": "185d11ea-6a90-47c0-aa52-38846c717cbe", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false + "sourceHandle": "Bottomleft", + "targetHandle": "Up", + "data": { + "name": "", + "points": [] + } } + ] + }, + "lastUpdate": "2026-04-10T11:31:46.986Z" + } + ], + "UserDiagram": [ + { + "id": "8c65c53a-1961-4fac-85da-271169d789e4", + "title": "User Diagram", + "model": { + "version": "4.0.0", + "type": "UserDiagram", + "size": { + "width": 1400, + "height": 740 }, - "assessments": {} + "nodes": [], + "edges": [] + }, + "lastUpdate": "2026-04-08T10:49:34.566Z" + } + ], + "QuantumCircuitDiagram": [ + { + "id": "a5305903-0441-43cb-a268-052815a4d17e", + "title": "Quantum Circuit", + "model": { + "cols": [], + "gates": [], + "gateMetadata": {}, + "initialStates": [], + "version": "1.0.0" }, - "lastUpdate": "2026-09-11T14:35:13.353Z" + "lastUpdate": "2026-04-08T10:49:34.566Z" } ] }, "settings": { "defaultDiagramType": "ClassDiagram", "autoSave": true, - "collaborationEnabled": false, - "perspectives": { - "ClassDiagram": true, - "ObjectDiagram": true, - "StateMachineDiagram": true, - "AgentDiagram": true, - "UserDiagram": true, - "GUINoCodeDiagram": true, - "QuantumCircuitDiagram": true, - "NNDiagram": true, - "BPMN": true - } + "collaborationEnabled": false }, "currentDiagramIndices": { "ClassDiagram": 0, @@ -1267,12 +401,10 @@ "AgentDiagram": 0, "NNDiagram": 0, "UserDiagram": 0, - "GUINoCodeDiagram": 0, - "QuantumCircuitDiagram": 0, - "BPMN": 0 + "QuantumCircuitDiagram": 0 }, - "schemaVersion": 4 + "schemaVersion": 3 }, - "exportedAt": "2026-09-11T14:35:20.964Z", + "exportedAt": "2026-04-10T11:32:00.347Z", "version": "2.0.0" -} \ No newline at end of file +} diff --git a/tests/utilities/web_modeling_editor/converters/nn/fixtures/tutorial_example.json b/tests/utilities/web_modeling_editor/converters/nn/fixtures/tutorial_example.json index d2096b4d8..23d092168 100644 --- a/tests/utilities/web_modeling_editor/converters/nn/fixtures/tutorial_example.json +++ b/tests/utilities/web_modeling_editor/converters/nn/fixtures/tutorial_example.json @@ -1,1624 +1,414 @@ { - "version": "3.0.0", - "type": "NNDiagram", - "size": { - "width": 1460, - "height": 880 - }, - "interactive": { - "elements": {}, - "relationships": {} - }, - "elements": { - "6feb868b-45bf-4c44-88ab-6af624191fa9": { - "id": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "name": "Neural_Network", - "type": "NNContainer", - "owner": null, - "bounds": { - "x": -710, - "y": -420, + "title": "Neural_Network", + "model": { + "version": "4.0.0", + "type": "NNDiagram", + "size": { + "width": 1460, + "height": 880 + }, + "nodes": [ + { + "id": "6feb868b-45bf-4c44-88ab-6af624191fa9", + "type": "NNContainer", + "position": { + "x": -710, + "y": -420 + }, "width": 1150, - "height": 250 - } - }, - "dc98557d-a1e1-403d-afcb-01b318a221dd": { - "id": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "name": "Conv2DLayer", - "type": "Conv2DLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -680, - "y": -320, - "width": 110, - "height": 110 - }, - "attributes": [ - "bfae619a-284a-4f14-9e4e-a44b8f722b4f", - "b2718503-5aa2-474a-8570-b79ed1e91292", - "5643fecb-2424-45dd-a3a6-62796f49a1eb", - "02c27f2c-d012-4e73-a7cb-99f0277c436e", - "c1d9d722-8276-4ea8-93c2-719542051758" - ], - "methods": [] - }, - "bfae619a-284a-4f14-9e4e-a44b8f722b4f": { - "id": "bfae619a-284a-4f14-9e4e-a44b8f722b4f", - "name": "name = l1", - "type": "NameAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l1", - "isMandatory": true - }, - "b2718503-5aa2-474a-8570-b79ed1e91292": { - "id": "b2718503-5aa2-474a-8570-b79ed1e91292", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "5643fecb-2424-45dd-a3a6-62796f49a1eb": { - "id": "5643fecb-2424-45dd-a3a6-62796f49a1eb", - "name": "out_channels = 32", - "type": "OutChannelsAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "32", - "isMandatory": true - }, - "02c27f2c-d012-4e73-a7cb-99f0277c436e": { - "id": "02c27f2c-d012-4e73-a7cb-99f0277c436e", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "c1d9d722-8276-4ea8-93c2-719542051758": { - "id": "c1d9d722-8276-4ea8-93c2-719542051758", - "name": "in_channels = 3", - "type": "InChannelsAttributeConv2D", - "owner": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "bounds": { - "x": -680, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "3", - "isMandatory": false - }, - "a0594c44-830e-4693-a34a-fd97f81f6b85": { - "id": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "name": "PoolingLayer", - "type": "PoolingLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -540, - "y": -320, - "width": 110, - "height": 110 - }, - "attributes": [ - "4e47255c-80bd-4743-b205-0320b2fcaf12", - "b89dc1bc-4d9e-4fc8-835b-8aa7bdc43e62", - "6062815a-e7df-457a-be9e-f09e53d0ea55", - "4fffff4c-6527-4a5e-9b74-8c6d4d60e3a6" - ], - "methods": [] - }, - "4e47255c-80bd-4743-b205-0320b2fcaf12": { - "id": "4e47255c-80bd-4743-b205-0320b2fcaf12", - "name": "name = l2", - "type": "NameAttributePooling", - "owner": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "bounds": { - "x": -540, - "y": -320, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l2", - "isMandatory": true - }, - "b89dc1bc-4d9e-4fc8-835b-8aa7bdc43e62": { - "id": "b89dc1bc-4d9e-4fc8-835b-8aa7bdc43e62", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "bounds": { - "x": -540, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "6062815a-e7df-457a-be9e-f09e53d0ea55": { - "id": "6062815a-e7df-457a-be9e-f09e53d0ea55", - "name": "dimension = 2D", - "type": "DimensionAttributePooling", - "owner": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "bounds": { - "x": -540, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "dimension", - "value": "2D", - "isMandatory": true - }, - "4fffff4c-6527-4a5e-9b74-8c6d4d60e3a6": { - "id": "4fffff4c-6527-4a5e-9b74-8c6d4d60e3a6", - "name": "kernel_dim = [2, 2]", - "type": "KernelDimAttributePooling", - "owner": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "bounds": { - "x": -540, - "y": -320, - "width": 200, - "height": 20 + "height": 250, + "measured": { + "width": 1150, + "height": 250 + }, + "data": { + "name": "Neural_Network" + } }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[2, 2]", - "isMandatory": false - }, - "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39": { - "id": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "name": "Conv2DLayer", - "type": "Conv2DLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -400, - "y": -320, + { + "id": "dc98557d-a1e1-403d-afcb-01b318a221dd", + "type": "Conv2DLayer", + "position": { + "x": -680, + "y": -320 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "a8022ee0-fe59-48aa-a4c3-ca0c9d95e2f4", - "e032d54e-4e31-40fe-8905-88e98a3d6a75", - "20d2d231-1722-4347-8dfe-20eed1dc1139", - "9c88de03-7d12-4376-a565-6c72c356fda1", - "d4b2f43d-1161-483c-9736-61469a8a0df0" - ], - "methods": [] - }, - "a8022ee0-fe59-48aa-a4c3-ca0c9d95e2f4": { - "id": "a8022ee0-fe59-48aa-a4c3-ca0c9d95e2f4", - "name": "name = l3", - "type": "NameAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l3", - "isMandatory": true - }, - "e032d54e-4e31-40fe-8905-88e98a3d6a75": { - "id": "e032d54e-4e31-40fe-8905-88e98a3d6a75", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "20d2d231-1722-4347-8dfe-20eed1dc1139": { - "id": "20d2d231-1722-4347-8dfe-20eed1dc1139", - "name": "out_channels = 64", - "type": "OutChannelsAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "64", - "isMandatory": true - }, - "9c88de03-7d12-4376-a565-6c72c356fda1": { - "id": "9c88de03-7d12-4376-a565-6c72c356fda1", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "d4b2f43d-1161-483c-9736-61469a8a0df0": { - "id": "d4b2f43d-1161-483c-9736-61469a8a0df0", - "name": "in_channels = 32", - "type": "InChannelsAttributeConv2D", - "owner": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "bounds": { - "x": -400, - "y": -320, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "32", - "isMandatory": false - }, - "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5": { - "id": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "name": "PoolingLayer", - "type": "PoolingLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -260, - "y": -320, + "height": 110, + "measured": { + "width": 110, + "height": 110 + }, + "data": { + "name": "Conv2DLayer", + "attributes": { + "name": "l1", + "kernel_dim": "[3, 3]", + "out_channels": "32", + "actv_func": "relu", + "in_channels": "3" + } + }, + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" + }, + { + "id": "a0594c44-830e-4693-a34a-fd97f81f6b85", + "type": "PoolingLayer", + "position": { + "x": -540, + "y": -320 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "e32bea52-bd09-4eba-b9cb-1b143a008443", - "4fd73771-b971-44c5-a893-c827ba809ec6", - "ad125315-4a4f-4a7c-8f7f-469204499219", - "83990485-6499-4984-b8fe-4808e58e7bd8" - ], - "methods": [] - }, - "e32bea52-bd09-4eba-b9cb-1b143a008443": { - "id": "e32bea52-bd09-4eba-b9cb-1b143a008443", - "name": "name = l4", - "type": "NameAttributePooling", - "owner": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "bounds": { - "x": -260, - "y": -320, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l4", - "isMandatory": true - }, - "4fd73771-b971-44c5-a893-c827ba809ec6": { - "id": "4fd73771-b971-44c5-a893-c827ba809ec6", - "name": "pooling_type = max", - "type": "PoolingTypeAttributePooling", - "owner": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "bounds": { - "x": -260, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "pooling_type", - "value": "max", - "isMandatory": true - }, - "ad125315-4a4f-4a7c-8f7f-469204499219": { - "id": "ad125315-4a4f-4a7c-8f7f-469204499219", - "name": "dimension = 2D", - "type": "DimensionAttributePooling", - "owner": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "bounds": { - "x": -260, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "dimension", - "value": "2D", - "isMandatory": true - }, - "83990485-6499-4984-b8fe-4808e58e7bd8": { - "id": "83990485-6499-4984-b8fe-4808e58e7bd8", - "name": "kernel_dim = [2, 2]", - "type": "KernelDimAttributePooling", - "owner": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "bounds": { - "x": -260, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[2, 2]", - "isMandatory": false - }, - "b4f15221-2f2b-4876-8b79-ab7655ea7fa3": { - "id": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "name": "Conv2DLayer", - "type": "Conv2DLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": -120, - "y": -320, + "height": 110, + "measured": { + "width": 110, + "height": 110 + }, + "data": { + "name": "PoolingLayer", + "attributes": { + "name": "l2", + "pooling_type": "max", + "kernel_dim": "[2, 2]", + "pooling.dimension": "2D" + } + }, + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" + }, + { + "id": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", + "type": "Conv2DLayer", + "position": { + "x": -400, + "y": -320 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "e1e26deb-820f-4d06-8fdb-e0104dae41ec", - "49c136db-a712-4c5e-ae0c-0c7a31d09cb0", - "8632faf5-1855-46a1-aa55-915432734fe4", - "384057f0-1660-4182-b949-ec86530932c7", - "337d5cab-647f-4a0f-865e-789e925a7e0c" - ], - "methods": [] - }, - "e1e26deb-820f-4d06-8fdb-e0104dae41ec": { - "id": "e1e26deb-820f-4d06-8fdb-e0104dae41ec", - "name": "name = l5", - "type": "NameAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l5", - "isMandatory": true - }, - "49c136db-a712-4c5e-ae0c-0c7a31d09cb0": { - "id": "49c136db-a712-4c5e-ae0c-0c7a31d09cb0", - "name": "kernel_dim = [3, 3]", - "type": "KernelDimAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "kernel_dim", - "value": "[3, 3]", - "isMandatory": true - }, - "8632faf5-1855-46a1-aa55-915432734fe4": { - "id": "8632faf5-1855-46a1-aa55-915432734fe4", - "name": "out_channels = 64", - "type": "OutChannelsAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_channels", - "value": "64", - "isMandatory": true - }, - "384057f0-1660-4182-b949-ec86530932c7": { - "id": "384057f0-1660-4182-b949-ec86530932c7", - "name": "actv_func = relu", - "type": "ActvFuncAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "337d5cab-647f-4a0f-865e-789e925a7e0c": { - "id": "337d5cab-647f-4a0f-865e-789e925a7e0c", - "name": "in_channels = 64", - "type": "InChannelsAttributeConv2D", - "owner": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "bounds": { - "x": -120, - "y": -320, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_channels", - "value": "64", - "isMandatory": false - }, - "c97bc5bd-dfff-4d74-8d6d-b9bee945913c": { - "id": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", - "name": "FlattenLayer", - "type": "FlattenLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": 20, - "y": -320, + "height": 110, + "measured": { + "width": 110, + "height": 110 + }, + "data": { + "name": "Conv2DLayer", + "attributes": { + "name": "l3", + "kernel_dim": "[3, 3]", + "out_channels": "64", + "actv_func": "relu", + "in_channels": "32" + } + }, + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" + }, + { + "id": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", + "type": "PoolingLayer", + "position": { + "x": -260, + "y": -320 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "6c62667a-893f-48bd-9cdb-9c4a21bf5fed" - ], - "methods": [] - }, - "6c62667a-893f-48bd-9cdb-9c4a21bf5fed": { - "id": "6c62667a-893f-48bd-9cdb-9c4a21bf5fed", - "name": "name = l6", - "type": "NameAttributeFlatten", - "owner": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", - "bounds": { - "x": 20, - "y": -320, - "width": 210, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l6", - "isMandatory": true - }, - "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4": { - "id": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "name": "LinearLayer", - "type": "LinearLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": 160, - "y": -330, + "height": 110, + "measured": { + "width": 110, + "height": 110 + }, + "data": { + "name": "PoolingLayer", + "attributes": { + "name": "l4", + "pooling_type": "max", + "kernel_dim": "[2, 2]", + "pooling.dimension": "2D" + } + }, + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" + }, + { + "id": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", + "type": "Conv2DLayer", + "position": { + "x": -120, + "y": -320 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "9126a77d-afd8-40d1-b18b-b50e747624a0", - "bc911bfa-baa2-4c39-aeae-17d57747e317", - "797b5fcb-4688-4d0a-8536-2b32bfeb7c51", - "2bb380fd-1d08-41f4-87c4-741d167d8404" - ], - "methods": [] - }, - "9126a77d-afd8-40d1-b18b-b50e747624a0": { - "id": "9126a77d-afd8-40d1-b18b-b50e747624a0", - "name": "name = l7", - "type": "NameAttributeLinear", - "owner": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "bounds": { - "x": 160, - "y": -330, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l7", - "isMandatory": true - }, - "bc911bfa-baa2-4c39-aeae-17d57747e317": { - "id": "bc911bfa-baa2-4c39-aeae-17d57747e317", - "name": "out_features = 64", - "type": "OutFeaturesAttributeLinear", - "owner": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "bounds": { - "x": 160, - "y": -330, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_features", - "value": "64", - "isMandatory": true - }, - "797b5fcb-4688-4d0a-8536-2b32bfeb7c51": { - "id": "797b5fcb-4688-4d0a-8536-2b32bfeb7c51", - "name": "actv_func = relu", - "type": "ActvFuncAttributeLinear", - "owner": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "bounds": { - "x": 160, - "y": -330, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "actv_func", - "value": "relu", - "isMandatory": false - }, - "2bb380fd-1d08-41f4-87c4-741d167d8404": { - "id": "2bb380fd-1d08-41f4-87c4-741d167d8404", - "name": "in_features = 1024", - "type": "InFeaturesAttributeLinear", - "owner": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "bounds": { - "x": 160, - "y": -330, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_features", - "value": "1024", - "isMandatory": false - }, - "448f4122-75ed-4acb-b54a-c00a052a04b5": { - "id": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "name": "LinearLayer", - "type": "LinearLayer", - "owner": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "bounds": { - "x": 300, - "y": -330, + "height": 110, + "measured": { + "width": 110, + "height": 110 + }, + "data": { + "name": "Conv2DLayer", + "attributes": { + "name": "l5", + "kernel_dim": "[3, 3]", + "out_channels": "64", + "actv_func": "relu", + "in_channels": "64" + } + }, + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" + }, + { + "id": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", + "type": "FlattenLayer", + "position": { + "x": 20, + "y": -320 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "030354fc-6f46-48e7-9f8e-f919af96a016", - "b6e82026-c047-442e-ae8c-4c96b66f1dfa", - "3ba40354-cfc2-4710-ba55-ca8e1879b78e" - ], - "methods": [] - }, - "030354fc-6f46-48e7-9f8e-f919af96a016": { - "id": "030354fc-6f46-48e7-9f8e-f919af96a016", - "name": "name = l8", - "type": "NameAttributeLinear", - "owner": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "bounds": { - "x": 300, - "y": -330, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "l8", - "isMandatory": true - }, - "b6e82026-c047-442e-ae8c-4c96b66f1dfa": { - "id": "b6e82026-c047-442e-ae8c-4c96b66f1dfa", - "name": "out_features = 10", - "type": "OutFeaturesAttributeLinear", - "owner": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "bounds": { - "x": 300, - "y": -330, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "out_features", - "value": "10", - "isMandatory": true - }, - "3ba40354-cfc2-4710-ba55-ca8e1879b78e": { - "id": "3ba40354-cfc2-4710-ba55-ca8e1879b78e", - "name": "in_features = 64", - "type": "InFeaturesAttributeLinear", - "owner": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "bounds": { - "x": 300, - "y": -330, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "in_features", - "value": "64", - "isMandatory": false - }, - "399f908e-b3ec-4c17-ad60-f5327f1b6aa0": { - "id": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "name": "Configuration", - "type": "Configuration", - "owner": null, - "bounds": { - "x": -650, - "y": -70, + "height": 110, + "measured": { + "width": 110, + "height": 110 + }, + "data": { + "name": "FlattenLayer", + "attributes": { + "name": "l6" + } + }, + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" + }, + { + "id": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", + "type": "LinearLayer", + "position": { + "x": 160, + "y": -330 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "5cdfcd61-4afe-48f2-831e-433e8573bb6f", - "11db3162-21fb-47b5-9e13-07992157917f", - "a8ae0754-736e-46fd-8f8a-d3cefb0af682", - "f022489b-c72c-4c39-af28-4553c4caf858", - "fc2d0e02-dbce-47ee-a0f5-8a4cb6be264b", - "ee723efc-e7a9-4f34-b235-133792d1468f" - ], - "methods": [] - }, - "5cdfcd61-4afe-48f2-831e-433e8573bb6f": { - "id": "5cdfcd61-4afe-48f2-831e-433e8573bb6f", - "name": "batch_size = 32", - "type": "BatchSizeAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 170, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "batch_size", - "value": "32", - "isMandatory": true - }, - "11db3162-21fb-47b5-9e13-07992157917f": { - "id": "11db3162-21fb-47b5-9e13-07992157917f", - "name": "epochs = 10", - "type": "EpochsAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 160, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "int", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "epochs", - "value": "10", - "isMandatory": true - }, - "a8ae0754-736e-46fd-8f8a-d3cefb0af682": { - "id": "a8ae0754-736e-46fd-8f8a-d3cefb0af682", - "name": "learning_rate = 0.001", - "type": "LearningRateAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 230, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "float", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "learning_rate", - "value": "0.001", - "isMandatory": true - }, - "f022489b-c72c-4c39-af28-4553c4caf858": { - "id": "f022489b-c72c-4c39-af28-4553c4caf858", - "name": "optimizer = adam", - "type": "OptimizerAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 180, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "optimizer", - "value": "adam", - "isMandatory": true - }, - "fc2d0e02-dbce-47ee-a0f5-8a4cb6be264b": { - "id": "fc2d0e02-dbce-47ee-a0f5-8a4cb6be264b", - "name": "loss_function = crossentropy", - "type": "LossFunctionAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 260, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "loss_function", - "value": "crossentropy", - "isMandatory": true - }, - "ee723efc-e7a9-4f34-b235-133792d1468f": { - "id": "ee723efc-e7a9-4f34-b235-133792d1468f", - "name": "metrics = [f1-score]", - "type": "MetricsAttributeConfiguration", - "owner": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "bounds": { - "x": -650, - "y": -70, - "width": 280, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "metrics", - "value": "[f1-score]", - "isMandatory": true - }, - "19601d31-0821-4dde-a24b-c9059321657f": { - "id": "19601d31-0821-4dde-a24b-c9059321657f", - "name": "TrainingDataset", - "type": "TrainingDataset", - "owner": null, - "bounds": { - "x": -340, - "y": -50, + "height": 110, + "measured": { + "width": 110, + "height": 110 + }, + "data": { + "name": "LinearLayer", + "attributes": { + "name": "l7", + "out_features": "64", + "actv_func": "relu", + "in_features": "1024" + } + }, + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" + }, + { + "id": "448f4122-75ed-4acb-b54a-c00a052a04b5", + "type": "LinearLayer", + "position": { + "x": 300, + "y": -330 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "349b6bdd-c067-4865-a9a5-170f859a0311", - "a9e4a4af-c700-4b67-b51d-f1e5fca2e68a", - "e8a36a43-bde0-4a1b-b579-1f63ae18d4ed", - "5568a334-08bf-4dd5-9575-3ac26892670d", - "b9e824a0-3cd8-4c6a-9d84-ae7e311297c1", - "e813c402-0c8d-4f32-8cbb-af5eb0da0d48" - ], - "methods": [] - }, - "349b6bdd-c067-4865-a9a5-170f859a0311": { - "id": "349b6bdd-c067-4865-a9a5-170f859a0311", - "name": "name = train_data", - "type": "NameAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "train_data", - "isMandatory": true - }, - "a9e4a4af-c700-4b67-b51d-f1e5fca2e68a": { - "id": "a9e4a4af-c700-4b67-b51d-f1e5fca2e68a", - "name": "path_data = dataset/cifar10/train", - "type": "PathDataAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 290, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "path_data", - "value": "dataset/cifar10/train", - "isMandatory": true - }, - "e8a36a43-bde0-4a1b-b579-1f63ae18d4ed": { - "id": "e8a36a43-bde0-4a1b-b579-1f63ae18d4ed", - "name": "task_type = multi_class", - "type": "TaskTypeAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 230, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "task_type", - "value": "multi_class", - "isMandatory": false - }, - "5568a334-08bf-4dd5-9575-3ac26892670d": { - "id": "5568a334-08bf-4dd5-9575-3ac26892670d", - "name": "input_format = images", - "type": "InputFormatAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 220, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "input_format", - "value": "images", - "isMandatory": false - }, - "b9e824a0-3cd8-4c6a-9d84-ae7e311297c1": { - "id": "b9e824a0-3cd8-4c6a-9d84-ae7e311297c1", - "name": "shape = [32, 32, 3]", - "type": "ShapeAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 200, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "List", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "shape", - "value": "[32, 32, 3]", - "isMandatory": false - }, - "e813c402-0c8d-4f32-8cbb-af5eb0da0d48": { - "id": "e813c402-0c8d-4f32-8cbb-af5eb0da0d48", - "name": "normalize = false", - "type": "NormalizeAttributeDataset", - "owner": "19601d31-0821-4dde-a24b-c9059321657f", - "bounds": { - "x": -340, - "y": -50, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "bool", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "normalize", - "value": "false", - "isMandatory": false - }, - "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302": { - "id": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", - "name": "TestDataset", - "type": "TestDataset", - "owner": null, - "bounds": { - "x": -80, - "y": -60, + "height": 110, + "measured": { + "width": 110, + "height": 110 + }, + "data": { + "name": "LinearLayer", + "attributes": { + "name": "l8", + "out_features": "10", + "in_features": "64" + } + }, + "parentId": "6feb868b-45bf-4c44-88ab-6af624191fa9" + }, + { + "id": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", + "type": "Configuration", + "position": { + "x": -650, + "y": -70 + }, "width": 110, - "height": 110 - }, - "attributes": [ - "f192f9df-844a-4e5f-a3be-117cabad01e6", - "146be0fe-0f87-42d1-b2d0-ea5fb774b0a9" - ], - "methods": [] - }, - "f192f9df-844a-4e5f-a3be-117cabad01e6": { - "id": "f192f9df-844a-4e5f-a3be-117cabad01e6", - "name": "name = test_data", - "type": "NameAttributeDataset", - "owner": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", - "bounds": { - "x": -80, - "y": -60, - "width": 190, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "name", - "value": "test_data", - "isMandatory": true - }, - "146be0fe-0f87-42d1-b2d0-ea5fb774b0a9": { - "id": "146be0fe-0f87-42d1-b2d0-ea5fb774b0a9", - "name": "path_data = dataset/cifar10/test", - "type": "PathDataAttributeDataset", - "owner": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", - "bounds": { - "x": -80, - "y": -60, - "width": 290, - "height": 20 - }, - "code": "", - "visibility": "public", - "attributeType": "str", - "implementationType": "none", - "stateMachineId": "", - "quantumCircuitId": "", - "isOptional": false, - "isDerived": false, - "attributeName": "path_data", - "value": "dataset/cifar10/test", - "isMandatory": true - } - }, - "relationships": { - "13169dfb-19ec-41f6-9814-5c350a2845b9": { - "id": "13169dfb-19ec-41f6-9814-5c350a2845b9", - "name": "next", - "type": "NNNext", - "owner": null, - "bounds": { - "x": -570, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 + "height": 110, + "measured": { + "width": 110, + "height": 110 }, - { - "x": 30, - "y": 10 + "data": { + "name": "Configuration", + "attributes": { + "batch_size": "32", + "epochs": "10", + "learning_rate": "0.001", + "optimizer": "adam", + "loss_function": "crossentropy", + "metrics": "[f1-score]" + } } - ], - "source": { - "direction": "Right", - "element": "dc98557d-a1e1-403d-afcb-01b318a221dd", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false - }, - "bdafcfe1-e093-481a-a868-9741cea085fc": { - "id": "bdafcfe1-e093-481a-a868-9741cea085fc", - "name": "next", - "type": "NNNext", - "owner": null, - "bounds": { - "x": -430, - "y": -275, - "width": 30, - "height": 31 }, - "path": [ - { - "x": 0, - "y": 10 + { + "id": "19601d31-0821-4dde-a24b-c9059321657f", + "type": "TrainingDataset", + "position": { + "x": -340, + "y": -50 }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "a0594c44-830e-4693-a34a-fd97f81f6b85", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false - }, - "1fd2f4f5-b2a5-46b4-a3c4-968484c7eeaa": { - "id": "1fd2f4f5-b2a5-46b4-a3c4-968484c7eeaa", - "name": "next", - "type": "NNNext", - "owner": null, - "bounds": { - "x": -290, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 + "width": 110, + "height": 110, + "measured": { + "width": 110, + "height": 110 }, - { - "x": 30, - "y": 10 + "data": { + "name": "TrainingDataset", + "attributes": { + "name": "train_data", + "path_data": "dataset/cifar10/train", + "task_type": "multi_class", + "input_format": "images", + "shape": "[32, 32, 3]", + "normalize": "false" + } } - ], - "source": { - "direction": "Right", - "element": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", - "multiplicity": "", - "role": "" }, - "target": { - "direction": "Left", - "element": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false - }, - "3d84e689-b33d-477b-8a88-0a6b2564f4dd": { - "id": "3d84e689-b33d-477b-8a88-0a6b2564f4dd", - "name": "next", - "type": "NNNext", - "owner": null, - "bounds": { - "x": -150, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 + { + "id": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", + "type": "TestDataset", + "position": { + "x": -80, + "y": -60 }, - { - "x": 30, - "y": 10 - } - ], - "source": { - "direction": "Right", - "element": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false - }, - "60b782ab-f63e-44fc-b1cc-ff016dcdb47d": { - "id": "60b782ab-f63e-44fc-b1cc-ff016dcdb47d", - "name": "next", - "type": "NNNext", - "owner": null, - "bounds": { - "x": -10, - "y": -275, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 + "width": 110, + "height": 110, + "measured": { + "width": 110, + "height": 110 }, - { - "x": 30, - "y": 10 + "data": { + "name": "TestDataset", + "attributes": { + "name": "test_data", + "path_data": "dataset/cifar10/test" + } } - ], - "source": { - "direction": "Right", - "element": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false - }, - "02882625-8756-4a2d-a288-77f88020cdff": { - "id": "02882625-8756-4a2d-a288-77f88020cdff", - "name": "next", - "type": "NNNext", - "owner": null, - "bounds": { - "x": 130, - "y": -280, - "width": 30, - "height": 31 - }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 + } + ], + "edges": [ + { + "id": "13169dfb-19ec-41f6-9814-5c350a2845b9", + "source": "dc98557d-a1e1-403d-afcb-01b318a221dd", + "target": "a0594c44-830e-4693-a34a-fd97f81f6b85", + "type": "NNNext", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] } - ], - "source": { - "direction": "Right", - "element": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false - }, - "7443ee55-2a5e-44c5-a981-b401a53d2dd6": { - "id": "7443ee55-2a5e-44c5-a981-b401a53d2dd6", - "name": "next", - "type": "NNNext", - "owner": null, - "bounds": { - "x": 270, - "y": -285, - "width": 30, - "height": 31 }, - "path": [ - { - "x": 0, - "y": 10 - }, - { - "x": 30, - "y": 10 + { + "id": "bdafcfe1-e093-481a-a868-9741cea085fc", + "source": "a0594c44-830e-4693-a34a-fd97f81f6b85", + "target": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", + "type": "NNNext", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] } - ], - "source": { - "direction": "Right", - "element": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", - "multiplicity": "", - "role": "" - }, - "target": { - "direction": "Left", - "element": "448f4122-75ed-4acb-b54a-c00a052a04b5", - "multiplicity": "", - "role": "" }, - "isManuallyLayouted": false - }, - "1c81e414-f791-4bb2-bfe5-ada765894730": { - "id": "1c81e414-f791-4bb2-bfe5-ada765894730", - "name": "", - "type": "NNComposition", - "owner": null, - "bounds": { - "x": -600, - "y": -170, - "width": 10, - "height": 100 - }, - "path": [ - { - "x": 5, - "y": 100 - }, - { - "x": 5, - "y": 0 + { + "id": "1fd2f4f5-b2a5-46b4-a3c4-968484c7eeaa", + "source": "28142ef8-9d9a-4b5b-b0bb-bf8338f7da39", + "target": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", + "type": "NNNext", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] } - ], - "source": { - "direction": "Up", - "element": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", - "multiplicity": "", - "role": "" }, - "target": { - "direction": "Bottomleft", - "element": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "multiplicity": "", - "role": "" - }, - "isManuallyLayouted": false - }, - "4d85f21f-a198-4249-a510-aed3fcf10ba6": { - "id": "4d85f21f-a198-4249-a510-aed3fcf10ba6", - "name": "", - "type": "NNAssociation", - "owner": null, - "bounds": { - "x": -290, - "y": -170, - "width": 10, - "height": 120 + { + "id": "3d84e689-b33d-477b-8a88-0a6b2564f4dd", + "source": "b2215ce8-2b0c-4cc4-97ba-0957480c2ce5", + "target": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", + "type": "NNNext", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "path": [ - { - "x": 5, - "y": 120 - }, - { - "x": 5, - "y": 0 + { + "id": "60b782ab-f63e-44fc-b1cc-ff016dcdb47d", + "source": "b4f15221-2f2b-4876-8b79-ab7655ea7fa3", + "target": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", + "type": "NNNext", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] } - ], - "source": { - "direction": "Up", - "element": "19601d31-0821-4dde-a24b-c9059321657f", - "multiplicity": "", - "role": "" }, - "target": { - "direction": "Down", - "element": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "multiplicity": "", - "role": "" + { + "id": "02882625-8756-4a2d-a288-77f88020cdff", + "source": "c97bc5bd-dfff-4d74-8d6d-b9bee945913c", + "target": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", + "type": "NNNext", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "isManuallyLayouted": false - }, - "f6329bdf-b5e3-4f39-b9bf-ecd1e6c132e8": { - "id": "f6329bdf-b5e3-4f39-b9bf-ecd1e6c132e8", - "name": "", - "type": "NNAssociation", - "owner": null, - "bounds": { - "x": -30, - "y": -170, - "width": 10, - "height": 110 + { + "id": "7443ee55-2a5e-44c5-a981-b401a53d2dd6", + "source": "726c2fc0-6ca9-49e5-8a83-2bd6c818ddf4", + "target": "448f4122-75ed-4acb-b54a-c00a052a04b5", + "type": "NNNext", + "sourceHandle": "Right", + "targetHandle": "Left", + "data": { + "name": "next", + "points": [] + } }, - "path": [ - { - "x": 5, - "y": 110 - }, - { - "x": 5, - "y": 0 + { + "id": "1c81e414-f791-4bb2-bfe5-ada765894730", + "source": "399f908e-b3ec-4c17-ad60-f5327f1b6aa0", + "target": "6feb868b-45bf-4c44-88ab-6af624191fa9", + "type": "NNComposition", + "sourceHandle": "Up", + "targetHandle": "Bottomleft", + "data": { + "name": "", + "points": [] } - ], - "source": { - "direction": "Up", - "element": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", - "multiplicity": "", - "role": "" }, - "target": { - "direction": "Down", - "element": "6feb868b-45bf-4c44-88ab-6af624191fa9", - "multiplicity": "", - "role": "" + { + "id": "4d85f21f-a198-4249-a510-aed3fcf10ba6", + "source": "19601d31-0821-4dde-a24b-c9059321657f", + "target": "6feb868b-45bf-4c44-88ab-6af624191fa9", + "type": "NNAssociation", + "sourceHandle": "Up", + "targetHandle": "Down", + "data": { + "name": "", + "points": [] + } }, - "isManuallyLayouted": false - } - }, - "assessments": {} -} \ No newline at end of file + { + "id": "f6329bdf-b5e3-4f39-b9bf-ecd1e6c132e8", + "source": "ae8a9f8f-5ab5-4193-b12c-e74dd1b23302", + "target": "6feb868b-45bf-4c44-88ab-6af624191fa9", + "type": "NNAssociation", + "sourceHandle": "Up", + "targetHandle": "Down", + "data": { + "name": "", + "points": [] + } + } + ] + } +} diff --git a/tests/utilities/web_modeling_editor/converters/nn/test_nn_container_layout.py b/tests/utilities/web_modeling_editor/converters/nn/test_nn_container_layout.py new file mode 100644 index 000000000..ec515fbba --- /dev/null +++ b/tests/utilities/web_modeling_editor/converters/nn/test_nn_container_layout.py @@ -0,0 +1,45 @@ +"""A B-UML NN imported into the editor draws its layers inside their container. + +v4 child positions are relative to the parent (``parentId``). Development +placed each module inside its container, side by side; the v4 port passed the +absolute coordinates as offsets, so the layers landed outside and overlapped. +""" + +from besser.BUML.metamodel.nn import NN, FlattenLayer, LinearLayer +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.nn_diagram_converter import ( + nn_model_to_json, +) + + +def _model(): + sub = NN(name="sub") + sub.add_layer(LinearLayer(name="l0", in_features=8, out_features=4)) + nn = NN(name="main") + nn.add_layer(FlattenLayer(name="f")) + nn.add_sub_nn(sub) + nn.add_layer(LinearLayer(name="l1", in_features=4, out_features=2)) + return nn + + +def _box(node): + return node["position"]["x"], node["position"]["y"], node["width"], node["height"] + + +def test_layers_lie_inside_their_container_without_overlapping(): + nodes = {n["id"]: n for n in nn_model_to_json(_model())["nodes"]} + children = {} + for node in nodes.values(): + if node.get("parentId"): + children.setdefault(node["parentId"], []).append(node) + assert children, "no layer is nested in a container" + + for parent_id, kids in children.items(): + _, _, parent_w, parent_h = _box(nodes[parent_id]) + for kid in kids: + x, y, w, h = _box(kid) + assert 0 <= x and x + w <= parent_w and 0 <= y and y + h <= parent_h, ( + f"{kid['data'].get('name')} at {(x, y, w, h)} is outside its {parent_w}x{parent_h} container" + ) + boxes = sorted(_box(k) for k in kids) + for (x1, _, w1, _), (x2, _, _, _) in zip(boxes, boxes[1:]): + assert x1 + w1 <= x2, "sibling layers overlap" diff --git a/tests/utilities/web_modeling_editor/converters/nn/test_nn_diagram_processor.py b/tests/utilities/web_modeling_editor/converters/nn/test_nn_diagram_processor.py index c2eb256b5..62fdac553 100644 --- a/tests/utilities/web_modeling_editor/converters/nn/test_nn_diagram_processor.py +++ b/tests/utilities/web_modeling_editor/converters/nn/test_nn_diagram_processor.py @@ -318,44 +318,38 @@ def test_tutorial_test_dataset(): # Error-case tests for dataset parsing # --------------------------------------------------------------------------- -def _dataset_element(attrs): - """Build a minimal TrainingDataset element + attribute children dict.""" - elements = {} - attr_ids = [] - for field, value in attrs.items(): - aid = f"attr_{field}" - elements[aid] = {"attributeName": field, "value": value} - attr_ids.append(aid) - elements["ds1"] = {"type": "TrainingDataset", "attributes": attr_ids} - return elements["ds1"], elements +def _dataset_node(attrs): + """Build a minimal v4 TrainingDataset node with the given attrs dict.""" + return { + "id": "ds1", "type": "TrainingDataset", + "position": {"x": 0, "y": 0}, "width": 100, "height": 100, + "measured": {"width": 100, "height": 100}, + "data": {"name": "TrainingDataset", "attributes": dict(attrs)}, + } def test_dataset_missing_name_raises(): """create_dataset raises ValueError when name attribute is missing.""" - element, elements = _dataset_element({"path_data": "/data"}) with pytest.raises(ValueError, match="name"): - create_dataset(element, elements) + create_dataset(_dataset_node({"path_data": "/data"})) def test_dataset_empty_name_raises(): """create_dataset raises ValueError when name is empty string.""" - element, elements = _dataset_element({"name": "", "path_data": "/data"}) with pytest.raises(ValueError, match="name"): - create_dataset(element, elements) + create_dataset(_dataset_node({"name": "", "path_data": "/data"})) def test_dataset_missing_path_data_raises(): """create_dataset raises ValueError when path_data is missing.""" - element, elements = _dataset_element({"name": "train"}) with pytest.raises(ValueError, match="path_data"): - create_dataset(element, elements) + create_dataset(_dataset_node({"name": "train"})) def test_dataset_empty_path_data_raises(): """create_dataset raises ValueError when path_data is empty string.""" - element, elements = _dataset_element({"name": "train", "path_data": ""}) with pytest.raises(ValueError, match="path_data"): - create_dataset(element, elements) + create_dataset(_dataset_node({"name": "train", "path_data": ""})) def test_dataset_invalid_shape_raises(): @@ -364,30 +358,27 @@ def test_dataset_invalid_shape_raises(): Silently falling back to a default hid user-entry mistakes; the processor now surfaces them so the editor can show a validation error. """ - element, elements = _dataset_element({ - "name": "train", "path_data": "/d", - "input_format": "images", "shape": "not-a-list", - }) with pytest.raises(ValueError, match="malformed 'shape'"): - create_dataset(element, elements) + create_dataset(_dataset_node({ + "name": "train", "path_data": "/d", + "input_format": "images", "shape": "not-a-list", + })) def test_dataset_default_shape_when_empty(): """Empty/missing shape still falls back to [256, 256] (unchanged).""" - element, elements = _dataset_element({ + ds = create_dataset(_dataset_node({ "name": "train", "path_data": "/d", "input_format": "images", "shape": "", - }) - ds = create_dataset(element, elements) + })) assert ds.image.shape == [256, 256] def test_dataset_without_input_format_has_no_image(): """Dataset with no input_format (or non-images) has no image attached.""" - element, elements = _dataset_element({ + ds = create_dataset(_dataset_node({ "name": "train", "path_data": "/d", "input_format": "csv", - }) - ds = create_dataset(element, elements) + })) assert ds.image is None @@ -395,35 +386,44 @@ def test_dataset_without_input_format_has_no_image(): # Regression tests for PR review fixes # --------------------------------------------------------------------------- -def _minimal_container_json(extra_elements=None, extra_relationships=None): - """Build a minimal NNDiagram JSON with one container + one Linear layer.""" - elements = { - "c1": { - "id": "c1", "type": "NNContainer", "name": "Net", "owner": None, - "bounds": {"x": 0, "y": 0, "width": 200, "height": 100}, - }, - "l1": { - "id": "l1", "type": "LinearLayer", "name": "LinearLayer", "owner": "c1", - "bounds": {"x": 0, "y": 0, "width": 100, "height": 100}, - "attributes": ["l1a1", "l1a2"], "methods": [], - }, - "l1a1": { - "id": "l1a1", "type": "NameAttributeLinear", - "attributeName": "name", "value": "lin", "owner": "l1", - }, - "l1a2": { - "id": "l1a2", "type": "OutFeaturesAttributeLinear", - "attributeName": "out_features", "value": "10", "owner": "l1", - }, +def _layer_node(node_id, layer_type, parent_id, *, attributes, x=0, y=0): + """Build a v4 layer node owned by ``parent_id`` with the given attributes dict.""" + return { + "id": node_id, "type": layer_type, "parentId": parent_id, + "position": {"x": x, "y": y}, + "width": 100, "height": 100, + "measured": {"width": 100, "height": 100}, + "data": {"name": attributes.get("name", layer_type), + "attributes": dict(attributes)}, } - if extra_elements: - elements.update(extra_elements) + + +def _container_node(node_id, name, *, x=0, y=0, w=200, h=100): + return { + "id": node_id, "type": "NNContainer", + "position": {"x": x, "y": y}, + "width": w, "height": h, + "measured": {"width": w, "height": h}, + "data": {"name": name}, + } + + +def _minimal_container_json(extra_nodes=None, extra_edges=None): + """Build a minimal v4 NNDiagram with one container + one Linear layer.""" + nodes = [ + _container_node("c1", "Net"), + _layer_node("l1", "LinearLayer", "c1", + attributes={"name": "lin", "out_features": "10"}), + ] + if extra_nodes: + nodes.extend(extra_nodes) return { "title": "Net", "model": { + "version": "4.0.0", "type": "NNDiagram", - "elements": elements, - "relationships": extra_relationships or {}, + "nodes": nodes, + "edges": list(extra_edges or []), }, } @@ -453,144 +453,124 @@ def test_project_format_empty_list_raises(): def test_unresolved_nnreference_raises(): """An NNReference pointing to a missing container must raise (regression for review #3).""" - extra = { - "ref1": { - "id": "ref1", "type": "NNReference", "name": "ghost", - "referencedNN": "ghost", "owner": "c1", - "bounds": {"x": 0, "y": 0, "width": 100, "height": 100}, + extra_nodes = [ + { + "id": "ref1", "type": "NNReference", "parentId": "c1", + "position": {"x": 0, "y": 0}, "width": 100, "height": 100, + "measured": {"width": 100, "height": 100}, + "data": {"name": "ghost", "referenceTarget": "ghost"}, }, - } + ] # Connect l1 -> ref1 so the connectivity check passes and the unresolved-ref # check is the next failure mode. - rels = { - "rel1": { - "id": "rel1", "type": "NNNext", - "source": {"element": "l1"}, "target": {"element": "ref1"}, + extra_edges = [ + { + "id": "rel1", "source": "l1", "target": "ref1", + "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}, }, - } - diagram = _minimal_container_json(extra_elements=extra, extra_relationships=rels) + ] + diagram = _minimal_container_json(extra_nodes=extra_nodes, extra_edges=extra_edges) with pytest.raises(ValueError, match="NNReference 'ghost'"): process_nn_diagram(diagram) def test_nnnext_cycle_raises(): """A cycle in NNNext relationships must raise (regression for review #6).""" - extra = { - "l2": { - "id": "l2", "type": "LinearLayer", "name": "LinearLayer", "owner": "c1", - "bounds": {"x": 0, "y": 0, "width": 100, "height": 100}, - "attributes": ["l2a1", "l2a2"], "methods": [], - }, - "l2a1": { - "id": "l2a1", "type": "NameAttributeLinear", - "attributeName": "name", "value": "lin2", "owner": "l2", - }, - "l2a2": { - "id": "l2a2", "type": "OutFeaturesAttributeLinear", - "attributeName": "out_features", "value": "5", "owner": "l2", - }, - } - rels = { - "r1": {"id": "r1", "type": "NNNext", "source": {"element": "l1"}, "target": {"element": "l2"}, "name": "next"}, - "r2": {"id": "r2", "type": "NNNext", "source": {"element": "l2"}, "target": {"element": "l1"}, "name": "next"}, - } - diagram = _minimal_container_json(extra_elements=extra, extra_relationships=rels) + extra_nodes = [ + _layer_node("l2", "LinearLayer", "c1", + attributes={"name": "lin2", "out_features": "5"}), + ] + extra_edges = [ + {"id": "r1", "source": "l1", "target": "l2", "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}}, + {"id": "r2", "source": "l2", "target": "l1", "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}}, + ] + diagram = _minimal_container_json(extra_nodes=extra_nodes, extra_edges=extra_edges) with pytest.raises(ValueError, match="cycle"): process_nn_diagram(diagram) def test_disconnected_modules_raise(): """Two layers in the same container with no NNNext between them must raise.""" - extra = { - "l2": { - "id": "l2", "type": "LinearLayer", "name": "LinearLayer", "owner": "c1", - "bounds": {"x": 0, "y": 0, "width": 100, "height": 100}, - "attributes": ["l2a1", "l2a2"], "methods": [], - }, - "l2a1": { - "id": "l2a1", "type": "NameAttributeLinear", - "attributeName": "name", "value": "lin2", "owner": "l2", - }, - "l2a2": { - "id": "l2a2", "type": "OutFeaturesAttributeLinear", - "attributeName": "out_features", "value": "5", "owner": "l2", - }, - } - diagram = _minimal_container_json(extra_elements=extra) + extra_nodes = [ + _layer_node("l2", "LinearLayer", "c1", + attributes={"name": "lin2", "out_features": "5"}), + ] + diagram = _minimal_container_json(extra_nodes=extra_nodes) with pytest.raises(ValueError, match="no incoming NNNext edge"): process_nn_diagram(diagram) def test_connected_modules_pass(): """Two layers connected via NNNext must not trigger the connectivity check.""" - extra = { - "l2": { - "id": "l2", "type": "LinearLayer", "name": "LinearLayer", "owner": "c1", - "bounds": {"x": 0, "y": 0, "width": 100, "height": 100}, - "attributes": ["l2a1", "l2a2"], "methods": [], - }, - "l2a1": { - "id": "l2a1", "type": "NameAttributeLinear", - "attributeName": "name", "value": "lin2", "owner": "l2", - }, - "l2a2": { - "id": "l2a2", "type": "OutFeaturesAttributeLinear", - "attributeName": "out_features", "value": "5", "owner": "l2", - }, - } - rels = { - "r1": {"id": "r1", "type": "NNNext", - "source": {"element": "l1"}, "target": {"element": "l2"}}, - } - diagram = _minimal_container_json(extra_elements=extra, extra_relationships=rels) + extra_nodes = [ + _layer_node("l2", "LinearLayer", "c1", + attributes={"name": "lin2", "out_features": "5"}), + ] + extra_edges = [ + {"id": "r1", "source": "l1", "target": "l2", "type": "NNNext", + "sourceHandle": "Right", "targetHandle": "Left", + "data": {"name": "next", "points": []}}, + ] + diagram = _minimal_container_json(extra_nodes=extra_nodes, extra_edges=extra_edges) nn = process_nn_diagram(diagram) assert len(nn.modules) == 2 def test_multiple_training_datasets_raises(): """Two TrainingDataset elements must raise rather than silently overwrite (review #8).""" - extra = { - "ds1": {"id": "ds1", "type": "TrainingDataset", "owner": None, "attributes": ["ds1a1", "ds1a2"]}, - "ds1a1": {"id": "ds1a1", "attributeName": "name", "value": "t1", "owner": "ds1"}, - "ds1a2": {"id": "ds1a2", "attributeName": "path_data", "value": "/a", "owner": "ds1"}, - "ds2": {"id": "ds2", "type": "TrainingDataset", "owner": None, "attributes": ["ds2a1", "ds2a2"]}, - "ds2a1": {"id": "ds2a1", "attributeName": "name", "value": "t2", "owner": "ds2"}, - "ds2a2": {"id": "ds2a2", "attributeName": "path_data", "value": "/b", "owner": "ds2"}, - } - diagram = _minimal_container_json(extra_elements=extra) + extra_nodes = [ + { + "id": "ds1", "type": "TrainingDataset", + "position": {"x": 0, "y": 200}, "width": 100, "height": 100, + "measured": {"width": 100, "height": 100}, + "data": {"name": "TrainingDataset", + "attributes": {"name": "t1", "path_data": "/a"}}, + }, + { + "id": "ds2", "type": "TrainingDataset", + "position": {"x": 200, "y": 200}, "width": 100, "height": 100, + "measured": {"width": 100, "height": 100}, + "data": {"name": "TrainingDataset", + "attributes": {"name": "t2", "path_data": "/b"}}, + }, + ] + diagram = _minimal_container_json(extra_nodes=extra_nodes) with pytest.raises(ValueError, match="TrainingDataset"): process_nn_diagram(diagram) def test_multiple_top_level_containers_raises(): """Two NNContainers that aren't referenced by each other must raise (review #19).""" - extra = { - "c2": { - "id": "c2", "type": "NNContainer", "name": "Other", "owner": None, - "bounds": {"x": 400, "y": 0, "width": 200, "height": 100}, - }, - } - diagram = _minimal_container_json(extra_elements=extra) + extra_nodes = [_container_node("c2", "Other", x=400)] + diagram = _minimal_container_json(extra_nodes=extra_nodes) with pytest.raises(ValueError, match="top-level NNContainers"): process_nn_diagram(diagram) def test_attribute_prefix_match_no_collision(): - """'NameAttribute' must not match 'NameModuleInputAttributeX' (review #5).""" + """'NameAttribute' must not match 'NameModuleInputAttributeX' (review #5). + + The v4 form looks up keys in ``data.attributes`` by name (no prefix + matching), so providing the longer ``name_module_input`` key must not + surface as ``name``. + """ from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( get_element_attribute, ) - # Intentionally only provide NameModuleInput (a longer-prefix attribute); - # the shorter 'NameAttribute' key must NOT mistake it for a match. - element = {"attributes": ["a1"]} - elements = { - "a1": { - "id": "a1", "type": "NameModuleInputAttributeConv2D", - "attributeName": "name_module_input", "value": "prev_layer", + node = { + "id": "L", "type": "Conv2DLayer", + "data": { + "name": "c1", + "attributes": {"name_module_input": "prev_layer"}, }, } - assert get_element_attribute(element, 'NameAttribute', elements) is None - assert ( - get_element_attribute(element, 'NameModuleInputAttribute', elements) - == 'prev_layer' - ) + # 'NameAttribute' should not match 'name_module_input'. + assert get_element_attribute(node, "NameAttribute") is None + # The longer key resolves to its value. + assert get_element_attribute(node, "NameModuleInputAttribute") == "prev_layer" diff --git a/tests/utilities/web_modeling_editor/converters/nn/test_nn_templates.py b/tests/utilities/web_modeling_editor/converters/nn/test_nn_templates.py index 090d35282..550dd862c 100644 --- a/tests/utilities/web_modeling_editor/converters/nn/test_nn_templates.py +++ b/tests/utilities/web_modeling_editor/converters/nn/test_nn_templates.py @@ -51,27 +51,29 @@ class TestNNTemplates: @staticmethod def _wrap(template_model: dict) -> dict: """process_nn_diagram expects the outer diagram wrapper, templates - are the flat UMLModel — wrap to match the editor payload shape.""" + are the flat v4 model — wrap to match the editor payload shape.""" return { "title": template_model.get("type", "NNDiagram"), "model": template_model, } def test_template_is_flat_umlmodel(self, template_path: Path): - """Every NN template is a flat UMLModel (no ``project`` wrapper). + """Every NN template is a flat v4 model (no ``project`` wrapper). A regression that re-introduces the wrapped-project format would - make the template load as an empty canvas in the editor — this - test locks in the fix from iteration 1. + make the template load as an empty canvas in the editor. """ model = json.loads(template_path.read_text(encoding="utf-8")) assert model.get("type") == "NNDiagram", ( f"{template_path.name} must have top-level type=NNDiagram, got {model.get('type')!r}" ) - assert "elements" in model, f"{template_path.name} missing 'elements'" - assert "relationships" in model, f"{template_path.name} missing 'relationships'" + assert model.get("version", "").startswith("4."), ( + f"{template_path.name} must be a v4 model, got version {model.get('version')!r}" + ) + assert isinstance(model.get("nodes"), list), f"{template_path.name} missing 'nodes'" + assert isinstance(model.get("edges"), list), f"{template_path.name} missing 'edges'" assert "project" not in model, ( - f"{template_path.name} is a wrapped-project export — templates must be flat UMLModel" + f"{template_path.name} is a wrapped-project export — templates must be a flat model" ) def test_template_parses_via_process_nn_diagram(self, template_path: Path): @@ -88,9 +90,9 @@ def test_template_roundtrips_through_converter(self, template_path: Path): nn = process_nn_diagram(self._wrap(model)) out = nn_model_to_json(nn) assert out["type"] == "NNDiagram" - assert out["version"] == "3.0.0" - assert isinstance(out.get("elements"), dict) - assert isinstance(out.get("relationships"), dict) + assert out["version"] == "4.0.0" + assert isinstance(out.get("nodes"), list) + assert isinstance(out.get("edges"), list) @pytest.mark.skipif( diff --git a/tests/utilities/web_modeling_editor/converters/nn/test_nn_v4_extended_attributes.py b/tests/utilities/web_modeling_editor/converters/nn/test_nn_v4_extended_attributes.py new file mode 100644 index 000000000..67c8d2898 --- /dev/null +++ b/tests/utilities/web_modeling_editor/converters/nn/test_nn_v4_extended_attributes.py @@ -0,0 +1,198 @@ +"""v4 wire-shape coverage for the extended NN attributes. + +Layers gained ``bias`` / ``dilation`` / ``groups`` / ``is_layer_call`` / +``input_var`` / ``output_var`` (plus per-kind extras such as ``eps``, +``affine``, ``hx_source``), TensorOps gained the reduce / split / pad / +interpolate / subscript / dropout families, and the NN container carries its +forward signature (``input_var`` / ``return_vars``). In v4 every layer +attribute lives on ``node.data.attributes`` and the container signature on +``node.data``; these tests pin both directions of the converter pair. +""" + +import json + +from besser.BUML.metamodel.nn import ( + NN, + BatchNormLayer, + Conv2D, + LSTMLayer, + TensorOp, +) +from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.nn_diagram_converter import ( + nn_model_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.json_to_buml.nn_diagram_processor import ( + process_nn_diagram, +) + + +def _node(node_id, node_type, attributes, parent_id="c1"): + return { + "id": node_id, + "type": node_type, + "position": {"x": 0, "y": 0}, + "width": 110, + "height": 110, + "parentId": parent_id, + "data": {"name": attributes.get("name", node_type), "attributes": attributes}, + } + + +def _next(edge_id, source, target): + return {"id": edge_id, "type": "NNNext", "source": source, "target": target, + "data": {"name": "next", "points": []}} + + +def _diagram(nodes, edges, container_data=None): + container = { + "id": "c1", "type": "NNContainer", "position": {"x": 0, "y": 0}, + "width": 800, "height": 200, + "data": {"name": "net", **(container_data or {})}, + } + return {"title": "net", "model": {"version": "4.0.0", "type": "NNDiagram", + "nodes": [container, *nodes], "edges": edges}} + + +def _layers_by_name(nn): + return {m.name: m for m in nn.modules} + + +def test_layer_extended_attributes_are_read_from_data_attributes(): + nodes = [ + _node("n1", "Conv2DLayer", { + "name": "conv", "kernel_dim": "[3, 3]", "out_channels": "8", + "dilation": "[2, 2]", "groups": "1", "bias": "false", + "is_layer_call": "true", "output_var": "feat", + }), + _node("n2", "LSTMLayer", { + "name": "rnn", "hidden_size": "16", "bias": "false", + "hx_source": "feat", "hidden_state_var": "h", "cell_state_var": "c", + "cell_unused": "true", "input_var": "feat", "output_var": "seq", + }), + _node("n3", "BatchNormalizationLayer", { + "name": "bn", "num_features": "16", + "batch_normalization.dimension": "1D", "eps": "0.001", + "momentum": "0.2", "affine": "false", "track_running_stats": "false", + "input_var": "seq", + }), + ] + nn = process_nn_diagram(_diagram(nodes, [_next("e1", "n1", "n2"), _next("e2", "n2", "n3")])) + layers = _layers_by_name(nn) + + conv = layers["conv"] + assert conv.dilation == [2, 2] + assert conv.bias is False + assert conv.is_layer_call is True + assert conv.output_var == "feat" + + lstm = layers["rnn"] + assert lstm.bias is False + assert lstm.hx_source == "feat" + assert lstm.hidden_state_var == "h" + assert lstm.cell_state_var == "c" + assert lstm.cell_unused is True + assert lstm.input_var == "feat" + + bn = layers["bn"] + assert bn.dimension == "1D" + assert bn.eps == 0.001 + assert bn.momentum == 0.2 + assert bn.affine is False + assert bn.track_running_stats is False + + +def test_container_signature_is_read_from_container_data(): + nodes = [_node("n1", "LinearLayer", {"name": "fc", "out_features": "4"})] + # return_vars accepted both as the list the backend emits and as the + # comma-separated string a user may have typed. + for return_vars in (["y", "z"], "y, z"): + nn = process_nn_diagram(_diagram( + nodes, [], container_data={"input_var": "x", "return_vars": return_vars}, + )) + assert nn.input_var == "x" + assert nn.return_vars == "y, z" + + +def test_reference_target_resolves_container_id(): + """The editor stores the referenced container's node id in ``referenceTarget``.""" + sub = {"id": "sub", "type": "NNContainer", "position": {"x": 0, "y": 0}, + "data": {"name": "encoder"}} + sub_layer = _node("s1", "LinearLayer", {"name": "enc_fc", "out_features": "4"}, parent_id="sub") + ref = {"id": "r1", "type": "NNReference", "parentId": "c1", "position": {"x": 0, "y": 0}, + "data": {"name": "encoder", "referenceTarget": "sub"}} + head = _node("n1", "LinearLayer", {"name": "head", "out_features": "2"}) + payload = _diagram([sub, sub_layer, ref, head], [_next("e1", "r1", "n1")]) + nn = process_nn_diagram(payload) + assert [m.name for m in nn.modules] == ["encoder", "head"] + assert nn.sub_nns[0].name == "encoder" + + +def test_tensor_op_extended_families(): + nodes = [ + _node("n1", "LinearLayer", {"name": "fc", "out_features": "4"}), + _node("n2", "TensorOp", { + "name": "chunks", "tns_type": "split", "split_dim": "1", + "split_sizes": "2", "output_vars": "[a, b]", "input_var": "x", + }), + _node("n3", "TensorOp", { + "name": "padded", "tns_type": "pad", "pad_amount": "[[1, 1], [2, 2]]", + "pad_mode": "constant", "pad_value": "0.5", "input_var": "a", + }), + _node("n4", "TensorOp", { + "name": "picked", "tns_type": "subscript", + "subscript_indices": json.dumps([{"type": "index", "value": 0}, + {"type": "slice", "start": 1}]), + "layers_of_tensors": "['padded']", + }), + _node("n5", "TensorOp", { + "name": "summed", "tns_type": "binop_add", + "layers_of_tensors": "['picked', 1.5]", + }), + ] + edges = [_next("e1", "n1", "n2"), _next("e2", "n2", "n3"), + _next("e3", "n3", "n4"), _next("e4", "n4", "n5")] + nn = process_nn_diagram(_diagram(nodes, edges)) + ops = _layers_by_name(nn) + assert ops["chunks"].split_dim == 1 + assert ops["chunks"].split_sizes == 2 + assert ops["chunks"].output_vars == ["a", "b"] + assert ops["padded"].pad_amount == [[1, 1], [2, 2]] + assert ops["padded"].pad_value == 0.5 + assert ops["picked"].subscript_indices[0] == {"type": "index", "value": 0} + assert ops["summed"].layers_of_tensors == ["picked", 1.5] + + +def test_extended_attributes_round_trip_through_v4(): + nn = NN(name="net", input_var="x", return_vars="out, h") + nn.add_layer(Conv2D(name="conv", kernel_dim=[3, 3], out_channels=8, + dilation=[2, 2], bias=False, output_var="feat")) + nn.add_layer(LSTMLayer(name="rnn", hidden_size=16, hx_source="feat", + input_var="feat", output_var="out", hidden_state_var="h")) + nn.add_layer(BatchNormLayer(name="bn", num_features=16, dimension="1D", + eps=0.001, input_var="out")) + nn.add_tensor_op(TensorOp(name="flat", tns_type="reshape", reshape_dim=[-1], + input_var="out")) + + model = nn_model_to_json(nn) + assert model["version"] == "4.0.0" + container = next(n for n in model["nodes"] if n["type"] == "NNContainer") + assert container["data"]["input_var"] == "x" + assert container["data"]["return_vars"] == ["out", "h"] + conv_attrs = next(n for n in model["nodes"] if n["type"] == "Conv2DLayer")["data"]["attributes"] + assert conv_attrs["dilation"] == "[2, 2]" + assert conv_attrs["bias"] == "false" + assert conv_attrs["output_var"] == "feat" + bn_attrs = next(n for n in model["nodes"] if n["type"] == "BatchNormalizationLayer")["data"]["attributes"] + assert bn_attrs["batch_normalization.dimension"] == "1D" + assert bn_attrs["eps"] == "0.001" + + back = process_nn_diagram({"title": "net", "model": model}) + assert back.input_var == "x" + assert back.return_vars == "out, h" + layers = _layers_by_name(back) + assert layers["conv"].dilation == [2, 2] + assert layers["conv"].bias is False + assert layers["rnn"].hx_source == "feat" + assert layers["rnn"].hidden_state_var == "h" + assert layers["bn"].eps == 0.001 + assert layers["flat"].input_var == "out" diff --git a/tests/utilities/web_modeling_editor/converters/test_method_return_type.py b/tests/utilities/web_modeling_editor/converters/test_method_return_type.py index 2a3399287..8121c24f6 100644 --- a/tests/utilities/web_modeling_editor/converters/test_method_return_type.py +++ b/tests/utilities/web_modeling_editor/converters/test_method_return_type.py @@ -22,15 +22,19 @@ def _diagram(method: dict) -> dict: + """A v4 class diagram with one ``Loan`` class holding the given method row.""" return { "title": "T", "model": { - "elements": { - "c1": {"id": "c1", "type": "Class", "name": "Loan", - "attributes": [], "methods": ["m1"]}, - "m1": {"id": "m1", "type": "ClassMethod", **method}, - }, - "relationships": {}, + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + {"id": "c1", "type": "class", + "position": {"x": 0, "y": 0}, "width": 160, "height": 100, + "data": {"name": "Loan", "stereotype": None, "attributes": [], + "methods": [{"id": "m1", **method}]}}, + ], + "edges": [], }, } @@ -92,3 +96,49 @@ def test_a_stale_type_property_does_not_sink_the_whole_diagram(): assert method.name == "decrease_stock" assert method.type is None + + +@pytest.mark.parametrize("field", ["returnType", "attributeType"]) +@pytest.mark.parametrize("stale", ["Book", "int): any"]) +def test_an_unresolvable_return_type_is_ignored_with_a_warning(field, stale, caplog): + """A method returning a class that was later deleted or renamed keeps the + old name in ``returnType``. Development ignores such a type with a warning + instead of failing every generate and validate call on the diagram.""" + with caplog.at_level("WARNING"): + method = _only_method(_diagram({"name": "renew", field: stale})) + + assert method.type is None + assert any("Ignoring unresolvable return type" in r.getMessage() for r in caplog.records) + + +def test_an_unresolvable_return_type_keeps_the_signature_type(): + method = _only_method(_diagram({"name": "renew(): date", "returnType": "Book"})) + + assert getattr(method.type, "name", method.type) == "date" + + +@pytest.mark.parametrize("field", ["returnType", "attributeType"]) +def test_the_any_placeholder_means_untyped(field): + """``any`` is the v4 editor's "no explicit return type" placeholder. + + Every method the inspector creates carries ``returnType: "any"``, and + ``buml_to_json`` writes ``"any"`` for an untyped method, so reading it as + ``PrimitiveDataType('any')`` would type every default method (``-> any``, + ``Object`` instead of ``void``) and break JSON -> B-UML -> JSON -> B-UML + idempotence. See ``docs/source/migrations/uml-v4-shape.md``. + """ + method = _only_method(_diagram({"name": "renew", field: "any"})) + + assert method.type is None + + +def test_an_untyped_method_stays_untyped_across_a_round_trip(): + from besser.utilities.web_modeling_editor.backend.services.converters.buml_to_json.class_diagram_converter import ( + class_buml_to_json, + ) + + domain = process_class_diagram(_diagram({"name": "renew", "returnType": "any", "attributeType": "any"})) + again = process_class_diagram({"title": "T", "model": class_buml_to_json(domain)}) + cls = next(c for c in again.get_classes() if c.name == "Loan") + + assert next(iter(cls.methods)).type is None diff --git a/tests/utilities/web_modeling_editor/converters/test_spec_fidelity_roundtrip.py b/tests/utilities/web_modeling_editor/converters/test_spec_fidelity_roundtrip.py index 4d7890f16..cb1d9d37f 100644 --- a/tests/utilities/web_modeling_editor/converters/test_spec_fidelity_roundtrip.py +++ b/tests/utilities/web_modeling_editor/converters/test_spec_fidelity_roundtrip.py @@ -57,96 +57,112 @@ # "The first literal" is a decision the user made when they typed the list. LITERAL_ORDER = ["SCHEDULED", "CONFIRMED", "CANCELLED"] +def _node(node_id: str, node_type: str, data: dict[str, Any], x: int = 0) -> dict[str, Any]: + return {"id": node_id, "type": node_type, + "position": {"x": x, "y": 0}, "width": 160, "height": 100, "data": data} + + +def _edge(edge_id: str, edge_type: str, source: str, target: str, **data: Any) -> dict[str, Any]: + return {"id": edge_id, "type": edge_type, "source": source, "target": target, + "data": {"points": [], **data}} + + +# v4 wire shape (``{nodes, edges}``), see docs/source/migrations/uml-v4-shape.md. DIAGRAM: dict[str, Any] = { "title": "Hotel", "model": { - "elements": { - "e1": {"id": "e1", "type": "Enumeration", "name": "BookingStatus", - "attributes": ["l1", "l2", "l3"], "methods": []}, - "l1": {"id": "l1", "type": "ClassAttribute", "name": "SCHEDULED", "owner": "e1"}, - "l2": {"id": "l2", "type": "ClassAttribute", "name": "CONFIRMED", "owner": "e1"}, - "l3": {"id": "l3", "type": "ClassAttribute", "name": "CANCELLED", "owner": "e1"}, + "version": "4.0.0", + "type": "ClassDiagram", + "nodes": [ + _node("e1", "class", { + "name": "BookingStatus", "stereotype": "Enumeration", "methods": [], + "attributes": [ + {"id": "l1", "name": "SCHEDULED"}, + {"id": "l2", "name": "CONFIRMED"}, + {"id": "l3", "name": "CANCELLED"}, + ], + }), # Abstract class, with description + URI metadata. - "c0": {"id": "c0", "type": "AbstractClass", "name": "Person", - "description": "Anyone the hotel holds a record for", - "uri": "https://schema.org/Person", - "attributes": ["a0"], "methods": []}, - "a0": {"id": "a0", "type": "ClassAttribute", "name": "fullName", - "visibility": "public", "attributeType": "str", "owner": "c0"}, + _node("c0", "class", { + "name": "Person", "stereotype": "Abstract", + "description": "Anyone the hotel holds a record for", + "uri": "https://schema.org/Person", + "attributes": [ + {"id": "a0", "name": "fullName", "visibility": "public", "attributeType": "str"}, + ], + "methods": [], + }), # Concrete child: visibility, optional, default, natural identifier. - "c1": {"id": "c1", "type": "Class", "name": "Guest", - "attributes": ["a1", "a2"], "methods": []}, - "a1": {"id": "a1", "type": "ClassAttribute", "name": "email", - "visibility": "private", "attributeType": "str", - "isExternalId": True, "owner": "c1"}, - "a2": {"id": "a2", "type": "ClassAttribute", "name": "loyaltyPoints", - "visibility": "public", "attributeType": "int", - "defaultValue": "0", "isOptional": True, "owner": "c1"}, + _node("c1", "class", { + "name": "Guest", "stereotype": None, "methods": [], + "attributes": [ + {"id": "a1", "name": "email", "visibility": "private", + "attributeType": "str", "isExternalId": True}, + {"id": "a2", "name": "loyaltyPoints", "visibility": "public", + "attributeType": "int", "defaultValue": "0", "isOptional": True}, + ], + }), # Declared id, enum-typed attribute, derived attribute, and three # method shapes: zero-argument, parameterised, defaulted parameter. - "c2": {"id": "c2", "type": "Class", "name": "Booking", - "attributes": ["a3", "a4", "a6"], "methods": ["m1", "m2"]}, - "a3": {"id": "a3", "type": "ClassAttribute", "name": "reference", - "visibility": "public", "attributeType": "str", - "isId": True, "owner": "c2"}, - "a4": {"id": "a4", "type": "ClassAttribute", "name": "status", - "visibility": "public", "attributeType": "BookingStatus", - "owner": "c2"}, - "a6": {"id": "a6", "type": "ClassAttribute", "name": "totalPrice", - "visibility": "public", "attributeType": "float", - "isDerived": True, "owner": "c2"}, - # Bare name + separate return-type property (the editor's newer shape). - "m1": {"id": "m1", "type": "ClassMethod", "name": "cancel()", - "attributeType": "bool", "owner": "c2"}, - # Legacy signature shape, private, one required and one defaulted arg. - "m2": {"id": "m2", "type": "ClassMethod", - "name": "- addGuest(guest: Guest, nights: int = 1): bool", - "owner": "c2"}, - - "c3": {"id": "c3", "type": "Class", "name": "Room", - "attributes": ["a5"], "methods": []}, - "a5": {"id": "a5", "type": "ClassAttribute", "name": "roomNumber", - "visibility": "public", "attributeType": "str", - "isExternalId": True, "owner": "c3"}, - - "o1": {"id": "o1", "type": "ClassOCLConstraint", - "name": "referenceIsSet", - "constraint": "context Booking inv referenceIsSet: self.reference <> ''"}, + _node("c2", "class", { + "name": "Booking", "stereotype": None, + "attributes": [ + {"id": "a3", "name": "reference", "visibility": "public", + "attributeType": "str", "isId": True}, + {"id": "a4", "name": "status", "visibility": "public", + "attributeType": "BookingStatus"}, + {"id": "a6", "name": "totalPrice", "visibility": "public", + "attributeType": "float", "isDerived": True}, + ], + "methods": [ + # Bare name + separate return-type property (the editor's newer shape). + {"id": "m1", "name": "cancel()", "attributeType": "bool"}, + # Legacy signature shape, private, one required and one defaulted arg. + {"id": "m2", "name": "- addGuest(guest: Guest, nights: int = 1): bool"}, + ], + }), + + _node("c3", "class", { + "name": "Room", "stereotype": None, "methods": [], + "attributes": [ + {"id": "a5", "name": "roomNumber", "visibility": "public", + "attributeType": "str", "isExternalId": True}, + ], + }), + + _node("o1", "ClassOCLConstraint", { + "name": "referenceIsSet", + "expression": "context Booking inv referenceIsSet: self.reference <> ''", + }), # Two comment boxes. A linked one becomes the class's description; # an unlinked one becomes the model's. Both are prose the user # typed and the editor keeps across a save. - "k1": {"id": "k1", "type": "Comments", - "name": "All prices are in EUR, VAT included."}, - "k2": {"id": "k2", "type": "Comments", - "name": "A stay is never shorter than one night."}, - }, - "relationships": { + _node("k1", "comment", {"name": "All prices are in EUR, VAT included."}), + _node("k2", "comment", {"name": "A stay is never shorter than one night."}), + ], + "edges": [ # Both ends named. Read by hand: the end typed Guest is reached # FROM a Booking, so `guest` is a property of Booking; the end # typed Booking is reached from a Guest, so `bookings` is a # property of Guest. - "r1": {"id": "r1", "type": "ClassBidirectional", "name": "bookingsFor", - "source": {"element": "c1", "multiplicity": "1", "role": "guest"}, - "target": {"element": "c2", "multiplicity": "0..*", "role": "bookings"}}, + _edge("r1", "ClassBidirectional", "c1", "c2", name="bookingsFor", + sourceMultiplicity="1", sourceRole="guest", + targetMultiplicity="0..*", targetRole="bookings"), # Composition, no explicit roles: both ends fall back to the # lowercased name of the class at that end. - "r2": {"id": "r2", "type": "ClassComposition", "name": "occupies", - "source": {"element": "c2", "multiplicity": "0..*"}, - "target": {"element": "c3", "multiplicity": "1..*"}}, - "r3": {"id": "r3", "type": "ClassInheritance", - "source": {"element": "c1"}, "target": {"element": "c0"}}, - "r5": {"id": "r5", "type": "Link", - "source": {"element": "k2"}, "target": {"element": "c2"}}, - # Unidirectional: the source end is not navigable. - "r4": {"id": "r4", "type": "ClassUnidirectional", "name": "handledBy", - "source": {"element": "c2", "multiplicity": "0..*", - "role": "bookingsHandled"}, - "target": {"element": "c0", "multiplicity": "1", "role": "handler"}}, - }, + _edge("r2", "ClassComposition", "c2", "c3", name="occupies", + sourceMultiplicity="0..*", targetMultiplicity="1..*"), + _edge("r3", "ClassInheritance", "c1", "c0"), + _edge("r5", "CommentLink", "k2", "c2"), + # One-way association: the source end is not navigable. + _edge("r4", "ClassBidirectional", "c2", "c0", name="handledBy", + sourceMultiplicity="0..*", sourceRole="bookingsHandled", sourceNavigable=False, + targetMultiplicity="1", targetRole="handler", targetNavigable=True), + ], }, } @@ -377,11 +393,13 @@ def test_literal_order_also_survives_back_to_editor_json(): agree with it, or a save/reload would renumber the user's literals. """ model = process_class_diagram(DIAGRAM) - elements = class_buml_to_json(model)["elements"] + nodes = class_buml_to_json(model)["nodes"] - enum_id = next(k for k, v in elements.items() - if v.get("type") == "Enumeration" and v["name"] == "BookingStatus") - literals = [elements[lid]["name"] for lid in elements[enum_id]["attributes"]] + enum_node = next(n for n in nodes + if n.get("type") == "class" + and (n["data"].get("stereotype") or "").lower() == "enumeration" + and n["data"]["name"] == "BookingStatus") + literals = [row["name"] for row in enum_node["data"]["attributes"]] assert literals == LITERAL_ORDER