extract-state-machine

Detects state machines from enums, status fields, switch/match statements, and transition methods. Extracts states, transitions, guards, and actions to build state diagram data.

59 stars

Best use case

extract-state-machine is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Detects state machines from enums, status fields, switch/match statements, and transition methods. Extracts states, transitions, guards, and actions to build state diagram data.

Teams using extract-state-machine should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/extract-state-machine/SKILL.md --create-dirs "https://raw.githubusercontent.com/dykyi-roman/awesome-claude-code/main/skills/extract-state-machine/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/extract-state-machine/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How extract-state-machine Compares

Feature / Agentextract-state-machineStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Detects state machines from enums, status fields, switch/match statements, and transition methods. Extracts states, transitions, guards, and actions to build state diagram data.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# State Machine Extractor

## Overview

Identifies implicit and explicit state machines in code — status fields, enum-based states, transition methods, guard conditions, and actions. Produces structured state diagram data for visualization.

## Detection Patterns

### Enum-Based States

```bash
# Status/State enums
Grep: "enum.*(Status|State)" --glob "**/*.php"

# Backed enum cases
Grep: "case [A-Z]" --glob "**/*.php" -A 0
# Read full enum to get all cases

# Enum with methods (transition logic)
Grep: "function (canTransitionTo|allowedTransitions|next)" --glob "**/*.php"
```

### Status Fields

```bash
# Status properties
Grep: "private.*\\$status|readonly.*Status|private.*Status \\$" --glob "**/*.php"

# Status setters/changers
Grep: "function (setStatus|changeStatus|updateStatus|transitionTo)" --glob "**/*.php"

# Status constants (legacy pattern)
Grep: "const STATUS_|const STATE_" --glob "**/*.php"
```

### Transition Methods

```bash
# Named transition methods (domain verbs)
Grep: "function (activate|deactivate|approve|reject|cancel|complete|suspend|resume|archive|publish|draft|submit|confirm|expire|close|open|block|unblock|verify|process|ship|deliver|refund|pay)" --glob "**/Domain/**/*.php"

# Status check before transition (guard)
Grep: "if.*status.*!==|if.*status.*===|match.*status" --glob "**/*.php"

# Transition with event recording
Grep: "->(recordEvent|raise|apply).*new.*Event" --glob "**/*.php"
```

### Switch/Match State Logic

```bash
# Match expression on status
Grep: "match.*\\(.*status|match.*\\(.*state|match.*\\(.*->getStatus" --glob "**/*.php"

# Switch on status
Grep: "switch.*\\(.*status|switch.*\\(.*state" --glob "**/*.php"

# State-dependent behavior
Grep: "case.*Status::|case.*State::" --glob "**/*.php"
```

### Symfony Workflow Component

```bash
# Workflow configuration
Glob: "config/packages/workflow.yaml"
Glob: "config/packages/workflow.php"

# Workflow service usage
Grep: "WorkflowInterface|Workflow::" --glob "**/*.php"
Grep: "->can\\(|->apply\\(|->getMarking" --glob "**/*.php"
```

## Analysis Process

### Step 1: Find State Holders

For each entity/aggregate with a status field:

1. **Read the enum/status definition** — get all possible states
2. **Find transition methods** — methods that change the status
3. **Extract guards** — conditions checked before transition
4. **Extract actions** — what happens during/after transition
5. **Find events** — events raised on transition

### Step 2: Build Transition Table

For each transition method found:

```
Read the method body:
1. What is the source state? (guard/precondition)
2. What is the target state? (assignment/return)
3. What conditions must be met? (if/match checks)
4. What side effects occur? (events, notifications)
```

### Step 3: Validate Completeness

- Can every state be reached from the initial state?
- Are there dead-end states (no outgoing transitions)?
- Are there unreachable states?
- Are all transitions guarded?

## Output Format

```markdown
## State Machines

### Summary

| Entity | States | Transitions | Has Guards | Events |
|--------|--------|-------------|-----------|--------|
| Order | 6 | 8 | Yes | 5 |
| Payment | 4 | 5 | Yes | 3 |
| User | 3 | 4 | Partial | 2 |

### Order State Machine

#### States

| State | Description | Terminal |
|-------|-------------|---------|
| `draft` | Order created but not submitted | No |
| `pending` | Submitted, awaiting payment | No |
| `confirmed` | Payment received | No |
| `shipped` | Items dispatched | No |
| `delivered` | Items received by customer | Yes |
| `cancelled` | Order cancelled | Yes |

#### Transitions

| # | From | To | Method | Guard | Action |
|---|------|----|--------|-------|--------|
| 1 | draft | pending | submit() | Has items | Validate totals |
| 2 | pending | confirmed | confirm() | Payment OK | Record payment |
| 3 | confirmed | shipped | ship() | Items packed | Send tracking |
| 4 | shipped | delivered | deliver() | Tracking confirms | Close order |
| 5 | draft | cancelled | cancel() | - | Release items |
| 6 | pending | cancelled | cancel() | - | Refund if paid |
| 7 | confirmed | cancelled | cancel() | Not shipped | Refund payment |

#### State Diagram Data (Mermaid-ready)

```
stateDiagram-v2
    [*] --> draft
    draft --> pending : submit()
    draft --> cancelled : cancel()
    pending --> confirmed : confirm()
    pending --> cancelled : cancel()
    confirmed --> shipped : ship()
    confirmed --> cancelled : cancel()
    shipped --> delivered : deliver()
    delivered --> [*]
    cancelled --> [*]
