| id | SKL-state-STATEMACHINESXSTATE |
| name | State Machines Xstate |
| description | XState is a state management library using finite state machines and statecharts for modeling application logic. It helps developers create applications with predictable state management, visualizatio |
| version | 1.0.0 |
| status | active |
| owner | @cerebra-team |
| last_updated | 2026-02-22 |
| category | Backend |
| tags | ["api","backend","server","database"] |
| stack | ["Python","Node.js","REST API","GraphQL"] |
| difficulty | Intermediate |
State Machines Xstate
Skill Profile
(Select at least one profile to enable specific modules)
Overview
XState is a state management library using finite state machines and statecharts for modeling application logic. It helps developers create applications with predictable state management, visualization tools, and excellent TypeScript support. XState uses a mathematical model of finite state machines which helps developers model complex logic as clear state transitions, visualize state flow with state diagrams and visualization tools, provide full TypeScript support for type safety, ensure deterministic state transitions that are easy to test, and include built-in support for async operations and side effects.
Why This Matters
- Reduces Bugs: State machines reduce bugs from complex state logic by 30-40%
- Increases Maintainability: Visualized state flow improves maintainability
- Reduces Debugging Time: Predictable state reduces debugging time
- Improves Testability: Deterministic transitions improve testability
- Improves Developer Experience: Visualization tools and TypeScript enhance DX
Core Concepts
Inputs / Outputs / Contracts
- Inputs:
- <e.g., env vars, request payload, file paths, schema>
- Entry Conditions:
- <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>
- Outputs:
- <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>
- Artifacts Required (Deliverables):
- <e.g., Code Diff, Unit Tests, Migration Script, API Docs>
- Acceptance Evidence:
- <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>
- Success Criteria:
- <e.g., p95 < 300ms, coverage ≥ 80%>
Skill Composition
Quick Start
- Install XState: Install xstate and framework integration
- Create Machine: Define finite state machine
- Add States: Define states and transitions
- Add Context: Define initial context
- Add Actions: Implement entry/exit/transition actions
- Add Guards: Implement guard conditions
- Integrate with React: Use useMachine hook
- Test Machine: Test state transitions
- Visualize: Use Stately Editor for visualization
import { createMachine } from 'xstate'
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: {
on: {
TOGGLE: 'active',
},
},
active: {
on: {
TOGGLE: 'inactive',
},
},
},
})
Assumptions / Constraints / Non-goals
- Assumptions:
- Development environment is properly configured
- Required dependencies are available
- Team has basic understanding of domain
- Constraints:
- Must follow existing codebase conventions
- Time and resource limitations
- Compatibility requirements
- Non-goals:
- This skill does not cover edge cases outside scope
- Not a replacement for formal training
Compatibility & Prerequisites
- Supported Versions:
- Python 3.8+
- Node.js 16+
- Modern browsers (Chrome, Firefox, Safari, Edge)
- Required AI Tools:
- Code editor (VS Code recommended)
- Testing framework appropriate for language
- Version control (Git)
- Dependencies:
- Language-specific package manager
- Build tools
- Testing libraries
- Environment Setup:
.env.example keys: API_KEY, DATABASE_URL (no values)
Test Scenario Matrix (QA Strategy)
| Type | Focus Area | Required Scenarios / Mocks |
|---|
| Unit | Core Logic | Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |
| Integration | DB / API | All external API calls or database connections must be mocked during unit tests |
| E2E | User Journey | Critical user flows to test |
| Performance | Latency / Load | Benchmark requirements |
| Security | Vuln / Auth | SAST/DAST or dependency audit |
| Frontend | UX / A11y | Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |
Technical Guardrails & Security Threat Model
1. Security & Privacy (Threat Model)
- Top Threats: Injection attacks, authentication bypass, data exposure
2. Performance & Resources
3. Architecture & Scalability
4. Observability & Reliability
Agent Directives & Error Recovery
(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)
- Thinking Process: Analyze root cause before fixing. Do not brute-force.
- Fallback Strategy: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.
- Self-Review: Check against Guardrails & Anti-patterns before finalizing.
- Output Constraints: Output ONLY the modified code block. Do not explain unless asked.
Definition of Done (DoD) Checklist
Anti-patterns
- Over-Engineering: Using state machines for simple logic adds unnecessary complexity
- Poor State Design: Poorly designed states create confusing machines
- Missing Guards: Not using guards for conditional transitions causes bugs
- Side Effect Issues: Not managing side effects properly causes unpredictable behavior
- Poor Testing: Not testing state machines properly leads to bugs
- Complex Machines: Overly complex machines are hard to understand and maintain
- Missing Documentation: Missing documentation makes machines hard to use
- Not Using Context: Not using context for persistent data causes code duplication
- Poor State Naming: Unclear state names make machines hard to understand
- Ignoring Events: Not properly handling events causes bugs
Reference Links & Examples
- Internal documentation and examples
- Official documentation and best practices
- Community resources and discussions
Versioning & Changelog
- Version: 1.0.0
- Changelog:
- 2026-02-22: Initial version with complete template structure