state-machine-hunter
Skill4 starsChanged 16 days agoMITView on GitHub
Find every implicit state machine in an app and make it explicit without breaking anything. Use when the user asks to find hidden or implicit state machines, clean up flag soup (isLoading, isError, isSubmitting combinations), fix impossible or stuck UI states, race conditions, double submits, or flaky async flows, refactor loading/error/retry/polling logic, model a lifecycle (orders, uploads, auth sessions, connections, wizards, onboarding, payments, jobs), or improve the UX, DX, and agent experience (AX) of stateful code. Inventories every machine, picks the least invasive fix that removes impossible states, pins behavior with characterization tests, then refactors in small safe steps.
In this repository15 other files it gives its agents.
- AGENTS.mdAGENTS.md
- agent-ready-repoSkill
- bug-triageSkill
- ci-auditorSkill
- deep-modulesSkill
- evidence-before-claimsSkill
- finish-the-jobSkill
- parallel-agentsSkill
- plan-before-codeSkill
- prior-art-scoutSkill
- security-auditSkill
- senior-engineerSkill
- staff-reviewSkill
- systematic-debuggingSkill
- test-driven-developmentSkill
The file
We split this skill into the rules it gives an agent
9 rules. About 0 are common, 8 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈8
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 57
UX: every state has a designed screen or message (idle, loading, empty, partial, error with recovery, offline, cancelled).
- Distinctive: line 63
Document only: Add the diagram and name the states in a comment.
- Distinctive: line 74
Pin today's behavior: Write characterization tests over the transitions that exist now, including the odd ones.
- Very specific: line 77
Make illegal states unrepresentable: remove the old fields and add exhaustiveness checks (assertNever, match with no wildcard, linters such …
- Distinctive: line 79
Separate bug fixes from refactors: If the explicit machine exposes a real bug (a stuck state, a missing cancel), fix it in its own commit …
- Distinctive: line 101
Read-only until the inventory and decisions exist.
- Distinctive: line 102
Don't introduce a library to model a machine the language can model with a union type.
- Distinctive: line 103
Don't rename persisted state values or public API fields as part of this work without explicit approval.
- Distinctive: line 104
Every changed machine ends with its tests passing and a diagram that matches the code.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
State Machine Hunter
Find all of the implicit state machines in my app. Make the best decision that will elevate all three: the user experience (UX), developer experience (DX), and agent experience (AX), always, without breaking anything.
Most "weird" bugs in stateful code are not logic errors. They are states the code can represent but never meant to allow: loading and errored, submitted twice, connected with no session, an upload that can't be cancelled. Every pair of booleans doubles the number of representable states, and almost none of the extra states are designed. Making the state machine explicit turns a class of runtime bugs into compile errors and gives every state a deliberate UX.
The work has five phases. Phases 1 to 3 are read-only; nothing changes until you have the full picture.
Match the scope to the request. When the user asks to find all the state machines (the prompt above), sweep the whole codebase. When the request is about one flow (a double submit, one stuck screen, one race), fix that machine with the same phases, and list any other machines you noticed as follow-ups instead of refactoring them uninvited.
Phase 1: Hunt (read-only)
Sweep the whole codebase, not just the file in front of you. Machines hide in UI components, services, background jobs, database columns, and the gaps between them. Signals, strongest first:
- Boolean clusters describing one thing:
isLoading,isError,isSuccess,hasFetched,isSubmitting,isRetrying. Two or more booleans about the same entity is almost always a machine. - Stringly typed status:
status,state,phase,step,stage,modetyped asstringorint, compared against literals in many places. - Nullable fields that encode state:
data: T | nullnext toerror: Error | null, ordeletedAt,archivedAt, andpublishedAtall on one row. - Check-and-set guards:
if (!this.connecting) { this.connecting = true; ... }. These are transitions without a machine, and the usual home of race conditions. - Timers and retries:
setTimeout, polling loops, backoff,attemptcounters, debounce flags. - Transitions written in several places: two services that both set
order.status = "paid". - Comments that admit it: "should never happen", "shouldn't get here", "TODO race",
unreachable. - Multi-step flows: wizards, checkout, onboarding, file upload, auth and session refresh, WebSocket connections, payment intents, background job status, feature rollouts.
references/patterns.md has ready-made rg searches for these signals in several languages.
Phase 2: Map each machine
For every candidate, write down:
| Field | Question |
| Name | What domain concept is this the lifecycle of? |
| Location | Every file and line that reads or writes the state |
| States | Which states are actually reachable today, including accidental ones? |
| Events | What causes each transition: user action, response, timer, webhook? |
| Impossible-but-representable | Which combinations can the types express but should never exist? |
| Missing transitions | Can the user cancel, retry, go back, or recover from every state? Any state with no exit? |
| Races | Can two events arrive in an order the code doesn't expect (double click, stale response, concurrent workers)? |
| Persistence | Is the state stored (DB, URL, local storage, queue) or exposed in a public API? |
| Tests | Which transitions are covered by tests today? |
Draw the machine as a Mermaid stateDiagram-v2. A diagram makes missing exits and dead states obvious in a way prose never does.
Phase 3: Decide, one machine at a time
Score each machine on pain (observed bugs, confusion, support load), risk (blast radius, test coverage, persisted data, public API), and payoff for each audience:
- UX: every state has a designed screen or message (idle, loading, empty, partial, error with recovery, offline, cancelled); no stuck states; the user can always exit or retry.
- DX: the compiler enforces exhaustive handling; the lifecycle is readable in one place; names match the domain.
- AX: states are named constants an agent can grep; transitions live in one file; a diagram sits next to the code; tests are named after transitions, so the next agent can change the machine safely.
Then choose the least invasive option that removes the impossible states:
- Document only. Add the diagram and name the states in a comment. Right when the machine is correct, stable, and untested enough that touching it is riskier than leaving it.
- Make the type honest. Replace the booleans or strings with a discriminated union, enum, or sealed type where each state carries only its own data. Behavior stays the same. This is the most common win.
- Centralise transitions. One
transition(state, event)function; illegal transitions are rejected explicitly instead of silently ignored. - Adopt a state-chart library (XState, a workflow engine). Only for hierarchical or parallel states, many events, or real need for visualisation. Never for a three-state toggle.
Machines that are fine as they are still go in the inventory, with the reason you left them alone. "I checked and it's fine" is a finding.
Phase 4: Refactor without breaking anything
"Without breaking anything" is a procedure, not a hope:
- Pin today's behavior. Write characterization tests over the transitions that exist now, including the odd ones. If a machine can't be tested, downgrade it to "document only" and say why.
- Introduce the explicit type next to the old one. Derive the old booleans from the new state (
const isLoading = state.status === "loading") so every call site keeps working. - Migrate call sites in small commits, running the tests after each.
- Make illegal states unrepresentable: remove the old fields and add exhaustiveness checks (
assertNever,matchwith no wildcard, linters such asexhaustivefor Go). - Respect boundaries. Persisted values, URLs, event payloads, and public API shapes keep their wire format; map at the boundary. Changing stored data needs a migration plan and the user's approval.
- Separate bug fixes from refactors. If the explicit machine exposes a real bug (a stuck state, a missing cancel), fix it in its own commit and call it out, because it is a behavior change.
- Remove the compatibility shims once nothing reads them.
Phase 5: Report
## State machines found: N
| # | Machine | Where | States (today) | Problems | Decision |
|---|---------|-------|----------------|----------|----------|
| 1 | Checkout submit | src/checkout/*.tsx | 4 booleans, 16 combos, 5 reachable | double submit; stuck "processing" on timeout | Honest type + central transitions |
| 2 | Socket connection | src/net/socket.ts | strings: 3 | none observed | Document only (diagram added) |
### 1. Checkout submit
Before/after diagram, what changed, UX/DX/AX impact, tests added, behavior changes (if any).
### Left alone and why
### Follow-ups worth filingGuardrails
- Read-only until the inventory and decisions exist. Don't start refactoring the first machine you find.
- Don't introduce a library to model a machine the language can model with a union type.
- Don't rename persisted state values or public API fields as part of this work without explicit approval.
- Every changed machine ends with its tests passing and a diagram that matches the code.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