```

#### Guards Detail

| Transition | Guard Condition | Error on Failure |
|-----------|-----------------|-----------------|
| submit() | Order has at least 1 item | "Cannot submit empty order" |
| confirm() | Payment amount matches total | "Payment mismatch" |
| ship() | All items available in warehouse | "Items not available" |
| cancel() | Status is not shipped/delivered | "Cannot cancel shipped order" |

#### Events Raised

| Transition | Event | Listeners |
|-----------|-------|-----------|
| submit() | OrderSubmitted | InventoryReserve, NotifyAdmin |
| confirm() | OrderConfirmed | SendConfirmation, StartPacking |
| ship() | OrderShipped | SendTracking, NotifyCustomer |
| deliver() | OrderDelivered | RequestReview, CloseTicket |
| cancel() | OrderCancelled | ReleaseInventory, RefundPayment |
```

## State Machine Quality Indicators

| Indicator | Good | Warning | Critical |
|-----------|------|---------|----------|
| All transitions guarded | Yes | Partial | No guards |
| No dead-end states | No dead ends | With purpose (terminal) | Unreachable |
| Events on transitions | All important | Some | None |
| Explicit state enum | Yes | Constants | String literals |
| Transition methods named | Domain verbs | Generic setStatus | Direct field set |

## Common Anti-Patterns

| Anti-Pattern | Detection | Issue |
|-------------|-----------|-------|
| String-based status | `$status = 'pending'` | No type safety |
| Direct field mutation | `$this->status = 'new'` | No guard enforcement |
| Missing transitions | State reachable only via DB | Bypasses domain logic |
| God transition | One method handles all transitions | No guard per transition |

## Integration

This skill is used by:
- `business-logic-analyst` — documents state machines in domain
- `diagram-designer` — generates state diagrams from extracted data
- `explain-business-process` — references state transitions in workflows

Related Skills

extract-domain-concepts

59
from dykyi-roman/awesome-claude-code

Maps domain model components — Entities, Value Objects, Aggregates, Services, Events, Repositories. Builds Ubiquitous Language glossary connecting code names to business terminology.

extract-business-rules

59
from dykyi-roman/awesome-claude-code

Extracts validation rules, guards, business constraints, authorization rules, and invariants from domain code. Maps technical implementations to business terminology for non-technical stakeholders.

create-state

59
from dykyi-roman/awesome-claude-code

Generates State pattern for PHP 8.4. Creates state machines with context, state interface, and concrete states for behavior changes. Includes unit tests.

yii-knowledge

59
from dykyi-roman/awesome-claude-code

Yii framework knowledge base. Provides Yii3 modular architecture, DDD integration, PSR-7/PSR-15 compliance, persistence, DI, security (RBAC, auth), event system (PSR-14), queue/jobs, infrastructure components (cache, rate limiter, HTTP client), testing, and antipatterns for Yii PHP projects.

troubleshooting-template

59
from dykyi-roman/awesome-claude-code

Generates troubleshooting guides and FAQ sections for PHP projects. Creates problem-solution documentation.

trace-request-lifecycle

59
from dykyi-roman/awesome-claude-code

Traces full request lifecycle from Router through Middleware, Controller, UseCase, Repository to Response. Documents HTTP methods, routes, middleware stack, response codes, and error handling paths.

trace-data-transformation

59
from dykyi-roman/awesome-claude-code

Maps data transformation chains — Request DTO to Command to Entity to Response DTO. Identifies mappers, serializers, type conversions, and data loss points across layer boundaries.

testing-knowledge

59
from dykyi-roman/awesome-claude-code

Testing knowledge base for PHP 8.4 projects. Provides testing pyramid, AAA pattern, naming conventions, isolation principles, DDD testing guidelines, and PHPUnit patterns.

task-progress-knowledge

59
from dykyi-roman/awesome-claude-code

TaskCreate pattern guidelines for progress tracking in coordinator agents

symfony-knowledge

59
from dykyi-roman/awesome-claude-code

Symfony framework knowledge base. Provides architecture, DDD integration, persistence, DI, security, messenger, workflow, events, infrastructure components, testing, and antipatterns for Symfony PHP projects.

suggest-testability-improvements

59
from dykyi-roman/awesome-claude-code

Suggests testability improvements for PHP code. Provides DI refactoring suggestions, mock opportunities, interface extraction, testing strategy recommendations.

suggest-simplification

59
from dykyi-roman/awesome-claude-code

Suggests code simplification opportunities. Identifies extract method candidates, complex expressions, redundant code, refactoring opportunities.