# 🤖 Rules for AI Agents (Copilot, Cursor, Gemini, etc.)

## 🚀 Environment & Tools
- This is a **Node.js** project using **npm**.
- You have **FULL PERMISSION** to execute terminal commands and create/modify files.
- The primary testing framework is `mcp-state-machine-test-framework` (SMS V12.5).

## 🛠️ Mandatory Workflow
1. **Never ask for setup details**: Read `package.json` and `README.md` first.
2. **Auto-Initialization**: The environment (folders like `/maps`, `/suites`, `/test_cases`, `/reports` and `dashboard.html`) scaffolds automatically when the state machine server starts up. If these files are deleted or corrupted, run the `init_project` MCP tool to restore them.
3. **Structured Design (No Manual Hacks)**: DO NOT edit or create JSON files in `/maps`, `/suites`, or `/test_cases` directly. ALWAYS use the provided `sms_builder` MCP tool to keep schemas 100% compliant.
4. **Strict JSON Test Case Schema (Poka-Yoke)**: If you ever write, modify, or read a Test Case JSON file, you MUST strictly adhere to the following schema:
   - Root key: exactly `"name"` (string) (NEVER `"testcasename"`).
   - Route key: exactly `"ruta_estricta"` (array of strings) (NEVER `"ruta extricta"` or spaces/typos).
   - Transition values: exactly `"transicion:TRANSITION_NAME"` matching the map definition (NEVER arrow syntax like `"transicion:state1->state2"`).
   - Data key: flat key-value object (NEVER nested BDD objects like `given`, `when`, `then`).
   Any deviation is rejected immediately by the execution engine's Poka-Yoke compiler.
5. **State Fingerprint Quality (2 Selectores Obligatorios)**: When creating or adding fingerprints for a state node, you must define **at least 2 standard visual selectors** (e.g. one unique view header/title selector to confirm context, plus one stable interactive element like a button or input). Do NOT use only one selector, to prevent false positives and duplicate matching.
6. **Flexible Delta-Based Auto-Inference Design Loop (CRITICAL & STATE-OF-THE-ART)**: When modeling state maps, the Agent MUST follow this flexible, smart delta-comparison cycle:
    - **Paso 0 (Inicialización Conversacional Híbrida - IA Cerebro, Node Manos)**:
      - El Agente **debe preguntar** a Mateo qué aplicación o servidor MCP se va a probar (ej: `wdio-mcp`).
      - El Agente **debe leer los esquemas de herramientas** en la carpeta del servidor MCP seleccionado (ej. `%USERPROFILE%\.gemini\antigravity\mcp\<serverName>` o la ruta correspondiente en el OS actual), analizar sus capacidades y presentarle a Mateo una sugerencia de herramientas ordenada de **mayor a menor idoneidad** para capturar huellas visuales estables.
      - El Agente pregunta por la acción física de arranque inicial y la ejecuta programáticamente.
      - El Agente utiliza su **inteligencia de análisis cognitivo** para inspeccionar el DOM (usando `get_accessibility_tree` o `get_elements`), identificar al menos 2 selectores estables (según la Regla 5) y generar las aserciones de la huella digital.
      - Finalmente, llama a `sms_builder` (`action: "start"`) enviando los parámetros programáticos (`launchAction`, `asserts`, `firstNodeName`) para que Node.js los registre en disco de forma determinista.
    - **Bucle de Inferencia Híbrido (Acción -> Delta Cognitivo -> Nombramiento -> Registro Atómico)**:
      - **Entrada del Usuario y Traducción (IA Cerebro)**: Mateo describe en lenguaje natural la acción física a realizar (ej: "escribir admin en usuario y clic en entrar"). El Agente utiliza herramientas de DOM (ej: `get_elements` o `get_accessibility_tree` de `wdio-mcp`) para analizar cognitivamente la pantalla actual, **extraer los selectores CSS/ID reales**, y construir la **acción física ejecutable calificada de MCP** (ej: `mcp:wdio-mcp/click_element {"selector":"#login-submit"}`).
      - **Ejecución y Captura (Node Manos)**: El Agente ejecuta de fondo dicho comando MCP calificado en el navegador Chrome. Al completarse, ejecuta el set de aserciones elegido para evaluar el nuevo estado de la pantalla.
      - **CRITICAL POKA-YOKE (Acción MCP Obligatoria)**: Al registrar la transición en `sms_builder` (`record_step` o `record_walkthrough_action`), el parámetro `accion` **DEBE SER SIEMPRE el comando ejecutable MCP calificado** (ej: `mcp:wdio-mcp/click_element {"selector":"#btn"}`) y **NUNCA** una descripción en lenguaje natural (como "clic en login"). Esto garantiza que la máquina pueda correr el test de forma 100% desatendida.
      - **Análisis Delta Cognitivo (IA)**: El Agente compara las huellas antes/después y analiza el DOM actual utilizando su inteligencia para determinar si hubo un Delta (cambio de pantalla). La IA detalla qué cambió y sugiere nombres idóneos para el nuevo estado.
      - **Flexibilidad Conversacional**: Si Mateo da instrucciones de desviación (borrar nodo, renombrar, etc.), el Agente actúa como traductor llamando a `sms_builder` (`remove_node`, `rename_node`, `build_test_case`, etc.) y luego continúa.
      - **Registro Atómico**: Una vez confirmado el nombre del destino, el Agente llama a `sms_builder` (`action: "record_step"`) enviando origen, destino, la **acción física MCP calificada** y las huellas analizadas de la pantalla destino.
   - **Traducción Determinista de Test Cases y Suites**:
     - Al pedirte crear un test o suite con lenguaje natural, traduce la intención identificando las transiciones exactas, validando nombres. Llama a `build_test_case` o `build_suite` enviando la estructura rigurosa para que el servidor la valide y escriba de forma determinista en su formato definitivo.
