# 🤖 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. **Walkthrough Chronological Design & Auto-Inference Rule (CRITICAL)**: When designing state maps, the recommended interactive flow MUST always follow this structured lifecycle:
   - **Paso 0 (Inicialización - Sin Registro)**: El agente debe preguntar y ejecutar la acción física de arranque del entorno (ej. abrir el navegador o app real mediante comandos como `launch_chrome` o cargar URL) y **esperar** a que la pantalla inicial cargue de forma interactiva. Luego se crea el primer nodo de entrada (`add_node`) y se blindan sus aserciones (`add_fingerprint`). **Nota crítica: Se omite la llamada a `record_walkthrough_action` en este Paso 0 para mantener el nodo inicial como un estado de entrada limpio sin transiciones ficticias de arranque.**
   - **Paso N en adelante (Bucle de Diseño con Registro)**: Para cada interacción subsiguiente, se sigue estrictamente el bucle: Realizar acción física en la app -> Registrar acción en bitácora (`record_walkthrough_action`) -> Crear nodo de destino (`add_node`) -> Blindar huella digital (`add_fingerprint`).
   - Repeat sequentially (e.g., click login -> record transition -> add node -> add fingerprint).
   - **Chronological Fallback Inflow**: If nodes are created sequentially without defining manual transitions or variations in their properties at design time, the agent MUST know that the execution engine automatically flattens and connects all nodes in the exact chronological order in which they were created. Do not force manual transitions; let the engine auto-infer and wire them.
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.*
