TLA+ skills

TLA+-BenchSANYTLC
Nemotron-3-Ultra All specifications · with repairs 1,290/1,302328/339
Nemotron-3-Ultra Random sample · first attempt 29/4214/21
Claude Haiku 5.5 Random sample · first attempt 40/4217/21

Counts only outputs that pass the checker and a requirements review. Most remaining failures are very large specifications or benchmark defects.

Skill
---
name: tla-check
description: Write and repair executable TLA+ modules and TLC configurations from requirements, preserving the intended behavior while resolving SANY and model-checker failures.
metadata:
  version: "2.0.34"
---

# TLA+ generation and repair

Apply this complete file before generation and every repair; no supporting file is required. Return the requested TLA+/configuration payload. Preserve the behavior: SANY acceptance and TLC completion alone do not establish requirement correctness.

## Check these first: the rejections that recur most

Each left form is rejected by SANY; each right form is accepted (verified with the pinned `tla2tools.jar`). Scan the whole module for every one of them before returning it.

- Rejected: `{ e : x \in S, y \in T : P(x, y) }` (map and filter at once). Write: `{ e : <<x, y>> \in {p \in S \X T : P(p[1], p[2])} }` or filter first: `LET Ok == {p \in S \X T : ...} IN {e(p) : p \in Ok}`.
- Rejected: `{ <<a+1, b>> \in S : ... }` (expression before `\in`). Write: filter binds a name: `{ p \in S : ... }`; map binds after the colon: `{ <<a+1, b>> : <<a, b>> \in S }`.
- Rejected: `[f EXCEPT ![i] = g[i] : i \in R]`, `... \forall i ...`. Write: `[j \in DOMAIN f |-> IF j \in R THEN g[j] ELSE f[j]]`.
- Rejected: `[](P)_vars`, `[](A => <>B)_vars`. Write: `[][A]_vars` only wraps an action in `[]`; state/temporal formulas are `[]P`, `[](P => <>Q)`.
- Rejected: `Enabled A`, `enabled A`. Write: `ENABLED A`.
- Rejected: `A; B` (sequencing). Write: `A \cdot B` (action composition) or separate steps/actions.
- Rejected: `-- comment`, `// comment`, `# comment`. Write: `\* comment` or `(* comment *)`.
- Rejected: `\A x \in S : ...` or `Op(x) == ...` when `x` is a VARIABLE, CONSTANT or definition. Write: choose a fresh binder: `\A s \in S : ...`, `Op(v) == ...`.
- Rejected: `Seq == ...`, `Len == ...`, `Append == ...` with `EXTENDS Sequences`. Write: use the library operator, or rename yours (`MySeq`) everywhere.
- Rejected: `LET X == ... IN` where `X` is already defined. Write: fresh local name (shadowing is a SANY warning; warnings fail clean SANY).
- Rejected: use before definition: `Inv == ... None ...` above `None == ...`; a variable used before `VARIABLES`. Write: order the module: `EXTENDS`, `CONSTANTS`, `VARIABLES`, then definitions in dependency order.
- Rejected: `F(f) == LAMBDA y : ...`, `G(n)(x) == ...` (returning an operator). Write: return a value: `G(n, x) == ...` or a function `[x \in S |-> ...]`.
- Rejected: `RECURSIVE F(_, _(_))`. Write: `RECURSIVE F(_, _)` with value parameters only; use `f[x \in S] == ...` for recursion over data.
- Rejected: `\Sum`, `\langle`, `\neq`, `!=`, `Max`/`Min`/`None`/`Range` without a definition. Write: `+` over a recursive fold, `<<`, `#`/`/=`, and define helpers yourself, e.g. `Max(a, b) == IF a >= b THEN a ELSE b`, `Range(f) == {f[i] : i \in DOMAIN f}` (`Sequences` defines none of these).
- Rejected: `LOCAL MODULE M`, `INSTANCE MODULE M`, `INSTANCE CommunityModules/Folds`. Write: `INSTANCE M`, `LOCAL I == INSTANCE M WITH ...`, `EXTENDS Folds`.
- Rejected: `"\in"`, `"/\"` (single backslash in a string). Write: `"\\in"`, `"/\\"`; inside strings only `\\ \" \t \n \r \f` are escapes.
- Rejected: `{x : P(x)}` (no unbounded comprehension). Write: a predicate such as `\A i \in DOMAIN s : P(s[i])`, or bound it: `{x \in S : P(x)}`.
- Rejected: `[5 |-> 1]`, `["a" |-> 1]`, `{k |-> v}` (record labels are identifiers only). Write: `(5 :> 1) @@ (6 :> 2)` (EXTENDS TLC) or `[e \in {5} |-> 1]`.
- Rejected at TLC: `[c1 |-> 1, c2 |-> 2]` keyed by model values `c1`, `c2` (labels are strings). Write: `(c1 :> 1) @@ (c2 :> 2)` or `[c \in Clients |-> ...]`.
- Rejected: `WF_Step == ...`, `SF_x == ...` (identifiers may not start with `WF_`/`SF_`). Write: `FairStep == WF_vars(Step)`.
- Rejected: `CONSTANT ast` (or `x == ...`) when an EXTENDed module already declares or defines that name. Write: use the inherited name as is.
- Rejected: `x % 2 + 3`, `F(2)!3 = Len(s) > 0`, `Init => Inv /\ Inv /\ Next => Inv'`. Write: `(x % 2) + 3`, `F(2)!3 = (Len(s) > 0)`, `(Init => Inv) /\ (Inv /\ Next => Inv')`.
- Rejected: `UNCHANGED <<a, b>> \ {a}`. Write: `UNCHANGED <<b>>` (a tuple of variables only).
- Rejected: `( *` written as `(*` when passing `*` as an argument: `Fold(*, 0, s)` opens a comment. Write: `Fold( *, 0, s)` or a named operator.