7. **Execution & Auditing**: Use `sms_executor` to run your test suites. You can visualize results and topographies by launching the dashboard with the `show_dashboard` tool.
7. **Hook Design and State Alignment Rules**:
   - **Suite Hooks (`beforeSuite` / `afterSuite`)**: Avoid transition actions (`transicion:...`). `beforeSuite` must only contain technical commands (e.g., `launch_chrome`, open app, DB setup) to avoid leaving the app in an unexpected starting state for the first test case. `afterSuite` must only contain state-independent, fail-safe teardown commands (e.g., `mcp:wdio-mcp/close_session`) to guarantee successful cleanup even if preceding tests crashed.
   - **Case Hooks (`beforeCase` / `afterCase`)**: Be extremely selective. If using a transition in `beforeCase` as a precondition, the final state must align perfectly with the starting node of the test case's `ruta_estricta`. `afterCase` should prefer non-interactive cleanup commands to ensure teardown succeeds even when test cases fail.
   - **Step Hooks (`beforeStep` / `afterStep`)**: STRICTLY FORBIDDEN to use transitions (`transicion:...`). They must only contain non-interactive MCP (`mcp:...`) or Shell (`sh:...`) actions (e.g., `get_screenshot`, logging, waiting for generic spinners to hide) to prevent breaking the state machine flow.


8. **Hierarchical State Machine Rules (HSM V13.0)**:
   - **Composite & Nesting**: Declare composite states using `"type": "composite"` and `"defaultEntry": "INITIAL_LEAF"`. Define nested child nodes inside the `"nodos": { ... }` object. The engine automatically flattens maps, adds parent references, and recursively resolves `defaultEntry`.
   - **Transition Bubbling**: Place high-level shared transitions (like logout or global alerts) directly on the parent composite state. Child nodes inherit these automatically via parent pointers.
   - **Boundary LCA hooks**: Lifecycle hooks (`before`/`after` / `beforeSubmap`/`afterSubmap`) run strictly at boundary crossings using the Lowest Common Ancestor algorithm. Do NOT execute transition actions inside these hooks.

## 🏁 How to Start
- Ensure the SMS server is running and configured correctly in `mcp_config.json`.
- Execute `sms_builder` with `action: "start"` to begin modeling maps or creating test cases.

---
*Follow these rules to ensure high-fidelity automation and state-of-the-art model-based testing.*
