State Machines
ASecurityFind the implicit state machines in a codebase, model the riskiest promise in TLA+ or PlusCal, check it with the everystate model checker, and map each counterexample back to code, a repro, and an honest finding. TRIGGER when: asked to "find the implicit state machines", find hidden lifecycles, model-check, write a TLA+ spec, prove an invariant, run everystate or `everystate conform`, or check races, retries, timeouts, idempotency, leases, locks, queues, leaks, stuck or orphaned resources, or...
- 43 stars
- 0 votes
- 0 copies
- 0 views
- Added December 3, 2026
Works with
Security analysis
100/100Pro scans all 20 files and shows the line behind each finding
npx -y skills add mifunedev/openharness --skill state-machines --agent claude-codeAre you the author of State Machines?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/mifunedev-state-machines)---
name: state-machines
description: |
Find the implicit state machines in a codebase, model the riskiest promise in
TLA+ or PlusCal, check it with the everystate model checker, and map each
counterexample back to code, a repro, and an honest finding. TRIGGER when:
asked to "find the implicit state machines", find hidden lifecycles,
model-check, write a TLA+ spec, prove an invariant, run everystate or
`everystate conform`, or check races, retries, timeouts, idempotency, leases,
locks, queues, leaks, stuck or orphaned resources, or subscription, invoice,
provisioning, or sandbox lifecycles; "can these steps happen in a bad
order?". Do NOT trigger for per-input function correctness (use property
tests), an audit verdict (/audit), or implementing a fix (/prd). It verifies
the model, not the code, unless `conform` runs on an independent trace.
argument-hint: "[path-or-subsystem] [--promise \"<one sentence>\"] [--unattended]"
license: MIT
---
# State machines
Find one promise that a hidden state machine must keep. Model it small. Check
every interleaving with everystate. Report what the checker found in the
code's own words. Discovery feeds modeling, and modeling feeds triage. A flood
of diagrams is a failure.
Arguments received: `$ARGUMENTS`
The modeling method belongs to upstream. Before you write the first spec, read
[`references/everystate.md`](references/everystate.md). It is a verbatim copy
of the everystate `formal-verification` skill, pinned to everystate 0.4.2
(MIT). This skill adds discovery, a pinned tool wrapper, pass gates, evidence
levels, a run layout outside the worktree, and a reviewed write-back loop.
## Non-negotiables
1. **Model one promise per run.** A promise is one sentence that the code must
keep, where a break harms a user or leaks a paid resource. Model up to
three only when each one has its own promise, cfg trio, and finding.
2. **Never edit product code.** Repro tests and `observe()` instrumentation are
proposed diffs in the run directory. They land only through a separate PR
that the operator approves.
3. **Never weaken a property or the model to get a pass.** A counterexample on
the current code is a finding.
4. **A pass is bounded, and the check must have failed first.** Apply the pass
gates in step 4.
5. **Never write a run artifact inside a git worktree by default.** Traces can
carry production data.
6. **No CONFIRMED-BUG label without L3 evidence and a human ruling.**
7. **Report the bounds, the assumptions, the everystate version, and what the
model leaves out.**
## Run layout
Set `SKILL_DIR` to this skill's directory: `${CLAUDE_SKILL_DIR}` in Claude Code,
or the absolute path of `.agro/skills/state-machines` in the harness. A session
started inside a nested repository under `projects/` does not list harness
skills, so start the session at the harness root and pass the target path, or
link this directory into the project. Do not copy it.
```bash
RUN="${XDG_STATE_HOME:-${HOME}/.local/state}/agro/state-machines/<repo>-$(date -u +%Y%m%dT%H%M%SZ)"
mkdir -p -m 0700 "${RUN}"
if git -C "${RUN}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then echo "BLOCKED: run dir is inside a worktree"; fi
export RUN
```
| Path | Holds |
|---|---|
| `${RUN}/inventory.md` | Candidates and the vocabulary map, from [`assets/inventory.md`](assets/inventory.md) |
| `${RUN}/spec/` | `<Thing>.tla`, `<Thing>.cfg`, `<Thing>Broken.cfg`, `<Thing>Reach.cfg` |
| `${RUN}/checks.jsonl` | One record per run of `scripts/check.sh`, appended by the script |
| `${RUN}/traces/` | `conform` inputs and the counterexample round-trip trace |
| `${RUN}/findings.md` | The report, from [`assets/findings.md`](assets/findings.md) |
| `${RUN}/run.json` | The run record, from [`assets/run.json`](assets/run.json) |
| `${RUN}/proposed/` | Repro-test and instrumentation diffs, never applied |
Write in the target repo only when the operator asks. Then put the spec, the
cfgs, and a short README beside the modeled code, as the upstream section
"Leaving it for the next change" says. Put run artifacts in the repo only when
`git check-ignore` passes for the path and no production-derived trace is
copied.
## Workflow
### 1. Discover (stop point H1)
Follow [`references/discovery.md`](references/discovery.md). Start from
persisted state and external resources, not from a search for "state":
1. Do the schema, enum, and declared-transition passes. Include non-SQL
storage: actor or Durable Object storage, in-memory maps.
2. Do the writer pass. Find every write of each state and mark it guarded,
predicate-guarded, or unguarded. The gap between declared and enforced
transitions is the strongest signal.
3. Do the coupling pass. Name the external resource that each state claims
(VM, container, payment object). A "leaked forever" bug lives where a row is
terminal and the resource is not, or the reverse.
4. Score each candidate on six 0/1 checks: paid resource or money, racing
writers, retries or timeouts, stallable state, incident history, guard
bypass. Record the sum. Decide MODEL, DEFER, or SKIP.
5. Keep at most three candidates. Incident history alone never ranks a
candidate first. If a stallable candidate without history exists, keep
one in the inventory.
6. For the top candidate, write a one-sentence promise and its user harm. If
you cannot write the harm, SKIP the candidate.
At H1, in an interactive session, confirm the promise only if the code cannot
answer the question. With `--promise`, use the promise as given. With
`--unattended`, record the promise as UNREVIEWED and continue.
### 2. Map the vocabulary (stop point H2)
Extend the inventory row into the vocabulary map:
- Map each model action to a function and its `file:line`, and each variable
to a column, field, or key.
- Name what is atomic: a transaction, `for update`, or a lock.
- Name the environment failures that can happen: lost reply, crash, timeout,
retry.
- The model's `Next` must be a subset of any explicit transition table in the
code. Diff the two.
When unattended, record these assumptions as UNREVIEWED.
### 3. Model
Follow `references/everystate.md` for the method and
[`references/modeling.md`](references/modeling.md) for the skeleton, the cfg
trio, and the checklists.
- Use the code's literal state strings.
- Put a comment on each action that names the function it stands for.
- Bound constants to 2 or 3.
- Write `TypeOK` first. Then write the promise as an `INVARIANT` or a
`PROPERTY`.
- A liveness `PROPERTY` needs fairness in `Spec`.
- Keep `SYMMETRY` out of any cfg that has a `PROPERTY`.
- Do not use labels or subexpression selectors. everystate 0.4.2 rejects them
with exit 150.
### 4. Check
```bash
"${SKILL_DIR}/scripts/check.sh" -config spec/<Thing>.cfg spec/<Thing>.tla # main cfg
"${SKILL_DIR}/scripts/check.sh" -config spec/<Thing>Broken.cfg spec/<Thing>.tla # mutation: must exit 12 or 13
"${SKILL_DIR}/scripts/check.sh" -config spec/<Thing>Reach.cfg spec/<Thing>.tla # witness: must exit 12
```
What `check.sh` does:
- It runs the native everystate 0.4.2 binary and refuses the WebAssembly
fallback.
- It installs the pinned npm package into `~/.cache/agro/everystate/0.4.2` on
first use. Set `EVERYSTATE_BIN` to use your own binary.
- It wraps each run in `timeout` and `prlimit`.
- It always passes `-json`.
- When `RUN` is set, it appends the version, the arguments, the wall time, the
exit code, and the result to `${RUN}/checks.jsonl`.
Act on the exit code first:
| Exit | Meaning | Next step |
|---|---|---|
| 0 | `ok` | Apply the pass gates |
| 10 | `assumption` | Fix the constants |
| 11 | `deadlock` | Find out whether it is a real stall or a missing legitimate end |
| 12 | `invariant` or `invariant-init` | Retell the trace, then go to step 5 |
| 13 | `liveness` or `action-property` | `loopTo:-1` means the run stops for good. If no step is enabled at the end, that is a real stall. Otherwise fairness is missing |
| 1, 75, 124, 134, 137, 150, 151, 255 | Bad option, missing `UNCHANGED`, time cap, memory cap, parse or semantic error (including labels), config error, evaluation error | NO-VERDICT. Fix the model or the bounds |
`references/modeling.md` holds the full verified table, the simulation rules,
and `pcal` usage. Use `-simulate num=N -seed S` only when exhaustive search
times out. A simulation pass covers only the behaviours it generated.
**Pass gates.** Every PASS needs all four of these. A violation result does
not.
- `distinct > 0`.
- The witness cfg (an `INVARIANT` that says "never reaches the target state")
exits 12.
- The mutation cfg (the guard removed, or two steps reordered) exits 12 or 13.
- A rerun with one constant raised by 1 is reported.
**A failing main cfg.** The finding itself needs no gate. When the main cfg
exits 12 or 13 and the violation needs an environment action (a crash, a
signal, a lost reply), the run has no PASS to gate. Add an environment-off
control cfg: a copy of the main cfg with the environment failure turned off. Apply the four pass gates to the control cfg.
Give the witness cfg and the mutation cfg the control constants. A control
PASS shows that the violation needs the environment failure. In step 5,
retell the main cfg trace. If the control cfg fails the same property, the
violation does not need that environment failure: retell the control trace
too. If the control cfg fails another property, fix the model first.
`references/modeling.md` § 5 gives an example.
### 5. Triage (stop point H3)
Follow [`references/counterexamples.md`](references/counterexamples.md).
Retell each trace step as the code's function, with its `file:line`, its
guard, and its atomicity. Then climb the evidence ladder:
| Level | Evidence |
|---|---|
| L0 | The checker reports a violation |
| L1 | Each trace step maps to a `file:line` and the guard that allows it |
| L2 | A reachability argument that covers atomicity, how realistic the environment is, and the bounds |
| L3 | A runnable repro: a failing test from `proposed/` run in a disposable checkout, or `conform` exit 20 or 12 at the mapped step on an independent recorded run |
Give each finding exactly one label:
| Label | Requires |
|---|---|
| CONFIRMED-BUG | L3 and a human ruling at H3 |
| PLAUSIBLE-BUG | L2. With L3 and no ruling yet, write "L3 attached, awaiting H3" |
| MODEL-ARTIFACT (reason) | The guard, transaction, bound, or fairness in the code that rules the trace out. The reason is env, guard, bound, fairness, or atomicity |
| LOG-ARTIFACT | Only for a `conform` mismatch caused by logging: a missing step, a duplicate, an order tie, or dedup |
| INTENT-UNCLEAR | Only at H3, when code and model disagree and the intended behaviour is unknown |
| NO-VERDICT | Exit 1, 75, 124, 134, 137, 150, 151, 255, 21, or 22 |
| PASS-BOUNDED | Every pass gate met, with the bounds and counts reported |
**Check the code against the model.**
- When pre-existing independent logs exist (event tables, structured logs),
run `everystate conform` on them. Label them "independent but weak", and
name their ordering and dedup caveats.
- Before any conform pass counts, confirm that a known-bad trace exits 20 or
12.
- Treat `-hidden` and `-stutter` as claims about the logger. Justify each one
in the finding.
- Without conform, the report says "model-only".
- `scripts/cex-to-trace.sh` turns a counterexample into a conform trace for a
repro test. That trace is synthetic. It never counts as independent
evidence.
Each PLAUSIBLE-BUG finding must cite a proposed repro diff under
`${RUN}/proposed/`, or state why the run cannot write a repro test. The diff is a
failing test that a reviewer can apply in a disposable checkout. The diff
raises the finding to L3 only after the test runs and fails.
Unattended runs stop here. They write the findings and leave every label at
PLAUSIBLE-BUG or below.
### 6. Report and hand off
Fill `assets/findings.md` in `${RUN}` with:
- scope and promise, with the H1 status;
- the vocabulary map, with the H2 status;
- the checks, with their bounds and counts;
- the pass gates;
- the `conform` sources and flags;
- the findings, grouped by label;
- the below-model risks of each finding: the failure modes of each code path
that the model abstracts away;
- a "Not covered" section.
Then fill `run.json`. Add an entry to `calibration.confirmedFindings` only for
a CONFIRMED-BUG finding.
| Situation | Hand off to |
|---|---|
| A finding changes a lifecycle or an ownership boundary | `/architect` |
| A confirmed bug needs a fix plan | `/prd` |
| A fix exists and needs a verdict | `/audit` (implementation target) |
| An unattended run needs an operator ruling | `/escalate` |
### 6b. Fixed-model gate (optional)
When a finding goes to `/prd` and the fix plan holds design choices, use this
step. Model the fix before the fix code exists. Keep the fixed model in
`${RUN}/spec/`. Record the `${RUN}` path and the host in the fix plan.
1. Add one constant to the spec for each design choice. The old-code
constants must still give the violation exit.
2. Fill this table in the fix plan. Write one mutation row for each design
choice:
| cfg | Constants | Expected exit | Design choice gated |
|---|---|---|---|
| `<Thing>.cfg` (old code, bug witness) | The old-code values | 12 or 13 | None: the finding still reproduces |
| `<Thing>Fixed.cfg` | Every fix constant on | 0, distinct > 0 | The whole fix |
| `<Thing>FixedBound.cfg` (bound+1) | As Fixed, one constant raised by 1 | 0, with the counts | The fix at a larger bound |
| `<Thing>FixedNo<Choice>.cfg` (mutation) | As Fixed, `<Choice>` off | 12 or 13 | The fix needs `<Choice>` |
| `<Thing>Reach.cfg` (witness) | The Fixed constants, the witness `INVARIANT` | 12 | The fixed model is not vacuous |
| `<Thing><Residual>.cfg` | As Fixed, `<residual failure>` on | 12, or 13 (state the expected `loopTo`) | The fix plan leaves out this residual and documents the residual |
| `<Thing><Residual><Remedy>.cfg` | As the residual row, `<Remedy>` on | 0 | A later fix plan delivers `<Remedy>` |
3. Run each row with `scripts/check.sh`. A remedy row gates the later fix
plan, not the current fix plan.
4. A row fails when the check gives an exit other than the expected exit. A
fixed-model row that fails blocks the fix plan until the plan changes or the
row changes. Never change a row only to get its expected exit. Record the
reason for each changed row.
The fixed model verifies the design, not the code. The `/audit` step checks
the code against the model.
## Write-back
The skill never edits itself during a run.
1. Fill the retro section of `findings.md` and `run.json.retro`. The proposals
there are candidates, not edits.
2. A candidate pattern or eval case enters `references/patterns.md` or
`assets/evals/` only through a reviewed PR made with `/git`. The PR must
show:
- `scripts/eval.sh` green before and after the change;
- a manual agent-tier before and after run on the seeded fixtures, with the
bugs detected and the false positives;
- for a new pattern, at least one finding id that has L3 evidence and a
human ruling. The pattern must be generalized and contain no product
code, secrets, or production log content.
3. Holdout fixtures never live in this directory. The advisor keeps them
outside every repository.
4. Other lessons go in the PR's `## Lessons` section. Never create follow-up
issues.
5. `/rsi` becomes the gate for skill edits only once an automatable agent-tier
metric exists. Its scope is `SKILL.md` and `references/`, never
`assets/evals/`.
Version 1 is a reviewed, human-gated pattern library, plus an automated
tool-tier regression, plus a manual agent-tier eval. It does not improve
itself automatically.
## Reference
| File | Load or run when |
|---|---|
| [`references/everystate.md`](references/everystate.md) | Before the first spec: the upstream method and the `conform` value rules |
| [`references/discovery.md`](references/discovery.md) | Step 1: the passes, the scoring, the skip rules |
| [`references/modeling.md`](references/modeling.md) | Steps 3 and 4: the skeleton, the cfg trio, the exit table, the false-positive and false-pass checklists |
| [`references/counterexamples.md`](references/counterexamples.md) | Step 5: the ladder, the round trip, the `conform` flags, the finding template |
| [`references/patterns.md`](references/patterns.md) | Steps 3 and 6: invariant patterns with their evidence |
| [`scripts/check.sh`](scripts/check.sh) | Every checker run |
| [`scripts/cex-to-trace.sh`](scripts/cex-to-trace.sh) | Turning a counterexample into a trace. `--self-test` proves the round trip |
| [`scripts/eval.sh`](scripts/eval.sh) | Before and after a skill PR. Prints the passing-case count |
| [`assets/example/`](assets/example/) | The upstream Charge example plus `ChargeReach.tla` and `ChargeReach.cfg` |
| [`assets/inventory.md`](assets/inventory.md), [`assets/findings.md`](assets/findings.md), [`assets/run.json`](assets/run.json) | Run templates |
| [`assets/evals/`](assets/evals/) | Tool-tier regression cases (`cases.json`) and the seeded fixtures |
Files in this skill
- SKILL.md
- assets/evals/KillSweep.cfg
- assets/evals/KillSweep.tla
- assets/evals/KillSweepBroken.cfg
- assets/evals/KillSweepReach.cfg
- assets/evals/LeaseLeak.cfg
- assets/evals/LeaseLeak.tla
- assets/evals/LeaseLeakBroken.cfg
- assets/evals/LeaseLeakReach.cfg
- assets/evals/LeaseLeakVacuous.cfg
- assets/evals/StuckJob.cfg
- assets/evals/StuckJob.tla
- assets/evals/StuckJobBroken.cfg
- assets/evals/StuckJobReach.cfg
- assets/evals/cases.json
- assets/example/Charge.cfg
- assets/example/Charge.tla
- assets/example/ChargeBroken.cfg
- assets/example/ChargeReach.cfg
- assets/example/ChargeReach.tla
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.