## Write to the configuration's interface

When an author configuration is supplied, before writing any definition list every identifier it uses and give each one its required form in the module:

- Left-hand names of `CONSTANT(S)` entries (`Name = value`, `Name = {m1, m2}`, `NoVal = NoVal`) need `CONSTANT Name` only when no module you EXTEND already declares or defines `Name`; a configuration `=` or `<-` overrides an extended module's definition directly. Names that appear only on the right of `=` (`m1`, `m2` in `Proc = {m1, m2}`) are TLC model values: never declare them.
- A parameter the prose fixes but the configuration does not assign is a definition (`MaxNum == 20`), not a `CONSTANT`; an unassigned constant stops TLC.
- A constant that is applied to arguments, or that the configuration replaces with an operator (`IsName <- IsString`), is declared with its arity: `CONSTANT IsName(_)`. The same holds for a primitive the requirements say is supplied (hash, signature, oracle): `CONSTANT Hash(_)`, not a stub.
- `Name <- Other`: `Other` must be defined in the module with exactly `Name`'s arity, e.g. `Send(m) == ...` replaced by `MCSend(m) == ...`; never leave `Other` undefined.
- `INIT`, `NEXT`, `SPECIFICATION`, `INVARIANT(S)`, `PROPERTY`/`PROPERTIES`, `CONSTRAINT`, `SYMMETRY`, `VIEW`: each named operator must exist with zero arguments and the right level (state predicate, action, or temporal formula).
- If the configuration does not contain `CHECK_DEADLOCK FALSE`, TLC treats a reachable state with no successor as an error. When the described system terminates, include its terminal step (`Done == finished /\ UNCHANGED vars`) as part of `Next`; this is the standard idiom, not a dummy transition.
- Re-read the configuration once more after writing the module and confirm every name above appears with that form.

## Build on the modules you are given

