Skip to content
Back to skills

Implicit State Machines

ASecurity

Finds an app's implicit state machines (state and transitions spread across booleans, status fields, nullables, timers, callbacks, webhooks, jobs and DB columns), verifies each one with a concrete sequence of events that breaks it and proposes the lightest fix that improves UX, DX and AX without breaking anything. Reports in the chat and stops; applies only what the user picks, test first. Use it for "find all of the implicit state machines in my app", "make state machines explicit" or the vi...

  • 2 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added November 17, 2026
developmentgodockerrefactoringgitapidatabasefrontendci/cdsecurity

Works with

  • terminal
  • api

Security analysis

A100/100

Pro scans all 7 files and shows the line behind each finding

Scanned November 17, 2026

npx -y skills add OmarAlex24/audit-skills --skill implicit-state-machines --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Implicit State Machines?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Implicit State Machines
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/omaralex24-implicit-state-machines/badge)](https://www.skillsdirectory.com/skills/omaralex24-implicit-state-machines)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: implicit-state-machines
description: Finds an app's implicit state machines (state and transitions spread across booleans, status fields, nullables, timers, callbacks, webhooks, jobs and DB columns), verifies each one with a concrete sequence of events that breaks it and proposes the lightest fix that improves UX, DX and AX without breaking anything. Reports in the chat and stops; applies only what the user picks, test first. Use it for "find all of the implicit state machines in my app", "make state machines explicit" or the viral UX/DX/AX prompt, and also for impossible or invalid states, flag soup or boolean soup (isLoading/isError/hasData), a stuck loading spinner, async races, orders or jobs stuck in a status, statuses written from many places without a guard, or an audit of how the app handles its state, even if they never say "state machine". Not for designing a new machine from scratch. Also triggers on Spanish requests such as "busca las máquinas de estado implícitas", "haz explícitas las máquinas de estado" or "sopa de booleanos".
---

# Implicit state machines

An implicit state machine is a lifecycle whose states and transition rules are not in one place: they live spread across variables, handlers, effects, timers, webhooks and database columns. Each function on its own can be fine and every test can pass, and the system still reaches a state nobody designed.

Reference example (e-commerce): an order's `status` is written by `checkout()` (`pending`), `handlePayment()` (`paid`), `shipOrder()` (`shipped`), `cancelOrder()` (`cancelled`), `onWebhook()` (`paid` again) and `adminFix()` (anything). Nothing stops `shipOrder()` on a `pending` order, so a `shipped` order with `paid: false` exists. The integration tests cover `cart → paid → shipped → done` and none goes through `refunded` or `re-shipped`.

Finding a machine is not finding a bug. This skill's value is in telling the two apart with evidence.

Write the report in the user's language.

## Non-negotiable rules

- **Report first.** Phases 1 to 5 change nothing: no code, no files, no git, no issues, no published pages, no installed dependencies. The report goes in the chat, in the user's language. It is saved to a file only if the user asks.
- **Apply only what the user picks.** Phase 6 starts when the user says which findings to apply. "Without breaking anything" means: test first, the project's checks run, refactors kept apart from fixes, and no commit or PR unless asked.
- **Nothing that writes during the scan.** Do not run tests, builds or migrations while auditing: they write caches and can touch a database. The default method is `static trace`. If an isolated execution would settle a Likely finding, propose it in the report.
- **No XState by default.** The fix is the lightest one that removes the defect (see phase 3).
- **Each topic in its skill.** Data values that overwrite each other (balances, stock, counters), dual writes, events and retries belong to `data-consistency`; measuring latency or load, to `perf-diagnosis`; auth and rate limiting, to `api-security-review`; a formula, a boundary, a condition, a parsing step or a default value that gives a wrong result, to `correctness-review`; system design (requirements, data, APIs, availability), to `architecture-review`; module or layer boundaries that are not respected, dependency cycles, the same problem solved several ways, god-modules, unused code or packages and docs or ADRs that contradict the code, to `code-structure`; IaC, environments, Docker and compose, K8s, CI/CD, deploy, config and secrets management, backups and restore, monitoring and alarms, platform limits, infrastructure SPOFs, pinned versions and infra cost, to `infra-review`; the code that calls an LLM (prompt injection, tools, unvalidated output, cost, provider failures), to `llm-app-review`. When a signal falls there, note it under "Not covered" with the skill it goes to and do not develop it.

## Phase 0: scope and context

1. Use the scope the user gave. If it is a monorepo and there is no hint, ask which app or package to audit before starting.
2. Read the project's rules (AGENTS.md, CLAUDE.md, CONTRIBUTING.md). Proposals follow its patterns; if one clashes with a rule, turn it into a question.
3. Note what is already explicit: enums or unions with an exhaustive switch, reducers, transition tables, statechart libraries, DB constraints. One existing does not rule out implicit coordination around it.
4. If there are persisted states, find the schema and the migrations: that is where the values that cannot be renamed lightly live.

## Phase 1: find candidates

Read [references/signals.md](references/signals.md). Prioritize units (component, hook, store, service, table) where two or more signals coincide; a single concrete, reachable failure is enough to trace a candidate with one signal.

Before keeping a group of fields, apply the **orthogonal flags filter**: if every combination is valid and each field controls something independent (`muted`, `fullscreen`, `captionsEnabled`), it is not a state machine, even if a reset writes them together.

Follow **every writer** of the state, also outside the scope: adapters, jobs, webhooks, pollers, admin scripts, migrations. In the order example the state is written by six functions in six files; auditing only one finds nothing. For queues, workers, leases, outboxes or persisted workflows, also read [references/distributed-lifecycles.md](references/distributed-lifecycles.md).

If the fix for a defect falls outside the requested scope (another package, another copy of the same code), report it anyway and ask whether to include it; do not drop it or widen the scope on your own.

**Large repos** (more than ~30 files or ~10,000 lines of code in scope, not counting tests): if you can launch subagents, split the scope by module among read-only subagents (Explore type). Give them their module, the path to `references/signals.md` and this output format per candidate:

```text
path:line | fields | states they encode | writers (n, lines) | readers (n) | invalid combinations | writers outside the module
```

The subagents only find. Verification, classification and risk review are yours, on the merged and deduplicated list, reading the code of each candidate you report. Without subagents, or below the threshold, do it all yourself.

## Phase 2: reconstruct and verify

For each candidate:

1. **Expected invariant**, in one sentence. "An order only ships if it is paid."
2. **Real map**: state variables, the states the code thinks it has, events (user action, response, error, timer, webhook, restart, unmount) and who writes each transition.
3. **Sequence that breaks it**: concrete events in order, with `path:line` at each step, up to the bad state and what the user or operator sees.
4. **Try to rule it out.** Check callers and their guards, remounts (`key`, route change), disabled or hidden UI, locks, transactions, conditional writes, DB constraints, deduplication, the real worker registration. If the recovery or degradation is deliberate (documented, with an alert or planned manual intervention), it is not a defect.
5. **Guaranteed exit.** Every non-final state needs an exit that does not depend on the happy path: failure, cancellation, timeout or recovery after a restart. A `processing` that is only left if a callback arrives is a state with no exit.
6. **Test coverage.** Which transitions the existing tests cover and which they do not. Typically: only the happy path.

Defects to look for: a reachable impossible combination; a state with no exit; an incomplete reset; a race (an old result overwrites a new one, or an action runs twice); lost work or live timers after unmount or cancel; a loop with no terminal or error state; copies of the same flow that diverged.

**Confidence label**, based on the trace in the code:

- **Confirmed**: you traced every step of the sequence. A complete static trace is enough.
- **Likely**: one step depends on runtime behavior you did not confirm (library, platform, queue topology). Name that step.
- **Smell**: it works today, but only by convention, by call order or by a guarantee somewhere else. Name that guarantee.

Report separately the **evidence method** (`static trace`, `isolated execution`, `integration execution`, `production evidence`; only the ones you really used; in the swarm contract, `static trace` is reading and the rest are measurement) and the **impact** (what the user sees, what is lost, how much money or data) with its **severity** (Critical, High, Medium or Low; scale in the template). Do not say something was reproduced if you did not run it.

Rule out the candidates that turn out healthy and count them, one line each: "reviewed, does not happen because…".

## Phase 3: propose the fix

Read [references/fixes.md](references/fixes.md). From the lightest to the heaviest:

1. a tagged union or enum instead of parallel flags;
2. a transition function when the transitions are spread out;
3. a conditional write (CAS) on the current state or version, checking how many rows it changed, for persisted states;
4. request id, generation counter or cancellation for races;
5. a statechart library only if the repo already uses one or the case has hierarchy, parallel regions or timers that justify it.

For each proposal write:

- **UX / DX / AX**, one line each. AX is how easy it is for an agent to read, change and verify that code: named states, a single source of truth, typed transitions, tests that describe the machine. Do not invent gains; if a dimension stays the same, say so. A proposal that makes any of them worse is dropped.
- **Risks of breaking something** (mandatory review; details in `fixes.md`): persisted or serialized names (DB values, storage keys, payloads), dynamic access by string (also in tests), API or event contracts, and checks CI does not run (device, staging, manual tests). If you cannot name the test that shows it does not break, the risk is not zero.
- **Regression test**: which sequence it reproduces, in which file and with which existing helper. If there is no helper, say so.
- **Fix status** (bugs only): **ready** to apply, or **needs decision** (link the report's question). A bug can have a ready fix even if the refactor of its machine is issue or leave.
- **Refactor action** (only for refactoring the machine, with no behavior change; bugs take the action **fix**):
  - **refactor-now** (Now): no behavior change, covered by existing automated tests, no pending product decision and no open risk. Every reachable combination maps to a state of the new type and every discarded combination is unreachable.
  - **issue** (Issue): deferred; needs a product decision, touches persisted values, requires a check outside CI or is part of something bigger. It is a verdict in the report, not an action: the skill does not open the issue.
  - **leave** (Leave): small and readable as it is, or it costs more than it gains. If refactor-now and leave both fit, pick leave unless you name a concrete benefit.
- **Effort**: S, M or L.

## Phase 4: two independent reviewers

Finish phases 2 and 3 before this one: the reviewers see the complete list once. If a new finding shows up afterwards, send it in a short round to both or mark it "no independent review".

If Confirmed or Likely findings remain, launch two reviewers in parallel, in a single message, following [references/reviewers.md](references/reviewers.md): one for correctness and regressions, the other for value and simplicity. They get the findings and the code paths, not your reasoning or your opinion; a reviewer you hand your conclusion to tends to confirm it.

You verify each objection in the code yourself, adjust or rule out the finding and send it back only to the reviewer who objected. At most two rounds. Whatever still lacks agreement goes to "Not included" with both positions.

If you cannot launch subagents (for example, because you are one yourself), say so in the report, make an adversarial pass yourself with both reviewers' questions and mark the findings as "no independent review".

## Phase 5: report and stop

Write the report in the chat with [references/report-template.md](references/report-template.md): summary, table, one block per finding with its Mermaid diagram of the real behavior, smells, ruled-out items, what was not covered and questions.

Detail goes where the risk is: a full block for Confirmed and Likely bugs; refactors, smells and ruled-out items in one or two lines each. Do not repeat in the block what the table already says.

End by asking which findings to apply, with your recommended order, and offer in one line to save the report to a file. **Then stop.** Do not start phase 6 in the same turn, even if the original prompt says "make state machines explicit": that describes the goal, not permission to edit without review.

## Phase 6: apply (only what the user picked)

Before touching anything, confirm in one line what you will apply. Then, in this order:

1. **Bug fixes**, one by one: write the regression test, run it and watch it fail for the expected reason, fix, watch it pass.
2. **refactor-now refactors**, with no behavior change: the existing tests pass without changing their expectations. They stay separate from the fixes (another step, another diff, and another commit if commits are requested).
3. **Project checks** after each block (lint, typecheck, tests). Report each command with its result and name the ones you could not run and why.

If a test touches a database, say which environment it points to before running it. Do not change persisted values without the project's migration process. Do not refactor the ones marked issue or leave. No commits, push or PRs unless asked.

## Common mistakes

- Reporting "could cause…" without a concrete sequence. No sequence, no finding.
- Staying in the frontend. `status` columns and jobs are usually the worst machines.
- Counting signals instead of tracing. Many booleans are not a bug.
- Proposing XState, or renaming persisted values, as if it were free.
- Citing `path:line` from memory. Every cited line must have been read.

## Swarm mode

It turns on when the invocation brings a swarm brief (between `[swarm brief]` and `[end of brief]`), with `contract:`, `map:`, `structure:`, `output:` and `data:`. Used on its own, the skill follows the procedure above unchanged, report included. In this mode:

- **Phases:** follow phases 0 to 3: verification is phase 2 and, from phase 3, the fix, its risks, the test, the action and the effort come in; you apply nothing. The brief's map replaces reading the rules and what is already explicit in phase 0, but read what the map points to and whatever it is missing.
- **No questions and no waiting:** what you would ask the user goes to the `questions` field; you do not stop to wait for an answer.
- **No subagents or reviewers:** the swarm does the independent verification. This overrides the large-repo rule of phase 1 and the two reviewers of phase 4. Make the pass that tries to rule out each finding yourself, prioritize by the map's hot paths and declare in `not_covered` what you did not cover.
- **Data:** only the `data:` command. You never open connections, tunnels or scripts of your own, and you do not read `.env` looking for credentials. If `data:` is "none", what you would have measured goes to `requested_measurements`.
- **Slice:** if the brief brings `slice:`, you only report findings whose main location (`locations[0]`) is in that slice; the membership rule is in the brief and other auditors of this same skill have the other slices. You may open files outside it only to follow a sequence that starts in your slice, and each one goes to `outside_slice` with the reason. A defect that starts outside is not yours: at most, one line in `not_covered` with its path:line. The slice section (`slice map:`) completes the global map. What the brief marks in `exclude:` belongs to no slice: you do not audit it, do not cite it as evidence and do not report anything whose main location falls there; you may open it only to understand a call that leaves the scope, and then it goes to `outside_slice` with the reason.
- **Limits:** you do not modify the audited repo and you do not read other audit runs or other auditors' folders, except what the brief gives you: contract, map, `structure:` and your folder.
- **Metric:** fill `metric` in each finding per `before-after.md` (next to the contract the brief gives), with this skill's row of its "Guide per skill" as the hint: writers of each status, writes without a guard, transitions outside the table or impossible states reachable in a property test, counted by a command (a grep or a script). A metric is a command that is run again, never a count of findings, and you do not invent its result: `{not_measurable: "<why>"}` is valid.
- **Output:** a single file, `findings.json`, in the folder the brief gives (`your folder:`), with the contract's object, and that same object as your answer. In swarm mode you write no readable report and no other file: the report template is for normal mode and the swarm's plan comes from the `findings.json` files. Use the contract's vocabulary: confidence, method, severity, effort and action.

Files in this skill

  • CREDITS.md5.3 KB
  • SKILL.md16.9 KB
  • references/distributed-lifecycles.md2.8 KB
  • references/fixes.md6.2 KB
  • references/report-template.md5 KB
  • references/reviewers.md2.4 KB
  • references/signals.md7.2 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.