/libpetri:petri-net-designfrom libpetri
Design, review and debug Coloured Time Petri Nets using libpetri (Java, TypeScript, Rust, Python). Models workflows, agents, protocols, pipelines and session lifecycles as provable nets with typed places, structural decisions, and bounded concurrency.
Ships in libpetri. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are helping someone model a real system as a Coloured Time Petri Net and keep it provable while it grows. The net is not a diagram of the program. The net is the program: places hold typed data, transitions do work, arcs declare flow, timing makes deadlines part of the model, and the marking is the state.
If the net must reason about it, it has to be structural. A place, an arc, a cardinality, a name equality. Anything else (a field in an action, a map on the side, a boolean in a session object) is invisible to the firing rule and invisible to the verifier, so it can neither coordinate correctly nor be proved.
Almost every bad libpetri design is one of two moves:
When you review a net, look for those two first.
Work in this order. It is much cheaper than reordering later.
Place<Order>, Place<DraftReply>, Place<ToolCall>. One concept per place.Xor output spec, never an if inside an action that the model cannot see.Then iterate: each new feature is new places and transitions, and the proofs you already wrote tell you immediately when it broke something.
The marking is owned by one logical orchestrator thread, without locks. Actions never touch it: an action reads its consumed inputs and read-arc values from the context and declares outputs through the context. A transition's preconditions are checked and consumed in one indivisible step, which is the whole point.
Anywhere else you can store state, you can read it, and that read happens outside the indivisible step. A session object, a context bag, a cache, a static field, an actor's instance state, a database row, "just this one flag" on the service: each is a check-then-act gap, the exact bug you adopted a Petri net to remove. So:
session.state map that actions poke at.The tell in review: if you can describe a bug as "we checked X and by the time we acted on it, X had changed", X was in a store and belonged in a place.
Typed places are the only compose-time contract you get: they let the compiler catch a mis-wired composition, and they make the exported diagram read as a process rather than plumbing. A single untyped everything-bag place threaded through the net throws both away.
Colour describes what the work is. It is not a coordination mechanism: verification is value-blind, so nothing that depends on a token's value can be proved.
There are no guards and no per-token value predicate anywhere in the model, deliberately. Model a decision as either
Xor output spec on the producing transition, where the action picks a branch and the verifier sees every branch as a possibility.The verifier reads production from the output spec, never from the action. If the action can write somewhere the spec does not declare, the model is a lie about the program and a Proven on it is worth nothing.
The most reusable pattern in this document:
No action ever asks "do I have budget left". The decision lives in the marking, so it is race-free and checkable: PlaceBound(budget, N) is provable, and so is "the fallback is reachable".
The same shape covers concurrency limits (a permit place with N tokens, consumed on start and returned on completion, which gives inFlight + permits = N for free), mutexes (N=1), pool capacity and rate limits. Prefer it over any runtime concurrency-limit option: a limit the verifier can see is worth more than one it cannot. A leaky-bucket rate limiter is a permit place plus a timed refill:
PERMITS seeded with `burst` unit tokens
CALL: In.one(REQUEST), In.one(PERMITS) -> IN_FLIGHT
DONE: In.one(IN_FLIGHT) -> RESULT
REFILL: read(BUCKET_TICK), delayed(interval) -> PERMITS (up to `burst`)
REJECT: In.one(REQUEST), inhibitor(PERMITS) -> THROTTLED
Make it a subnet with REQUEST, ADMITTED and THROTTLED as ports; instantiate it per dependency with its own rate, or fuse the permit places of several instances when the quota is shared. references/composition.md works both cases.
There is no rollback. When an action fails, its consumed tokens are gone. Any failure the system must react to is an explicit Xor branch into a failure place; "the exception propagates" is not a design. Decide per transition whether a failure needs a retry path, a dead-letter place or a compensating transition, and if so, put it in the output spec.
A timeout branch excludes the late output, it does not cancel the work. Side effects of an abandoned action still happen. If cancellation matters, model it (an inhibitor arc on a cancel place), do not hope for it.
A token nobody can consume is a hang in production and an unbounded place in the model, and unbounded places stop proofs from closing. Whenever you add a place, answer: who consumes this, and are they enabled in every state where this token can exist?
Xor leg emitting "no result this time" is still a token. Give it a drain, even a no-op one, or it accumulates one token per miss for the life of the net.Xor of And, not And of Xor. Two independent Xor outputs can produce a combination your code never produces, and the analysis will treat it as reachable. One Xor whose legs are complete output sets makes structural branches exactly the runtime outcomes.xor(realOutput, voidSink) and give the sink a drain. Validation succeeds only when exactly one branch of the spec claims exactly the set of places the action wrote; an extra write into a declared place that the selected branch did not ask for is a violation. And is unordered.Xor leg chosen by hidden action state is unprovable. If the action decides "is this the last result", the analysis will take the other leg on the last result and strand the batch. The provable encoding is a pending-marker place per outstanding job plus an inhibitor arc on it.read(X). A read arc is a precondition: when X is empty, usually the normal case, the transition never fires. Use a pair: consume X at high priority, inhibited by X at low priority.The executor consumes inputs before the action runs, does not restore them on failure, and commits outputs only on normal completion. So split each action into a part that computes and may throw but writes nothing, and a part that writes the complete output set once and cannot throw. An action that writes in a try and again in the catch produces duplicate tokens and both legs of an Xor, invisible to any proof. Wrap the whole body, including metrics and logging: an unguarded observability call between consume and write destroys the token when it throws.
The executor can fire that inhibitor or reset while an action that writes the tested place is still running, so the verifier splits each such writer into a start and a complete:<t> step (fact 6 below). Keep the design; expect the split in traces, and keep ν-joins and mints from writing the tested places, since those cannot be split.
A cancellation flag read inside an action is the classic stall: the action returns early, tokens sit in the in-flight place forever, and the marking never learned about the cancellation.
Tracing, logs, metrics, audit and live debugging all hang off an event-store decorator wrapping the net's event stream. Do not wrap actions or invent an execution-context hook for observation. Events are an observation channel, never a data-flow channel: if a downstream step needs a value, it travels as a token.
With inhibitor arcs this model is Turing-complete. Almost every "libpetri cannot express X" is "I have not found the places yet". Work the topology before proposing a new API or escape hatch:
| "I need..." | Structure |
|---|---|
| streaming output | per-chunk injection into an environment place, read arc on the generation token for staleness |
| cancel mid-flight | inhibitor arc on a cancel place, reset arcs for cleanup |
| pause and resume | an urgent transition blocked on a resume place |
| bounded retry | budget place plus inhibitor fallback |
| rate limit or mutex | permit place with N tokens |
| a time window | window timing plus a read arc on the state that must hold |
| fan out and rejoin | N transitions plus a cardinality join, or ν correlation when groups overlap |
| a tool or external service | its own subnet with typed ports; dependencies are shared places wired at composition |
| per-step observation | event-store decorator |
Genuine gaps are limited to observation and persistence seams that do not change firing semantics. A helper that lets an action emit tokens mid-flight outside the output spec is not a gap; it is the hole this model exists to close. A flat list of tool calls dispatched inside one action discards every reason to use this model.
| Arc | Requires | Consumes | Use it for | Classic misuse |
|---|---|---|---|---|
| input | yes | yes | ownership transfer: this work is mine now | draining with all() when one() would do |
| output | no | produces | the declared effect surface the verifier reads | declaring outputs the action only sometimes writes |
| inhibitor | absence | no | negative precondition: pause, kill switch, not yet | using it as a mutex where a permit token is the honest model |
| read | yes | no | shared state many transitions consult | expecting it to serialise (readers never conflict) or to see every token (it peeks the front) |
| reset | no | yes, all | cleanup, cancel, purge stale state | putting it on a place that carries a conservation law |
Consumption is the only ownership primitive, and it is race-free because the match is part of the firing rule. If two things must not happen at once, make them consume the same token, not read the same flag. Two input arcs on the same place are rejected; use one arc with a cardinality.
Prefer one() and exactly(n) over all() and at_least(n). Draining arcs destroy the linear conservation laws that make proofs converge (see references/verification.md). Drain only when the domain means "take everything", and into a place no invariant needs to weigh.
| Timing | Interval | Enforcement |
|---|---|---|
immediate | [0, inf) | fires as soon as enabled |
delayed(d) | [d, inf) | lower bound only |
deadline(by) | [0, by] | hard: force-disabled past the bound plus a tolerance (default 5 ms, configurable, 0 is strict), emits a timed-out event |
window(e, l) | [e, l] | hard, same reaping |
exact(at) | [at, at] | soft: never force-disabled, fires at the first opportunity at or after the target |
The clock starts at enablement and restarts on re-enablement; partial elapsed time is discarded. That includes the gap inside one firing: when another transition takes a token this one consumes or reads and puts one back, or drains the place with a reset arc, the clock restarts unless the place kept enough tokens. Good for refresh and cancel semantics, a trap for deadline modelling. To keep a clock running while another transition uses a shared token, let that transition read it instead of consuming it.
exact() is a logical instant for simulation and proof, not a real-time guarantee. For a wall-clock lower bound use delayed; for a hard bounded window use window.
The clock is injectable per executor (TIME-015), and the injected clock owns the wait as well as now, so timed nets test deterministically under virtual time and run inside a host that drives time itself (a durable workflow runtime, a replay). Action timeout(...) is the exception: it elapses in real time, so a net that relies on it is not fully virtualizable.
The primary-and-fallback idiom is timing plus priority: primary at high priority and immediate, fallback at low priority and delayed. The fallback is ready only if the primary did not take the token first. Use it for silence recovery, escalation and slow paths.
Ready order is priority descending, then enablement time, then declaration order. Priority is a scheduling policy, and by default no analysis sees it. If a safety argument depends on "the high-priority transition always wins", make the exclusion structural (inhibitor arc or permit) or opt into conflict-aware priority semantics explicitly.
An environment place marks the world boundary. Injection is thread-safe from anywhere and wakes an idle orchestrator immediately.
env -> transition -> place chain makes any bound on that place genuinely violated. Put a permit place in front of the consuming transition, as a real system would.Each cycle: process completions, process external events, update enablement, enforce deadlines, fire ready transitions, await work.
Deposits made during a pass are not visible to firing in that same pass. If a high-priority transition consumes a token and its synchronous action refills the place immediately, a lower-priority transition waiting on that place stays disabled until the next cycle. This binds counts as well as presence, and draining arcs too: a drain firing later in the same pass takes only what was there when the pass began. When a net behaves one cycle later than you expected, this is usually why.
Treat properties as tests. Write the first one with the first subnet.
What you can check: deadlock freedom, termination at a sink, mutual exclusion, place bounds, unreachability, and for correlated nets the branch-place bound and "every fork is eventually joined or dead-lettered".
The two stopping properties are different claims. DeadlockFree is strict: it fails on a quiescent marking that holds a token outside the declared sink places, so it answers "is anything stranded". TerminatesAtSink fails when a quiescent marking has no declared sink marked. They invert on the empty marking: a fully drained net is deadlock-free and does not terminate at a sink. Declare every place where the net legitimately rests, because one you leave off reads as a stranded token. For a designed halt or pause marker, under which interrupted work legitimately stays where it was, declare conditional sinks (sinkPlacesWhen(marker, ...places)).
Facts that shape designs (details, numbers and flags in references/verification.md):
Proven holds for the timed net too; Violated there can be spurious, because the abstraction lets an action route anywhere its spec allows. Read the counterexample before believing it, and read counterexampleTiming; timedCounterexampleCheck(true) asks the timed state-class graph whether the trace survives timing, without ever changing the verdict.result.route says which route answered. A graph cut off at its class budget still reports a violation found in the part it explored; it never reports Proven.Unknown is information, and the timeout is the first suspect. Raise it before concluding anything. Then read the report before reaching for a flag: Dropped invariant: / Dropped semiflow: lines naming a draining or reset place point at semiflowInvariants; a quiescence proof on a pipeline points at stateEquation(true); otherwise bound something, declare the budget place, declare sinks, or move a draining arc.t then complete:<t>, with inflight:<t> marked in between; a lower-bound QuiescentCount beside a terminal and conflict priority split more. A ν-join or a writer into a coloured place cannot be split, and the verdict is Unknown naming it. assumeAtomicFiring(true) reads every firing as one step and says so in the report. An inhibitor on a transition's own output is no mutex once two transitions share it, and on Rust not even for one transition; use a permit token.There are only three honest statements about a property, in code comments, commits, design documents and conversation:
Never call a net correct, safe, race-free or deadlock-free because you read it and it looked right; that is the failure mode this model exists to replace. In tests, never assert assertFalse(isViolated()): it is also true for Unknown, so a proof lost to a timeout passes silently. Assert Proven.
Two limits belong in the same breath:
Read references/verification.md before tuning anything: the route split, the exact-gate rule that decides proof cost, the semiflow option, siphons and traps, environment modes and the vacuity guard, open-net contracts, and wiring proofs into a build.
Whole-net proofs of a large composed net either finish fast because the design is good, or come back Unknown after minutes because it is not. Neither is a usable design-time check. Use this order:
DeadlockFree with all resting places declared as sinks, plus accounting: model arrivals through a generator and assert that outcomes equal inputs at quiescence. DeadlockFree alone passes while a reset silently loses events.When several designs pass, compare them with the sensors in references/metrics.md, not with size. Correct designs are usually bigger. To generate, check, compare and present candidate nets before writing production code, use the design harness described in references/harness.md.
The files below sit next to this SKILL.md; read them from this skill's own directory.
| Read this | When |
|---|---|
references/verification.md | any proof question: what is checkable, why a query is Unknown, actions in flight and complete:<t> steps in a trace, keeping proofs cheap, open-net contracts, CI wiring |
references/composition.md | building or reusing subnets, ports versus channels, instantiate versus compose, fusion, the cross-language place-equality divergence |
references/nu-nets.md | correlating parallel work by identity: minting, matching, the tie-break, the budget place, the fragment rules the exact routes require |
references/metrics.md | comparing designs that all pass their proofs: the check order, lint rules, the sensors that rank correct nets, what not to count, and precise reset rules |
references/harness.md | designing a net before implementing it: contract, candidates in TypeScript, checks, the comparison artifact, porting the chosen net to the project language, and proving the port equals the design |
references/patterns.md | worked topologies from a production system: per-session nets, turn handling, barge-in, budgets, queue draining, and changes that made real nets provably deadlock-free |
references/lang-java.md and the other lang-*.md | the per-language facts that change a design decision: API spellings, snapshot/restore, threading |
libpetri's requirement specification is the normative source for semantics; its registry is spec/00-index.md, at <repo-root>/spec/00-index.md inside a libpetri checkout, otherwise https://github.com/debe/libpetri/blob/main/spec/00-index.md. Cite requirement IDs (VER-013, NU-024, MOD-041) when you claim something about semantics, and read the index rather than trusting a remembered count. If you can open neither, say the claim is unverified rather than inventing an ID.
DeadlockFree asserted where "some sink got marked" (TerminatesAtSink) was meant.Proven.Xor leg whose choice lives in action state the model cannot see.Unknown, or a net called correct on the strength of having read it./ inside a place, transition or subnet name.Run this before calling a net design done.
Xor leg is a complete output set, and every action decides before it emits its output set exactly once.mintTransitions).DeadlockFree plus accounting) before any whole-net proof is attempted.DeadlockFree for "nothing stranded", TerminatesAtSink for "we reached a sink").Proven, and every correctness claim names property, verdict and marking.evals/evals.json (opens in a new tab)harness/examples/guard/contract.ts (opens in a new tab)harness/examples/guard/gate.ts (opens in a new tab)harness/examples/guard/hub.ts (opens in a new tab)harness/examples/guard/shared.ts (opens in a new tab)harness/package-lock.json (opens in a new tab)harness/package.json (opens in a new tab)harness/src/artifact.ts (opens in a new tab)harness/src/cli.ts (opens in a new tab)harness/src/dot.ts (opens in a new tab)harness/src/equivalence.ts (opens in a new tab)harness/src/gates.ts (opens in a new tab)harness/src/net-utils.ts (opens in a new tab)harness/src/sensors.ts (opens in a new tab)harness/src/types.ts (opens in a new tab)harness/src/units.ts (opens in a new tab)harness/test/artifact.test.ts (opens in a new tab)harness/test/equivalence.test.ts (opens in a new tab)harness/test/fixtures-voice-step5.ts (opens in a new tab)harness/test/fixtures.ts (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Java, TypeScript, Rust, Python
npx claudepluginhub debe/libpetri --plugin libpetriOther plugins' skills for the same job