- When the task configures, model-checks, wraps or extends a named specification, or the configuration selects or replaces names that belong to another module, write a thin wrapper: `EXTENDS ThatModule` and define only what is new (the configuration's replacement operators, bounds, extra invariants, `Spec`). Do not re-implement that module, re-declare its CONSTANTS/VARIABLES, or redefine its operators and invariants.
- A configuration override (`Name = v`, `Name <- Op`) reaches a module's declarations and definitions only through `EXTENDS`. Through `I == INSTANCE M`, `I!Name` keeps `M`'s own definition and every declared parameter needs a substitution.
- If a section "Modules available in the checker for this task" lists modules, they exist under exactly those names: use their real variable names, record fields, sentinel values and arities instead of guessing.
- A set of messages of different kinds is a union of per-kind record sets: `[type: {"a"}, src: P] \cup [type: {"b"}, val: V]`. A single `[type: {"a", "b"}, src: P, val: V]` requires every message to carry every field.

## Use TLC configuration features correctly

- Terminating algorithms: if `pc` (or any phase variable) can reach `"Done"` and the configuration does not contain `CHECK_DEADLOCK FALSE`, `Next` must include `Terminating == pc = "Done" /\ UNCHANGED vars` (multi-process: `\A self \in ProcSet : pc[self] = "Done"`). `WF` and `[][Next]_vars` do not stop TLC's deadlock error.
- `_POSSIBLE P1 P2` with `POSTCONDITION`: each listed operator must be Boolean. TLC counts, for a state predicate, every generated state satisfying it (duplicates included), and for an action predicate, the transitions satisfying it. Read the counts as `PossibleCounts == LET p == TLCGet("all:named")["s:_possible"][1] IN p["P1"] = n1 /\ p["P2"] = n2`; never `TLCGet("P1")`, extra arguments, or `TLCSet` presets.
- `SYMMETRY` names a set of permutations: `Sym == Permutations(S)` (EXTENDS TLC), possibly `\cup`-combined; a hand-built set of bijections is rejected.
- TLC checks invariants on every generated successor, including states a `CONSTRAINT` then prunes; a constraint must stop one step before a value leaves the type invariant's domain (`num[i] < Max`, not `\in 0..Max`).
- `TLCCache(expr, closure)` comes from `TLCExt`. A TLC register must be set before it is read (`ASSUME TLCSet(1, 0)`), and a side effect must sit in an evaluated position, `IF TLCSet(i, TLCGet(i) + 1) THEN v ELSE v`, never in an unused `LET`.
- In a checked `PROPERTY`, `WF_e(A)`, `SF_e(A)` and `ENABLED A` need `A` to prime declared variables. When `A` primes defined (refinement-mapped) expressions, write the fairness out: `[]<>~Guard \/ []<><<A>>_e` with an explicit state predicate `Guard` for when `A` is enabled.

## Define operators with real TLA+ symbols

- User-definable infix symbols (the complete list): `!! ## $ $$ % %% & && (+) (-) (.) (/) (\X) * ** + ++ - -- -| .. ... / // ::= := < <: =< <= =| > >= ?? @@ ^ ^^ | |- |= || \approx \asymp \bigcirc \bullet \circ \cong \div \doteq \geq \gg \leq \ll \o \odot \ominus \oplus \oslash \otimes \prec \preceq \propto \sim \simeq \sqcap \sqcup \sqsubset \sqsubseteq \sqsupset \sqsupseteq \star \subset \succ \succeq \supset \supseteq \uplus \wr`.
- Built-ins that cannot be redefined: `# ? ~> -+-> \cap \cup \cdot \equiv \subseteq \union \intersect \in = \land \times \X`. Pass them bare as operator arguments: `Apply(\cup, A, B)`.
- Not TLA+ at all: `\cdots \vdash \triangleleft \plus \mod \circledast \centerdot \intercal \dagger \boxempty \setminus \langle \neq` and Unicode glyphs. Synonyms are one operator (`\oplus`/`(+)`, `\o`/`\circ`, `\leq`/`=<`/`<=`); define only one spelling.
- Unparenthesized chains `a op b op c` are accepted only for `## $ $$ %% & && (+) (-) (.) (\X) * ** + ++ - -- ?? @@ | || \bigcirc \bullet \circ \o \odot \ominus \oplus \otimes \sqcap \sqcup \star \uplus`; parenthesize every other chain and every mix of operators with overlapping precedence (`=` with `>`, `=>` with `=>`).

## Labels, theorems, selectors and proofs

- A label is `name::` in front of an expression inside a definition body (`Op == lab:: e`), referenced as `Op!lab`. Name assumptions and theorems keyword first: `ASSUME A == e`, `THEOREM T == ASSUME ... PROVE lab:: e`, `LEMMA L == e`. Never `lab: e`, `T == THEOREM ...`, `T == ASSUME ... PROVE ...`, or a label in front of a definition.
- Selectors follow a named definition with its arguments: `F(2)!3` is the third conjunct/operand/IF-CASE part, `!<<` and `!>>` the left and right operand, `R!(c1, c2)` instantiates bound variables, and `!@` is an operator whose arity is the number of bound variables, usable only as an operator argument (`Ap(R!@, 1, 3)`). Selectors never follow a parenthesized expression.
- In `BY`/`USE`/`HIDE`, `DEF` lists only user-defined operators: never variables, keywords (`ENABLED`), fairness forms (`WF_v`) or step names; step names go before `DEF` (`BY <1>1 DEF P`). Never prime a formula containing `[]` or `<>`.

## Library modules on the checker classpath

Use these instead of re-implementing them; never redefine their operators.
- `TLC`: `Print(out, val)`, `Assert(b, msg)`, `ToString(v)`, `:>`, `@@`, `Permutations(S)`, `SortSeq(s, Op(_,_))`, `TLCGet`, `TLCSet`. `TLCExt`: `TLCCache`, `AssertError`, `PickSuccessor`.
- `Folds`: `MapThenFoldSet(op(_,_), base, f(_), choose(_), S)`. `BagsExt`: `BagAdd`, `BagRemove`, `BagRemoveAll`, `FoldBag(op(_,_), base, B)`, `MapThenFoldBag` (five arguments: op, base, f, choose, bag), `SumBag`, `ProductBag`.
- `IOUtils`: `IOExec(cmd)`, `IOEnvExec(env, cmd)` (results have `.exitValue`, `.stdout`, `.stderr`). `CSV`: `CSVWrite(template, val, file)`, `CSVRecords(file)`.
- `Functions`, `SequencesExt`, `FiniteSetsExt` and `Bags` provide `Range`, `Restrict`, `SetToSeq`, `RemoveAt`, `ReplaceAt`, `Max`/`Min` over sets and similar helpers; check the module's own text before guessing an arity.

## Preserve the contract

Identify the module/interface, imports, constants, state, initial choices, operations, safety, goals, fairness, and model parameters. Preserve supplied names, arities, data shapes, and transitions. Supplied configurations, properties, and evaluator witnesses are immutable. Never replace a property with `TRUE`, freeze state, narrow initialization, delete an operation, strengthen assumptions, or change bounds to obtain a pass. Preserve intentional nondeterminism. For a required safety bound `x <= B`, widening the invariant to `x <= B + 1` masks a counterexample; repair the implementation against the original bound.

When the task explicitly requests an invalid construction or an expected tool rejection, preserve that negative test. Confirm rejection at the intended phase for the intended reason; do not repair away the requested failure or infer intentional invalidity from a failure alone. If the task deliberately calls unary `F(_)` as `F(1, 2)`, changing that call to `F(1)` erases the requested failure. Apply the repair rules below only to unintended defects. Report requirement faithfulness separately from unchanged SANY/TLC pass/fail results.

Separate language validity from executable-model limits. Unbounded quantifiers, infinite sets/functions, and mathematical `CHOOSE` are legal TLA+; preserve them when required, including SANY-only tasks. Finiteness rules apply to domains TLC actually enumerates, not every definition. Never invent bounds or a behavioral wrapper for a utility module.

Retrieve only relevant language/modeling mechanisms, never evaluation answers or near-duplicate solutions. Transfer a mechanism, not another model's constants or behavior.

## Make a complete, resolvable module

- Match `---- MODULE Name ----` to `Name.tla`; end it with standalone `====`. Dashes only divide sections. When one file is requested and the main module only `INSTANCE`s a helper module, a nested module inside the outer module works. When the main module `EXTENDS` a helper written in the same file, do not nest it: close the main module with `====` and write `---- MODULE Helper ---- ... ====` after it (nesting is rejected). Separate top-level helper blocks do not form nested modules; supply separate named files only when the contract supports multiple artifacts. Preserve required nesting rather than flattening it.
- Balance parentheses, brackets, tuples, strings, and `(* ... *)` comments; `\*` comments end at the newline. Separate `(` from a symbolic `*` operator argument, as in `Apply( *, x, y)`; `Apply(*, x, y)` starts a comment. Preserve the operator and arity. Preserve parentheses that belong to a symbolic operator token: `(\X)` aliases `\otimes`, whereas `\X` aliases built-in `\times`; they are not interchangeable. Preserve literal backslashes and valid string escapes. Align conjunction/disjunction lists and indent their continuation expressions consistently; malformed layout can change the enclosing parse.
- `CONSTANT(S)`, `VARIABLE(S)`, and `EXTENDS` are module declarations, not expressions after `==`, inside `Init`, or inside `LET`. Place `EXTENDS` immediately after its module header, before declarations, definitions, or nested modules. Separate declarations from definitions; keywords are not helper names. A bare formula or operator call is not a module-level unit: give it a named definition, or use `ASSUME`/`THEOREM` only for an actual assumption/theorem.
- Import what expressions use: `Naturals` for natural arithmetic/ranges, `Integers` for negative values/unary minus, `Sequences` for `Append`, `Head`, `Tail`, `Len`, `SubSeq`, and `\o`, `FiniteSets` for `Cardinality`, and `TLC` only for its actual operators. Integer quotient is `\div` and remainder is `%`; `/` is real division from `Reals`. Preserve the required arithmetic and verify evaluator support; importing `Reals` does not make arbitrary real arithmetic executable by TLC.
- With `EXTENDS Bags`, binary bag addition is `left \oplus right` (ASCII `left (+) right`) and difference is `left \ominus right` (ASCII `left (-) right`). `BagUnion(S)` takes one set of bags. `SubBag(B)` takes one bag and returns its subbags; it is not binary subtraction. `BagSub` is not a standard Bags operator. `CopiesIn(element, bag)` counts occurrences of that element in the bag.
- `None`, `NULL`, `TLCModelValue`, `Min`, `Max`, `Sum`, and `Sort` are not automatically defined. Use real available definitions; do not invent a library or an unassigned constant to suppress the error. If the contract needs an absence marker, represent it consistently in the intended value domain or use a declared, configured model value.
- Check imported names before defining helpers. Avoid redeclaring a constant, variable, imported operator, or visible bound name. Prefer `Alias == INSTANCE Module WITH Parameter <- Expression` and `Alias!Operator` when importing two modules would collide. Put `LOCAL` before the whole instance declaration, as in `LOCAL Alias(x) == INSTANCE Module WITH Parameter <- x`, never after `==`; preserve export visibility. Use only dependencies present in the checker environment; never stub a missing dependency with `TRUE`.
- Avoid self-imports and circular dependencies. An `INSTANCE ... WITH` target must be a declared constant or variable of that module, not one of its defined operators. Supply every required parameter, preserving arity and allowed expression level. Respect the interface's level and Leibniz restrictions on operator substitutions; keep state/temporal dependence explicit rather than hiding it in a replacement. Missing-substitution diagnostics identify actual declared parameters: map those exact names to the intended caller expressions instead of guessing names or substituting defined operators. After `M == INSTANCE Base WITH formal <- binding`, use `binding`, not `M!formal`, for substituted constants/variables; genuine defined accessors remain qualifiable, and parameterized instances require the corresponding actual-argument binding.
- Define helpers before use. Zero-argument operators use bare names in definitions and applications (`Value == 1`, `Use == Value`), without empty `()`. Call identifier-named operators with arguments as `Op(x)`, look up functions with `f[x]`, and declare operator-parameter arities as in `Apply(Op(_), x)`. Name value formals even when unused; bare `_` is not a value formal. Keep arity placeholders like `Op(_)` and symbolic operator formals like `_+_`. Symbolic definition headers use named operands in their prefix/infix/postfix positions, such as `left \oplus right == expression`, not argument lists or standalone underscores. Preserve the required symbol, arity, and body. This header restriction does not forbid valid argument-list applications or underscore arity declarations. A zero-argument function-valued definition is not a unary operator; supply `Lookup(x) == f[x]` when a unary consumer needs one. Match declaration, definition, call, and replacement arities. Preserve required Apalache operator types in comments before their definitions, including `LET` locals, for example `\* @type: Int => Int;`. Do not invent typed headers such as `Op(x) :: Type == ...` or remove required annotations.
- Use module qualification `Alias!Op` only for an actual instance. Subexpression selectors instead begin with a defined name (with arguments) or an in-scope proof-step name, followed by valid label/position selectors, never an arbitrary or parenthesized expression. Name that expression first, preserving its body, label scopes and parameters. For an operator defined inside a named/labeled `LET`, use `Root!:!Inner(args)` after root labels; without `!:` the identifier selector refers to a label.
- `LAMBDA` supplies an operator argument where the receiving interface expects one; it is not a first-class value or function constructor. Use `[x \in S |-> expression]` for function values and named operators for operator arguments. An expression cannot stand in for an operator merely because its value is a function.
- For operator recursion, write `RECURSIVE Op(_)` before `Op(x) == ... Op(smaller) ...`; match the number of underscores to its arity. A recursive function definition instead has the form `f[x \in S] == ... f[smaller] ...`. For TLC-evaluated calls, check base cases and a well-founded decrease; the mathematical function's whole domain need not be finite. Do not invent `RECURSIVE f[_]`.
- For recursive operator-parameter arity errors, check declaration, scope, and pinned-checker support. If recursive calls keep the operator fixed, consider an equivalent `LET`-local recursive helper with ordinary value formals that captures it, preserving the public signature and domains. Never erase operator arity or invent nested `_(_)` placeholders in `RECURSIVE`; report an unsupported required interface.
- PlusCal algorithms inside comments do not define TLA+ state or operators. Translate PlusCal before checking it, or provide the complete requested TLA+ implementation. Do not refer to generated names such as `pc`, `ProcSet`, or `vars` without their actual declarations/definitions and transitions.
- Named `THEOREM`, `LEMMA`, and `COROLLARY` declarations use `Name == assertion`, without operator-style parameters after the name. Bind inputs within the assertion using the required quantifiers or `ASSUME ... PROVE ...`, for example `ASSUME NEW CONSTANT x, NEW CONSTANT Op(_) PROVE ...`. Preserve theorem names, domains, declaration levels, arities, assumptions, and proof obligations; never replace a required theorem with a plain operator definition to obtain a pass.
- Attach `BY ...` as an unnumbered leaf proof to its assertion or `QED`, never as a bare numbered `BY` step. Numbered assertions and `USE`/`HIDE` instructions remain valid steps. A correctly leveled `QED` step (for example, `<1> QED`) terminates its matching structured proof; do not append a bare `QED` to a leaf or closed nested proof. Resolve actual visible proof labels and steps with their required arguments; label parameters must be permitted by the enclosing binding scope. `HIDE` facts name a theorem, assumption, or proof step, not an arbitrary expression; use `DEF` for definitions. Preserve the proof hierarchy and obligations; do not invent labels or remove obligations to silence SANY.
- Unlike an assertion, `HAVE`, `TAKE`, and `WITNESS` take no subproof; preserve the current goal, assumptions, and obligations when choosing a proof step. `TAKE` binds a universal goal; `WITNESS` supplies a value for an existential goal; `PICK` introduces witnesses with justification. `FIX` is not a proof command; it may still be an ordinary declared identifier.
- In `BY`, `USE`, and `HIDE`, separate the comma-delimited fact and definition lists with `DEF`, without a comma before it: `BY Fact1, Fact2 DEF Op1, Op2` or `BY DEF Op1`. Preserve the actual facts, definitions, and obligations.

## Use the right value and binding grammar

- `==` defines an operator; `=` states equality, including `x' = expression`. Do not use assignment syntax such as `:=`.
- Write inequality as `#` or `/=`. Use actual TLA+ spellings, including `|-` and `\` (set difference), not LaTeX `\vdash`, `\setminus`, `\neq`, or programming-language `!=`. Preserve each declared operator's spelling.
- `{a, b}` is a set; `<<a, b>>` is a tuple/sequence; `[key \in Keys |-> value]` constructs a function; `[Keys -> Values]` is a set of functions. `A \union B` is binary union; `UNION Sets` is unary union of a set of sets. Preserve the intended operand shape and arity. Bare `[]` is not an empty value; an empty function still needs `[key \in {} |-> expression]`. Temporal `[]P` takes a formula. Keep scalars, sets, functions, and operators distinct throughout an expression.
- Construct records with `[field |-> value]`, record types with `[field: Values]`, and access `record.field`. Record labels must be bare identifiers denoting literal string keys, never quoted strings, numbers, or expressions. For arbitrary string, numeric, or computed keys, use `[key \in Keys |-> value]` over the intended key set and access `f[key]`. Labels are not values of same-named variables/operators and must be unique within the constructor. Record types require sets as field domains; record values require values. Reachable records must contain the fields read.
- A sequence is a function over `1..Len(q)`, not a set of its elements. Use `i \in DOMAIN q` to range over indices and `{q[i] : i \in DOMAIN q}` for its value set. Do not write `item \in q`, use zero-based indices, or compare a tuple directly with an integer.
- `{x \in S : Predicate(x)}` selects elements; `{Expression(x) : x \in S}` maps them. Bounded and unbounded quantifiers both need a colon: `\E x \in S : Action(x)` or `\E x : P(x)`. Bind fresh unprimed identifiers, or tuple patterns where permitted, never primed expressions. Keep state primes in the body, as in `\E next \in Values : x' = next`; preserve required domains, nondeterministic choices, and value versus temporal quantification. Use finite bounds for TLC enumeration without narrowing required logical domains. Nest dependent bounds: `\E i \in S : \E j \in T(i) : P(i, j)`; sibling domain expressions cannot use each other's bound identifiers. Parenthesize quantified alternatives so a later disjunct is not captured by an earlier binder.
- Scope locals as `LET Helper(x) == expression IN body`; separate multiple `LET` definitions with whitespace, never commas between definitions. Bound identifiers must be visible where used. Give nested quantifiers, function constructors, and set comprehensions distinct binder names; do not reuse a visible name or a reserved keyword. Parenthesize mixed arithmetic whose precedence ranges conflict, such as `(a % b) + c`, using the grouping required by the specification. Also parenthesize mixed conjunction/disjunction/implication, nested quantifiers, `IF`, and `LET` bodies; do not assume programming-language precedence.
- Complete `IF ... THEN ... ELSE ...` syntactically. Nest `ELSE IF ... THEN ... ELSE ...` for multiple tests, preserving branch order; `ELSIF` is not a TLA+ expression branch. For TLC-evaluated `CASE`, cover every reachable input; use `OTHER` only for an intended fallback. `CASE` has no `ESAC` or `END` terminator. Test a function's domain, a sequence's nonemptiness, and a record's fields before evaluating a partial operation. Use an `IF` around a partial value expression; arbitrary Boolean operand order is not a safe evaluation guard.
- For TLC evaluation, conditions, guards, assumptions, invariants, and action results need Boolean values. Module `ASSUME` bodies must also be constant-level (0). Action or temporal syntax can raise the level even with constant operands; recheck the level of a selected subexpression. Preserve required test coverage when correcting a level mismatch. Guard evaluated division/modulo against zero and preserve supported numeric types and ranges. An undefined value, failed `Assert`, or false `ASSUME` requires correcting the violated contract or reporting inconsistent fixed inputs, not replacing it with a convenient truth value.
- `CHOOSE` selects one value; it does not enumerate nondeterministic transitions or assert that a witness exists. Preserve required mathematical bounded/unbounded choices. When TLC must evaluate `CHOOSE x \in S : P(x)`, provide an enumerable finite domain and an established witness without inventing either. Use existential actions for nondeterministic transitions, bounded when TLC enumerates them.

## Construct complete states and atomic transitions

- When TLC enumerates initial states, give every variable an executable value or membership in an intended finite set. Selecting an invariant in the configuration does not initialize variables; a predicate explicitly included in `Init` can constrain them. Initialize a per-actor map with `[a \in Actors |-> initial]`, not a scalar or a function type.
- In every action branch, assign each next-state variable once or frame it with `UNCHANGED`. Conjuncts are simultaneous constraints, not sequential statements. Updating a variable and also including it in `UNCHANGED` is contradictory. Revisit every branch when adding state.
- Use `Guard /\ Updates` to enable an action. `Guard => Updates` becomes true when the guard is false and can leave the successor unconstrained. Guards normally inspect current state; use primed expressions only for deliberate next-state relations.
- A functional update is `f' = [f EXCEPT ![key] = newValue]`; a nested record update can use `![key].field`. Within the update's right side, `@` denotes that selected old value. Do not use `@` outside `EXCEPT`. Constraining only `f[key]'` leaves the rest of the function unframed; use a whole-function update. Keep its domain distinct from its values.
- Keep all variables in `vars == <<...>>` and use that tuple in `Spec == Init /\ [][Next]_vars`. State invariants contain current-state predicates; action relations may contain primes; temporal formulas belong in properties. Do not prime an already primed, action-level, or temporal expression.
- A temporal operator applied to an action requires its proper action form: `[][Action]_vars` for always allowing the action or stuttering, and `<><<Action>>_vars` for eventual nonstuttering action. These forms have different meanings; choose from the contract. Quantified temporal formulas cannot have action-level bounds. Conjoin required `WF_vars(Action)`/`SF_vars(Action)` into the named temporal specification; preserve the action and fairness strength, never leave fairness bare at module scope or invent an assumption. Verify TLC support when checking; report unsupported formulas without weakening them.
- Preserve phases and interleavings: start, completion, and reset need their actual enabling state. Phase flags must prevent illegal repetitions without removing legal choices.
- For deadlock, inspect the last state's actual guards and frames. Add a guarded `UNCHANGED vars` terminal branch only when termination/quiescence is intended. Temporal stuttering in `[][Next]_vars` does not disable TLC's deadlock check. Add fairness only when the contract requires that scheduling assumption.

## Keep the required model finite and its configuration exact

- TLC enumeration needs finite, enumerable domains under the supplied parameters. `Nat`, `Int`, `STRING`, and `Seq(Items)` may appear in mathematical definitions and type predicates; do not enumerate them as state choices. Initialize a concrete sequence or enumerate `UNION {[1..n -> Items] : n \in 0..Limit}` only when the task already requires that bound.
- Checking a type invariant does not constrain `Next`. Guards and updates must preserve the intended bounds. Watch counters, histories, queues, powersets, maps, and process products for state growth. Do not add a new bound, state/action constraint, symmetry set, or `VIEW` to conceal behavior. Temporary smaller models are diagnostic; acceptance uses the required model. Check liveness without symmetry.
- If symmetry is already authorized, its operator evaluates to a set of permutation functions, not the set of interchangeable values. Verify that initial states, transitions, and checked properties respect those permutations; otherwise do not use that reduction.
- Distinguish a model-value symbol from a string and either from a set: the configured scalar `actor` is not the set `{actor}`. Match every declared constant and operator parameter to its supplied value/replacement; do not introduce unassigned constants.
- For a generated configuration, choose `SPECIFICATION Spec` or `INIT Init` plus `NEXT Next`. List named Boolean state operators under `INVARIANT` and named temporal operators under `PROPERTY`. Define `NoGoal == ~Goal` in the module; `INVARIANT ~Goal` is not a configuration expression. A definition is unchecked unless the configuration selects it.
- Configuration assignment `Name = Value` and replacement `Name <- Operator` have different purposes. Replacement operators must exist and have the target's required arity and level. Unlike `INSTANCE WITH`, configuration replacement can override a defined operator. Use configuration syntax, not module definitions or arbitrary expressions, and match every selected behavior/property name to the module's interface.
- For `POSTCONDITION`, verify the pinned TLC interface: it expects a zero-argument operator, and startup constant evaluation can replace a constant body with a value the interface rejects. Preserve the intended check. `TLCGet` keys must be supported in the current mode; distinguish built-in statistics from register storage initialized by `TLCSet` in the relevant worker context. Do not invent predicate-name selectors, fabricated metric values, or trivial postconditions.
- Preserve fixed configuration bytes. An empty or malformed supplied fixture, unresolved replacement, unsupported feature, or unavailable dependency is a reported limitation, not permission to fabricate a new fixture or dummy model.

## Separate safety, goals, and progress

Check safety independently from goal reachability. If either forbidden condition `A` or `B` makes a state unsafe, safety requires `~A /\ ~B`, not `~A \/ ~B`. Check each clause in initialization, every action branch, and the actual witness states; do not rely solely on a generated `Safe` predicate. A dedicated `NoGoal == ~Goal` probe should fail specifically because the actual task's `Goal` became true. A violation of type/safety, an arbitrary invariant, a temporal property, or a composite `Safe /\ ~Goal` is not a solution witness. A final-state predicate must include its terminal/phase condition; do not assert the desired final result over every intermediate state. An initial-state violation counts only if the actual task permits an initially satisfied goal.

Express `Goal` as the requested property over the current state and all required inputs, not equality to a memorized solution or a single favorable example. Inspect the witness's initial state, every legal step, and its final goal. Distinguish existence of one solution from eventual success on every fair behavior (`<>Goal`) or a strategy against all environmental choices. A universal claim requires its corresponding input/environment coverage. Preserve independent refinement/postconditions when supplied; a valid trace or finite one-way refinement is not whole-model equivalence.

For a behavioral task, reject empty, frozen, or stuttering-only models. Require actual state change and independent witnesses/action coverage for each requested operation, not merely a state-count threshold. `Next == Up \/ Hold` can pass type and state-count checks while omitting required `Down`; check a legal `Down` witness independently. If a fixture requires an unchanged Boolean `x`, changing it to `x' = ~x` or adding a progress-only counter violates its contract. Static utility modules may have SANY/evaluation coverage only; do not invent dummy transitions to inflate TLC coverage.

## Emit complete artifacts

Follow the requested output format exactly. Return the complete module and any requested configuration, keeping configuration text separate from TLA+ text. A repair returns the complete replacement unless a patch was requested. Never leave placeholders, ellipses, prose inside code, or an omitted tail. Fit the complete artifact within the output budget by removing commentary and redundancy, preserving all required behavior. Check delimiters, the enclosing module's final `====`, every identifier's declaration/scope, and every call's arity before returning it.

## Diagnose, repair, and validate

1. Run the repository validator with its pinned tools and explicit time budget. For direct use: `java -cp "$TLA2TOOLS_JAR" tla2sany.SANY Model.tla`, then, when a model/configuration is applicable, `java -cp "$TLA2TOOLS_JAR" tlc2.TLC -workers 1 -config Model.cfg Model`. Keep semantic/level analysis and warnings enabled. On supported releases, SANY's `-error-codes` helps; older releases can exit zero after semantic errors, so inspect diagnostics, including multiple-definition warnings.
2. Repair the earliest unintended causal error and its enclosing expression. Parse failures often originate at the preceding delimiter or quantifier. Unknown operators require a real import/definition, correct arity, or correct scope. Level errors require separating current-state, next-state, and temporal formulas.
3. For incomplete states, identify the exact unassigned variable and branch. For evaluation/type/domain failures, inspect the concrete values and restore the correct data shape or precondition. For invariant failures, repair the first illegal transition or incorrect initialization; do not weaken the property. For liveness, inspect the lasso/stuttering suffix and distinguish starvation from repeatedly disabled actions.
4. Re-run SANY after every edit and applicable TLC checks after SANY is clean. Use the fixed requirements, current complete candidate, and fresh diagnostics. Compare actual source/configuration hashes and changed expressions: an unchanged answer is not a repair. If a local patch repeats the same failure, rewrite the causal expression/action using the explicit forms above rather than accumulating speculative clauses. Preserve immutable configurations while comparing them.
5. For tasks requiring valid modules, require clean SANY diagnostics. A safety/model-checking pass requires completed exhaustive TLC of the requested configuration, nonempty initial states, a drained queue, and the required behavioral coverage. A goal probe instead requires its specific, inspected goal counterexample; it can stop before exhausting the queue. Keep deadlock checking on; TLC's `-deadlock` flag disables it. Timeouts, truncation, interrupted searches, unsupported formulas, and resource exhaustion are not passes.

Retain failed candidates, tool versions, configuration hashes, finite parameters, property names, state counts, and actual outcomes. Stop at the authorized attempt/time budget and preserve unresolved failures. No finite benchmark or prompt can guarantee arbitrary future SANY/TLC success.

## Distinguish tool failures and unavailable checks

Use a separate working directory, Java temporary directory (`-Djava.io.tmpdir=...`), and TLC state directory per checker invocation. Concurrent extraction of standard modules into shared temporary files can produce false missing/corrupt-dependency errors. Verify module paths, filenames/case, permissions, tool versions, and dependency availability before changing a candidate for a parser exception or lookup failure; retry the identical artifact in an isolated checker to identify infrastructure failures.

Bound checker runtime, memory, and diagnostic output. Stream large output to bounded artifacts; preserve the first error, useful tail, termination reason, and any truncation flag. Resource exhaustion, runaway diagnostic output, or a terminated checker is unresolved evidence, not a model violation or a pass. Fix runaway formatting/printing separately from state-space growth. Missing trusted configurations, incompatible fixtures, and unsupported checker features remain explicitly unmeasured or blocked. Covering a diagnostic family with instructions does not establish that the family has been fixed.

## Sources

Original guidance, consolidated 2026-10-17. Language forms follow Lamport's [TLA+ summary](https://lamport.azurewebsites.net/tla/summary.pdf) and [TLA+2 guide](https://lamport.azurewebsites.net/tla/tla2-guide.pdf); model-checking details follow [Specifying Systems](https://lamport.azurewebsites.net/tla/book.html) and the [TLC configuration reference](https://docs.tlapl.us/using%3Atlc%3Aconfig_file). Apalache operator annotation placement follows [ADR-004](https://apalache-mc.org/docs/adr/004adr-annotations.html). Sources are optional verification, not additional skill instructions.

The requested public skills informed the original workflow: [AgentSkills](https://github.com/tlaplus/AgentSkills/tree/f2adb5e4e2c6250661d1aff8bcc0b9f92d5442ec) (MIT), [Brian Wu](https://github.com/brianwu02/tla-claude-code/blob/56fdc3578e738a749edfb7e448cdddb5639ef6d1/skills/tla/SKILL.md) (MIT), and [model reduction](https://github.com/santosomar/general-secure-coding-agent-skills/blob/47d56bbc24dc4560c0afe546edbb34973da79391/skills/verification/tlaplus-model-reduction/SKILL.md) (declares Apache-2.0; no root license at that revision). No upstream worked answers are copied. Preserve URL/revision/license provenance for any separately retrieved material.