Skip to main content

meerkat_machine_codegen/
artifacts.rs

1use std::cell::{Cell, RefCell};
2use std::collections::{BTreeMap, BTreeSet};
3use std::fmt::Write;
4use std::rc::Rc;
5
6struct InfallibleWrite;
7
8impl InfallibleWrite {
9    fn expect(self, _message: &str) {}
10}
11
12fn push_fmt(out: &mut String, args: std::fmt::Arguments<'_>) {
13    let _ignored = out.write_fmt(args);
14}
15
16fn push_line(out: &mut String, args: std::fmt::Arguments<'_>) {
17    push_fmt(out, args);
18    out.push('\n');
19}
20
21macro_rules! pushln {
22    ($out:expr) => {{
23        $out.push('\n');
24    }};
25    ($out:expr, $($arg:tt)*) => {{
26        push_line($out, format_args!($($arg)*));
27    }};
28}
29
30macro_rules! writeln {
31    ($dst:expr) => {{
32        let _ignored = ::std::writeln!($dst);
33        InfallibleWrite
34    }};
35    ($dst:expr, $($arg:tt)*) => {{
36        let _ignored = ::std::writeln!($dst, $($arg)*);
37        InfallibleWrite
38    }};
39}
40
41const TLA_RUST_U64_MAX_CONSTANT: &str = "RustU64Max";
42const TLC_SAFE_RUST_U64_MAX_VALUE: u64 = 2_147_483_647;
43const SESSION_ID_STRING_BRIDGE_HELPER: &str = "meerkat_machine_session_id_matches_string";
44const TLC_REPRESENTATIVE_DOMAIN_HELPER: &str = "TlcRepresentativeDomain";
45
46/// Rust's `Option` order over the model's option records: `None` sorts below
47/// every `Some`, and two `Some`s compare their values. TLC cannot order
48/// records, so an ordering comparison with an option operand renders through
49/// these operators (`a > b` as `OptionLt(b, a)`, `a >= b` as `OptionLe(b, a)`).
50/// A module defines them only when it uses them, and its ASSUMEs re-check the
51/// order on every TLC run of that module.
52///
53/// The operators branch with `IF`, never `\/`: TLC evaluates every disjunct of
54/// an action-level `\/` to enumerate successors (see
55/// `render_or_short_circuit`), and a `None` record's `value` is the string
56/// `"none"`, which TLC cannot order against a number. An `IF` evaluates only
57/// the branch its condition selects, so a `.value` is read only after both
58/// `tag`s say `"some"`.
59const TLA_OPTION_ORDER_DEFINITIONS: &str = concat!(
60    "OptionLt(a, b) == IF b.tag = \"none\" THEN FALSE ELSE IF a.tag = \"none\" THEN TRUE ELSE a.value < b.value\n",
61    "OptionLe(a, b) == IF a.tag = \"none\" THEN TRUE ELSE IF b.tag = \"none\" THEN FALSE ELSE a.value <= b.value\n",
62    "ASSUME ~OptionLt(None, None) /\\ OptionLt(None, Some(0)) /\\ ~OptionLt(Some(0), None) /\\ ",
63    "OptionLt(Some(0), Some(1)) /\\ ~OptionLt(Some(1), Some(1)) /\\ ~OptionLt(Some(1), Some(0))\n",
64    "ASSUME OptionLe(None, None) /\\ OptionLe(None, Some(0)) /\\ ~OptionLe(Some(0), None) /\\ ",
65    "OptionLe(Some(0), Some(1)) /\\ OptionLe(Some(1), Some(1)) /\\ ~OptionLe(Some(1), Some(0))\n",
66    "\n",
67);
68
69use meerkat_machine_schema::{
70    CompositionCoverageManifest, CompositionInvariantKind, CompositionSchema,
71    CompositionStateLimits, CompositionWitness, CoverageAnchor, CoverageSchemaTarget,
72    DriverRefusalFieldSource, EntryInput, EnumSchema, Expr, FeedbackFieldSource, FeedbackInputRef,
73    Guard, HelperSchema, MachineCoverageManifest, MachineSchema, Quantifier, Route,
74    RouteBindingSource, RouteDelivery, RouteTarget, RouteTargetKind, SchedulerRule,
75    TransitionSchema, TriggerMatch, TypePathEnumPayloadAtom, TypePathEnumStructuralVariant,
76    TypePathStructField, TypePathStructFieldAtom, TypeRef, Update, VariantSchema,
77    canonical_machine_schemas,
78};
79
80/// Fail-closed error for composition/machine TLA model generation.
81///
82/// The composition CASE builders and helper ordering used to silently emit
83/// sentinel strings (`"unknown_actor"`, `"unknown_machine"`, …) and swallow
84/// compiler construction errors into `String::new()`. That turned a malformed
85/// composition (a route referencing an undeclared machine/effect/input, or a
86/// helper-call cycle) into a broken-but-passing model. Generation now returns
87/// this typed error so `machine-generate` / `machine-check-drift` fail closed
88/// on malformed input. For every currently-valid schema the resolution checks
89/// pass, so generated output is unchanged.
90/// How a machine's named-type bindings depart from the canonical machine
91/// that shares its id.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum CanonicalNamedTypeMismatchKind {
94    /// A canonical struct binding is missing.
95    MissingStructBinding,
96    /// The binding's generated domain shape differs from the canonical one.
97    DomainShape,
98}
99
100impl std::fmt::Display for CanonicalNamedTypeMismatchKind {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        f.write_str(match self {
103            Self::MissingStructBinding => "is missing the canonical struct binding",
104            Self::DomainShape => "has a different domain shape than the canonical binding",
105        })
106    }
107}
108
109#[derive(Debug, thiserror::Error)]
110pub enum CompositionTlaError {
111    #[error("machine `{machine}`: invalid finite TLC model: {reason}")]
112    InvalidTlcModel { machine: String, reason: String },
113    /// A route's `from_machine` is not a declared machine instance.
114    #[error(
115        "composition `{composition}`: route `{route}` source machine `{machine}` is not a declared machine instance"
116    )]
117    UnknownRouteSourceMachine {
118        composition: String,
119        route: String,
120        machine: String,
121    },
122    /// A route's `to.machine` is not a declared machine instance.
123    #[error(
124        "composition `{composition}`: route `{route}` target machine `{machine}` is not a declared machine instance"
125    )]
126    UnknownRouteTargetMachine {
127        composition: String,
128        route: String,
129        machine: String,
130    },
131    /// A route's `effect_variant` is not a declared effect on its source machine.
132    #[error(
133        "composition `{composition}`: route `{route}` effect `{effect}` is not a declared effect on source machine instance `{machine}`"
134    )]
135    UnknownRouteEffect {
136        composition: String,
137        route: String,
138        machine: String,
139        effect: String,
140    },
141    /// A route's `to.input_variant` is not a declared input on its target machine.
142    #[error(
143        "composition `{composition}`: route `{route}` target input `{input}` is not a declared input on target machine instance `{machine}`"
144    )]
145    UnknownRouteTargetInput {
146        composition: String,
147        route: String,
148        machine: String,
149        input: String,
150    },
151    /// A route's `to.input_variant` is not a declared signal on its target machine.
152    #[error(
153        "composition `{composition}`: route `{route}` target signal `{signal}` is not a declared signal on target machine instance `{machine}`"
154    )]
155    UnknownRouteTargetSignal {
156        composition: String,
157        route: String,
158        machine: String,
159        signal: String,
160    },
161    /// An obligation field on a handoff protocol is absent from the matching
162    /// effect payload (used to be papered over with an `"unknown_<field>"`
163    /// sentinel literal in the generated TLA record).
164    #[error(
165        "composition `{composition}`: handoff protocol `{protocol}` obligation field `{field}` is absent from effect `{effect}` payload"
166    )]
167    UnknownObligationField {
168        composition: String,
169        protocol: String,
170        effect: String,
171        field: String,
172    },
173    /// A generated composition `CASE` operator over a route component could
174    /// not resolve a non-empty mapping for a composition that declares the
175    /// corresponding routes/machines. The previous behaviour laundered this
176    /// into an `OTHER -> "unknown_*"` sentinel, so a model that referenced an
177    /// undeclared actor/machine/effect/input still type-checked. Fail closed
178    /// instead: the operator's `OTHER` catch-all is dropped and an empty
179    /// mapping for a populated composition is a hard codegen error.
180    #[error(
181        "composition `{composition}`: route component `{component}` operator has no resolvable mapping despite declared routes/machines"
182    )]
183    UnknownRouteComponent {
184        composition: String,
185        component: &'static str,
186    },
187    /// A witness references a machine instance that is not part of the
188    /// composition. The renderer must not fall back to an arbitrary schema,
189    /// because that can make a liveness witness weaker than its catalog claim.
190    #[error(
191        "composition `{composition}`: witness `{witness}` references unknown machine instance `{machine}`"
192    )]
193    UnknownWitnessMachine {
194        composition: String,
195        witness: String,
196        machine: String,
197    },
198    /// A witness references a transition that is not declared on its machine.
199    /// Dropping the transition silently would let the generated witness omit
200    /// required progress while still rendering.
201    #[error(
202        "composition `{composition}`: witness `{witness}` references unknown transition `{transition}` on machine instance `{machine}`"
203    )]
204    UnknownWitnessTransition {
205        composition: String,
206        witness: String,
207        machine: String,
208        transition: String,
209    },
210    /// A machine declares a helper-call cycle, so no topological helper order
211    /// exists. The previous fallback silently emitted the cyclic helpers in an
212    /// arbitrary order, producing a model that references helpers before they
213    /// are defined.
214    #[error("machine `{machine}`: helper-call cycle detected: {cycle}")]
215    HelperCycle { machine: String, cycle: String },
216    /// Two distinct UNCHANGED frames derived the same generated operator name.
217    /// Disambiguating with a counter would be order-dependent and would hand
218    /// one action a frame condition it did not have, so this fails the render.
219    #[error("composition `{composition}`: {collision}")]
220    UnchangedFrameCollision {
221        composition: String,
222        collision: UnchangedFrameCollision,
223    },
224    /// Two distinct UNCHANGED frames derived the same generated operator name
225    /// while rendering a per-machine model.
226    #[error("machine `{machine}`: {collision}")]
227    MachineUnchangedFrameCollision {
228        machine: String,
229        collision: UnchangedFrameCollision,
230    },
231    /// Lower-level TLA compiler construction/render failure (e.g. an unknown
232    /// machine schema for a composition instance).
233    #[error("composition TLA compilation failed: {0}")]
234    Compile(String),
235    /// A supplied machine schema fails its own validation.
236    #[error("supplied machine `{machine}` is invalid: {error}")]
237    InvalidSuppliedMachine { machine: String, error: String },
238    /// A supplied catalog lists the same machine id twice.
239    #[error("supplied machine catalog lists machine `{machine}` more than once")]
240    DuplicateSuppliedMachine { machine: String },
241    /// A supplied machine reuses a canonical Meerkat machine id with a
242    /// different schema. A caller's catalog may include a canonical machine
243    /// unchanged, but never a shadow of it.
244    #[error(
245        "supplied machine `{machine}` shares its id with a canonical Meerkat machine but has a different schema"
246    )]
247    ShadowsCanonicalMachine { machine: String },
248    /// A machine that shares a canonical machine's id omits a canonical
249    /// struct named-type binding, or binds a shared named type with a
250    /// different generated domain shape.
251    #[error("machine `{machine}`: named type `{named_type}` {reason}")]
252    CanonicalNamedTypeMismatch {
253        machine: String,
254        named_type: String,
255        reason: CanonicalNamedTypeMismatchKind,
256    },
257    /// Two machines of one composition bind the same named type with
258    /// different generated domain shapes.
259    #[error(
260        "composition `{composition}`: named type `{named_type}` is bound with different domain shapes"
261    )]
262    DivergentNamedTypeBinding {
263        composition: String,
264        named_type: String,
265    },
266    /// The composition does not validate against the supplied catalog.
267    #[error("composition `{composition}` does not validate against the supplied catalog: {error}")]
268    InvalidCompositionForCatalog { composition: String, error: String },
269}
270
271impl From<String> for CompositionTlaError {
272    fn from(message: String) -> Self {
273        CompositionTlaError::Compile(message)
274    }
275}
276
277fn route_target_variant<'a>(
278    machine: &'a MachineSchema,
279    target: &RouteTarget,
280) -> Option<&'a VariantSchema> {
281    match target.kind {
282        RouteTargetKind::Input => machine
283            .inputs
284            .variant_named(target.input_variant.as_str())
285            .ok(),
286        RouteTargetKind::Signal => machine
287            .signals
288            .variant_named(target.input_variant.as_str())
289            .ok(),
290    }
291}
292
293fn transition_trigger_variant<'a>(
294    schema: &'a MachineSchema,
295    transition: &TransitionSchema,
296) -> Option<&'a VariantSchema> {
297    match &transition.on {
298        meerkat_machine_schema::TriggerMatch::Input { variant, .. } => {
299            schema.inputs.variant_named(variant.as_str()).ok()
300        }
301        meerkat_machine_schema::TriggerMatch::Signal { variant, .. } => {
302            schema.signals.variant_named(variant.as_str()).ok()
303        }
304    }
305}
306
307/// Boolean input literals that every enabled instance of `transition` must
308/// carry.
309///
310/// Machine `Next` is an existential disjunction over input domains. Naively
311/// enumerating a large set of boolean validation facts creates a `2^N`
312/// cross-product even when the transition guard immediately requires each fact
313/// to be one literal. Replacing those existential bindings with the forced
314/// literals preserves the exact action relation: assignments carrying the
315/// opposite value cannot satisfy the existing conjunctive guard and therefore
316/// cannot produce a successor state.
317///
318/// Keep the analysis deliberately conservative. Only a whole conjunct that is
319/// structurally a binding, its negation, or a binding/literal equality is
320/// specialized. Values mentioned under disjunctions, helper calls, or other
321/// expressions retain their complete domains. Contradictory requirements also
322/// fall back to full enumeration so codegen never guesses about an
323/// unsatisfiable guard.
324fn transition_forced_bool_literals(
325    transition: &TransitionSchema,
326    binding_types: &BTreeMap<String, TypeRef>,
327) -> BTreeMap<String, bool> {
328    let mut requirements = BTreeMap::<String, Option<bool>>::new();
329    for guard in &transition.guards {
330        collect_conjunctive_bool_requirements(&guard.expr, &mut requirements);
331    }
332    requirements
333        .into_iter()
334        .filter_map(|(binding, required)| {
335            if matches!(binding_types.get(&binding), Some(TypeRef::Bool)) {
336                required.map(|value| (binding, value))
337            } else {
338                None
339            }
340        })
341        .collect()
342}
343
344fn transition_uses_tlc_representative_payload(
345    schema: &MachineSchema,
346    transition: &TransitionSchema,
347) -> bool {
348    match &transition.on {
349        meerkat_machine_schema::TriggerMatch::Input { variant, .. } => schema
350            .tlc_representative_inputs
351            .iter()
352            .any(|candidate| candidate == variant),
353        meerkat_machine_schema::TriggerMatch::Signal { .. } => false,
354    }
355}
356
357fn tlc_representative_domain(domain: String) -> String {
358    format!("{TLC_REPRESENTATIVE_DOMAIN_HELPER}({domain})")
359}
360
361fn collect_conjunctive_bool_requirements(
362    expr: &Expr,
363    requirements: &mut BTreeMap<String, Option<bool>>,
364) {
365    if let Expr::And(items) = expr {
366        for item in items {
367            collect_conjunctive_bool_requirements(item, requirements);
368        }
369        return;
370    }
371
372    let requirement = match expr {
373        Expr::Binding(binding) => Some((binding.as_str(), true)),
374        Expr::Not(inner) => match inner.as_ref() {
375            Expr::Binding(binding) => Some((binding.as_str(), false)),
376            _ => None,
377        },
378        Expr::Eq(left, right) => bool_binding_literal_equality(left, right, false),
379        Expr::Neq(left, right) => bool_binding_literal_equality(left, right, true),
380        _ => None,
381    };
382    let Some((binding, value)) = requirement else {
383        return;
384    };
385
386    match requirements.get(binding).copied() {
387        None => {
388            requirements.insert(binding.to_owned(), Some(value));
389        }
390        Some(Some(existing)) if existing != value => {
391            requirements.insert(binding.to_owned(), None);
392        }
393        Some(_) => {}
394    }
395}
396
397fn bool_binding_literal_equality<'a>(
398    left: &'a Expr,
399    right: &'a Expr,
400    negate: bool,
401) -> Option<(&'a str, bool)> {
402    let (binding, value) = match (left, right) {
403        (Expr::Binding(binding), Expr::Bool(value))
404        | (Expr::Bool(value), Expr::Binding(binding)) => (binding.as_str(), *value),
405        _ => return None,
406    };
407    Some((binding, if negate { !value } else { value }))
408}
409
410fn tla_bool_literal(value: bool) -> &'static str {
411    if value { "TRUE" } else { "FALSE" }
412}
413
414fn collect_helper_calls(expr: &Expr, calls: &mut BTreeSet<String>) {
415    match expr {
416        Expr::Bool(_)
417        | Expr::U64(_)
418        | Expr::U64Max
419        | Expr::String(_)
420        | Expr::NamedVariant { .. }
421        | Expr::EmptySet
422        | Expr::EmptyMap
423        | Expr::CurrentPhase
424        | Expr::Phase(_)
425        | Expr::Field(_)
426        | Expr::Binding(_)
427        | Expr::Variant(_)
428        | Expr::None => {}
429        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
430            for item in items {
431                collect_helper_calls(item, calls);
432            }
433        }
434        Expr::IfElse {
435            condition,
436            then_expr,
437            else_expr,
438        } => {
439            collect_helper_calls(condition, calls);
440            collect_helper_calls(then_expr, calls);
441            collect_helper_calls(else_expr, calls);
442        }
443        Expr::Not(inner)
444        | Expr::SeqElements(inner)
445        | Expr::Len(inner)
446        | Expr::Head(inner)
447        | Expr::MapKeys(inner)
448        | Expr::Some(inner)
449        | Expr::FieldAccess { base: inner, .. }
450        | Expr::EnumVariantIs { value: inner, .. }
451        | Expr::EnumStringSetPayload { value: inner, .. } => collect_helper_calls(inner, calls),
452        Expr::Eq(left, right)
453        | Expr::Neq(left, right)
454        | Expr::Add(left, right)
455        | Expr::Sub(left, right)
456        | Expr::Gt(left, right)
457        | Expr::Gte(left, right)
458        | Expr::Lt(left, right)
459        | Expr::Lte(left, right)
460        | Expr::SeqStartsWith {
461            seq: left,
462            prefix: right,
463        } => {
464            collect_helper_calls(left, calls);
465            collect_helper_calls(right, calls);
466        }
467        Expr::Contains { collection, value } => {
468            collect_helper_calls(collection, calls);
469            collect_helper_calls(value, calls);
470        }
471        Expr::Count { collection, value } => {
472            collect_helper_calls(collection, calls);
473            collect_helper_calls(value, calls);
474        }
475        Expr::MapContainsKey { map, key } => {
476            collect_helper_calls(map, calls);
477            collect_helper_calls(key, calls);
478        }
479        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
480            collect_helper_calls(map, calls);
481            collect_helper_calls(key, calls);
482        }
483        Expr::MapLiteral(entries) => {
484            for (key, value) in entries {
485                collect_helper_calls(key, calls);
486                collect_helper_calls(value, calls);
487            }
488        }
489        Expr::Call { helper, args } => {
490            calls.insert(helper.clone());
491            for arg in args {
492                collect_helper_calls(arg, calls);
493            }
494        }
495        Expr::Quantified { over, body, .. } => {
496            collect_helper_calls(over, calls);
497            collect_helper_calls(body, calls);
498        }
499    }
500}
501
502fn expr_uses_u64_max(expr: &Expr) -> bool {
503    match expr {
504        Expr::U64Max => true,
505        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
506            items.iter().any(expr_uses_u64_max)
507        }
508        Expr::IfElse {
509            condition,
510            then_expr,
511            else_expr,
512        } => {
513            expr_uses_u64_max(condition)
514                || expr_uses_u64_max(then_expr)
515                || expr_uses_u64_max(else_expr)
516        }
517        Expr::Not(inner)
518        | Expr::SeqElements(inner)
519        | Expr::Len(inner)
520        | Expr::Head(inner)
521        | Expr::MapKeys(inner)
522        | Expr::Some(inner)
523        | Expr::FieldAccess { base: inner, .. }
524        | Expr::EnumVariantIs { value: inner, .. }
525        | Expr::EnumStringSetPayload { value: inner, .. } => expr_uses_u64_max(inner),
526        Expr::Eq(left, right)
527        | Expr::Neq(left, right)
528        | Expr::Add(left, right)
529        | Expr::Sub(left, right)
530        | Expr::Gt(left, right)
531        | Expr::Gte(left, right)
532        | Expr::Lt(left, right)
533        | Expr::Lte(left, right) => expr_uses_u64_max(left) || expr_uses_u64_max(right),
534        Expr::Contains { collection, value } | Expr::Count { collection, value } => {
535            expr_uses_u64_max(collection) || expr_uses_u64_max(value)
536        }
537        Expr::MapContainsKey { map, key }
538        | Expr::MapGet { map, key }
539        | Expr::MapValue { map, key } => expr_uses_u64_max(map) || expr_uses_u64_max(key),
540        Expr::MapLiteral(entries) => entries
541            .iter()
542            .any(|(key, value)| expr_uses_u64_max(key) || expr_uses_u64_max(value)),
543        Expr::SeqStartsWith { seq, prefix } => expr_uses_u64_max(seq) || expr_uses_u64_max(prefix),
544        Expr::Call { helper, args } => {
545            native_helper_uses_u64_max(helper) || args.iter().any(expr_uses_u64_max)
546        }
547        Expr::Quantified { over, body, .. } => expr_uses_u64_max(over) || expr_uses_u64_max(body),
548        Expr::Bool(_)
549        | Expr::U64(_)
550        | Expr::String(_)
551        | Expr::NamedVariant { .. }
552        | Expr::EmptySet
553        | Expr::EmptyMap
554        | Expr::CurrentPhase
555        | Expr::Phase(_)
556        | Expr::Field(_)
557        | Expr::Binding(_)
558        | Expr::Variant(_)
559        | Expr::None => false,
560    }
561}
562
563fn expr_calls_helper(expr: &Expr, helper: &str) -> bool {
564    let mut calls = BTreeSet::new();
565    collect_helper_calls(expr, &mut calls);
566    calls.contains(helper)
567}
568
569fn native_helper_uses_u64_max(helper: &str) -> bool {
570    matches!(
571        helper,
572        "mob_machine_next_respawn_generation"
573            | "mob_machine_next_minted_generation"
574            | "mob_machine_u64_is_exact_successor"
575            | "mob_machine_optional_u64_is_exact_successor"
576    )
577}
578
579fn update_uses_u64_max(update: &Update) -> bool {
580    match update {
581        Update::Assign { expr, .. }
582        | Update::SetInsert { value: expr, .. }
583        | Update::SetRemove { value: expr, .. }
584        | Update::SeqAppend { value: expr, .. }
585        | Update::SeqPrepend { values: expr, .. }
586        | Update::SeqRemoveValue { value: expr, .. }
587        | Update::SeqRemoveAll { values: expr, .. } => expr_uses_u64_max(expr),
588        Update::MapInsert { key, value, .. } => expr_uses_u64_max(key) || expr_uses_u64_max(value),
589        Update::MapRemove { key, .. }
590        | Update::MapIncrement { key, .. }
591        | Update::MapDecrement { key, .. } => expr_uses_u64_max(key),
592        Update::Conditional {
593            condition,
594            then_updates,
595            else_updates,
596        } => {
597            expr_uses_u64_max(condition)
598                || then_updates.iter().any(update_uses_u64_max)
599                || else_updates.iter().any(update_uses_u64_max)
600        }
601        Update::ForEach { over, updates, .. } => {
602            expr_uses_u64_max(over) || updates.iter().any(update_uses_u64_max)
603        }
604        Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => false,
605    }
606}
607
608fn update_calls_helper(update: &Update, helper: &str) -> bool {
609    match update {
610        Update::Assign { expr, .. }
611        | Update::SetInsert { value: expr, .. }
612        | Update::SetRemove { value: expr, .. }
613        | Update::SeqAppend { value: expr, .. }
614        | Update::SeqPrepend { values: expr, .. }
615        | Update::SeqRemoveValue { value: expr, .. }
616        | Update::SeqRemoveAll { values: expr, .. } => expr_calls_helper(expr, helper),
617        Update::MapInsert { key, value, .. } => {
618            expr_calls_helper(key, helper) || expr_calls_helper(value, helper)
619        }
620        Update::MapRemove { key, .. }
621        | Update::MapIncrement { key, .. }
622        | Update::MapDecrement { key, .. } => expr_calls_helper(key, helper),
623        Update::Conditional {
624            condition,
625            then_updates,
626            else_updates,
627        } => {
628            expr_calls_helper(condition, helper)
629                || then_updates
630                    .iter()
631                    .any(|update| update_calls_helper(update, helper))
632                || else_updates
633                    .iter()
634                    .any(|update| update_calls_helper(update, helper))
635        }
636        Update::ForEach { over, updates, .. } => {
637            expr_calls_helper(over, helper)
638                || updates
639                    .iter()
640                    .any(|update| update_calls_helper(update, helper))
641        }
642        Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => false,
643    }
644}
645
646fn explicit_value_uses_u64_max(value: &meerkat_machine_schema::TlcValue) -> bool {
647    use meerkat_machine_schema::TlcValue;
648    match value {
649        TlcValue::U64(number) => *number == u64::MAX,
650        TlcValue::Some(value) => explicit_value_uses_u64_max(value),
651        TlcValue::Record(fields) => fields.values().any(explicit_value_uses_u64_max),
652        TlcValue::Set(values) => values.iter().any(explicit_value_uses_u64_max),
653        TlcValue::Bool(_) | TlcValue::String(_) | TlcValue::None => false,
654    }
655}
656
657fn machine_uses_u64_max(schema: &MachineSchema) -> bool {
658    schema.tlc_model.as_ref().is_some_and(|model| {
659        [&model.ci, &model.deep].iter().any(|profile| {
660            profile
661                .named_values
662                .values()
663                .flatten()
664                .any(explicit_value_uses_u64_max)
665        })
666    }) || schema
667        .state
668        .init
669        .fields
670        .iter()
671        .any(|field| expr_uses_u64_max(&field.expr))
672        || schema
673            .helpers
674            .iter()
675            .any(|helper| expr_uses_u64_max(&helper.body))
676        || schema
677            .derived
678            .iter()
679            .any(|helper| expr_uses_u64_max(&helper.body))
680        || schema
681            .invariants
682            .iter()
683            .any(|invariant| expr_uses_u64_max(&invariant.expr))
684        || schema.transitions.iter().any(|transition| {
685            transition
686                .guards
687                .iter()
688                .any(|guard| expr_uses_u64_max(&guard.expr))
689                || transition.updates.iter().any(update_uses_u64_max)
690                || transition
691                    .emit
692                    .iter()
693                    .any(|effect| effect.fields.values().any(expr_uses_u64_max))
694        })
695}
696
697fn machine_uses_session_id_string_bridge(schema: &MachineSchema) -> bool {
698    schema
699        .state
700        .init
701        .fields
702        .iter()
703        .any(|field| expr_calls_helper(&field.expr, SESSION_ID_STRING_BRIDGE_HELPER))
704        || schema
705            .helpers
706            .iter()
707            .chain(schema.derived.iter())
708            .any(|helper| expr_calls_helper(&helper.body, SESSION_ID_STRING_BRIDGE_HELPER))
709        || schema
710            .invariants
711            .iter()
712            .any(|invariant| expr_calls_helper(&invariant.expr, SESSION_ID_STRING_BRIDGE_HELPER))
713        || schema.transitions.iter().any(|transition| {
714            transition
715                .guards
716                .iter()
717                .any(|guard| expr_calls_helper(&guard.expr, SESSION_ID_STRING_BRIDGE_HELPER))
718                || transition
719                    .updates
720                    .iter()
721                    .any(|update| update_calls_helper(update, SESSION_ID_STRING_BRIDGE_HELPER))
722                || transition.emit.iter().any(|effect| {
723                    effect
724                        .fields
725                        .values()
726                        .any(|expr| expr_calls_helper(expr, SESSION_ID_STRING_BRIDGE_HELPER))
727                })
728        })
729}
730
731fn composition_uses_session_id_string_bridge(
732    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
733) -> bool {
734    machine_by_instance
735        .values()
736        .copied()
737        .any(machine_uses_session_id_string_bridge)
738}
739
740fn composition_uses_u64_max(
741    schema: &CompositionSchema,
742    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
743) -> bool {
744    machine_by_instance
745        .values()
746        .copied()
747        .any(machine_uses_u64_max)
748        || schema.routes.iter().any(|route| {
749            route.bindings.iter().any(|binding| match &binding.source {
750                RouteBindingSource::Literal(expr) => expr_uses_u64_max(expr),
751                RouteBindingSource::Field { .. } | RouteBindingSource::OwnerProvided => false,
752            })
753        })
754        || schema.witnesses.iter().any(|witness| {
755            witness.preload_inputs.iter().any(|input| {
756                input
757                    .fields
758                    .iter()
759                    .any(|field| expr_uses_u64_max(&field.expr))
760            }) || witness.expected_states.iter().any(|state| {
761                state
762                    .fields
763                    .iter()
764                    .any(|field| expr_uses_u64_max(&field.expr))
765            })
766        })
767}
768
769/// Detect a helper-call cycle via DFS over the helper-call dependency graph,
770/// using a visited set plus an explicit recursion stack to catch back-edges.
771///
772/// Returns the cycle path (in call order) the first time a back-edge is found,
773/// or `None` when the helper graph is acyclic. Only edges to declared helpers
774/// (`known`) are followed; self-references and calls to native/undeclared
775/// helpers are not dependency edges for ordering purposes.
776fn detect_helper_cycle(defs: &[&HelperSchema], known: &BTreeSet<String>) -> Option<Vec<String>> {
777    let deps_of = |helper: &HelperSchema| -> Vec<String> {
778        let mut calls = BTreeSet::new();
779        collect_helper_calls(&helper.body, &mut calls);
780        calls
781            .into_iter()
782            .filter(|dep| dep != &helper.name && known.contains(dep))
783            .collect()
784    };
785    let by_name: BTreeMap<&str, &HelperSchema> =
786        defs.iter().map(|h| (h.name.as_str(), *h)).collect();
787
788    let mut visited: BTreeSet<String> = BTreeSet::new();
789    let mut on_stack: BTreeSet<String> = BTreeSet::new();
790    let mut stack_path: Vec<String> = Vec::new();
791    // Explicit work stack of (node, next-dependency-index) frames so the DFS
792    // does not recurse on the (untrusted) helper graph depth.
793    let mut frames: Vec<(String, Vec<String>, usize)> = Vec::new();
794
795    for root in defs {
796        let root_name = root.name.clone();
797        if visited.contains(&root_name) {
798            continue;
799        }
800        frames.push((root_name.clone(), deps_of(root), 0));
801        on_stack.insert(root_name.clone());
802        stack_path.push(root_name);
803
804        while !frames.is_empty() {
805            // Read the next dependency (if any) from the top frame, advancing
806            // its cursor, then release the borrow before mutating `frames`.
807            let next_dep = {
808                let Some((_, deps, idx)) = frames.last_mut() else {
809                    break;
810                };
811                if *idx < deps.len() {
812                    let dep = deps[*idx].clone();
813                    *idx += 1;
814                    Some(dep)
815                } else {
816                    None
817                }
818            };
819
820            match next_dep {
821                Some(dep) => {
822                    if on_stack.contains(&dep) {
823                        // Back-edge: report the cycle path from `dep` onward,
824                        // closing the loop back to `dep`.
825                        let start = stack_path.iter().position(|n| n == &dep).unwrap_or(0);
826                        let mut cycle = stack_path[start..].to_vec();
827                        cycle.push(dep);
828                        return Some(cycle);
829                    }
830                    if visited.contains(&dep) {
831                        continue;
832                    }
833                    let dep_deps = match by_name.get(dep.as_str()) {
834                        Some(helper) => deps_of(helper),
835                        None => Vec::new(),
836                    };
837                    on_stack.insert(dep.clone());
838                    stack_path.push(dep.clone());
839                    frames.push((dep, dep_deps, 0));
840                }
841                None => {
842                    if let Some((node, _, _)) = frames.pop() {
843                        on_stack.remove(&node);
844                        visited.insert(node);
845                    }
846                    stack_path.pop();
847                }
848            }
849        }
850    }
851    None
852}
853
854fn helper_dependency_order(
855    schema: &MachineSchema,
856) -> std::result::Result<Vec<&HelperSchema>, CompositionTlaError> {
857    let defs = schema
858        .helpers
859        .iter()
860        .chain(schema.derived.iter())
861        .collect::<Vec<_>>();
862    let known = defs
863        .iter()
864        .map(|helper| &helper.name)
865        .cloned()
866        .collect::<BTreeSet<_>>();
867
868    // Fail closed: a helper-call cycle has no topological order. The previous
869    // fallback silently dumped the cyclic helpers in arbitrary order, emitting
870    // a model that references a helper before it is defined.
871    if let Some(cycle) = detect_helper_cycle(&defs, &known) {
872        return Err(CompositionTlaError::HelperCycle {
873            machine: schema.machine.as_str().to_owned(),
874            cycle: cycle.join(" -> "),
875        });
876    }
877
878    let mut remaining = defs;
879    let mut ordered = Vec::new();
880
881    while !remaining.is_empty() {
882        let remaining_names = remaining
883            .iter()
884            .map(|helper| &helper.name)
885            .cloned()
886            .collect::<BTreeSet<_>>();
887        let mut ready_indices = Vec::new();
888
889        for (index, helper) in remaining.iter().enumerate() {
890            let mut deps = BTreeSet::new();
891            collect_helper_calls(&helper.body, &mut deps);
892            let unresolved = deps.into_iter().filter(|dep| {
893                dep != &helper.name && known.contains(dep) && remaining_names.contains(dep)
894            });
895            if unresolved.count() == 0 {
896                ready_indices.push(index);
897            }
898        }
899
900        if ready_indices.is_empty() {
901            // Unreachable: `detect_helper_cycle` already failed closed on any
902            // cyclic helper graph above, so an acyclic graph always has at
903            // least one ready helper here. Fail closed defensively rather than
904            // re-introducing the silent arbitrary-order fallback.
905            let cycle = remaining
906                .iter()
907                .map(|helper| helper.name.clone())
908                .collect::<Vec<_>>()
909                .join(" -> ");
910            return Err(CompositionTlaError::HelperCycle {
911                machine: schema.machine.as_str().to_owned(),
912                cycle,
913            });
914        }
915
916        for index in ready_indices.into_iter().rev() {
917            ordered.push(remaining.remove(index));
918        }
919    }
920
921    Ok(ordered)
922}
923
924/// Render one coverage anchor as a generated contract-markdown bullet,
925/// surfacing its typed schema target so artifact drift is visible to the
926/// rerun-and-diff gate.
927fn render_contract_coverage_anchor_bullet(anchor: &CoverageAnchor) -> String {
928    let target = match &anchor.target {
929        CoverageSchemaTarget::Machine(machine) => format!("machine `{machine}`"),
930        CoverageSchemaTarget::Route(route) => format!("route `{route}`"),
931    };
932    format!(
933        "- `{}` ({}): `{}` — {}",
934        anchor.id,
935        target,
936        anchor.symbol.as_str(),
937        anchor.note
938    )
939}
940
941pub fn render_machine_contract_markdown(
942    schema: &MachineSchema,
943    coverage: &MachineCoverageManifest,
944) -> String {
945    let mut out = String::new();
946
947    pushln!(&mut out, "# {}", schema.machine);
948    pushln!(&mut out);
949    writeln!(
950        &mut out,
951        "_Generated from the Rust machine catalog. Do not edit by hand._"
952    )
953    .expect("write to string");
954    pushln!(&mut out);
955    pushln!(&mut out, "- Version: `{}`", schema.version);
956    writeln!(
957        &mut out,
958        "- Rust owner: `{}` / `{}`",
959        schema.rust.crate_name, schema.rust.module
960    )
961    .expect("write to string");
962    pushln!(&mut out);
963
964    render_state_markdown(&mut out, schema);
965    let runtime_internal_inputs: BTreeSet<&str> = schema
966        .runtime_internal_inputs
967        .iter()
968        .map(|input| input.as_str())
969        .collect();
970    render_input_subset(&mut out, "Inputs", &schema.inputs, |name| {
971        !runtime_internal_inputs.contains(name)
972    });
973    if !schema.surface_only_inputs.is_empty() {
974        pushln!(&mut out, "## Surface-only Inputs");
975        for input in &schema.surface_only_inputs {
976            pushln!(&mut out, "- `{input}`");
977        }
978        pushln!(&mut out);
979    }
980    if !runtime_internal_inputs.is_empty() {
981        render_input_subset(
982            &mut out,
983            "Runtime-Internal Inputs",
984            &schema.inputs,
985            |name| runtime_internal_inputs.contains(name),
986        );
987    }
988    render_ci_samples_markdown(&mut out, schema);
989    render_enum_markdown(&mut out, "Signals", &schema.signals);
990    render_enum_markdown(&mut out, "Effects", &schema.effects);
991
992    if !schema.helpers.is_empty() {
993        pushln!(&mut out, "## Helpers");
994        for helper in &schema.helpers {
995            writeln!(
996                &mut out,
997                "- `{}`({}) -> `{}`",
998                helper.name,
999                render_field_list(&helper.params),
1000                render_type_ref(&helper.returns)
1001            )
1002            .expect("write to string");
1003        }
1004        pushln!(&mut out);
1005    }
1006
1007    if !schema.derived.is_empty() {
1008        pushln!(&mut out, "## Derived");
1009        for derived in &schema.derived {
1010            writeln!(
1011                &mut out,
1012                "- `{}`({}) -> `{}`",
1013                derived.name,
1014                render_field_list(&derived.params),
1015                render_type_ref(&derived.returns)
1016            )
1017            .expect("write to string");
1018        }
1019        pushln!(&mut out);
1020    }
1021
1022    if !schema.command_plans.is_empty() {
1023        pushln!(&mut out, "## Command Plans");
1024        let transitions_by_name = schema
1025            .transitions
1026            .iter()
1027            .map(|transition| (transition.name.as_str(), transition))
1028            .collect::<BTreeMap<_, _>>();
1029        for plan in &schema.command_plans {
1030            pushln!(&mut out, "### `{}`", plan.name);
1031            pushln!(&mut out, "- Authority: `{}`", plan.authority_type);
1032            if !plan.source_inputs.is_empty() {
1033                writeln!(
1034                    &mut out,
1035                    "- Source Inputs: {}",
1036                    plan.source_inputs
1037                        .iter()
1038                        .map(|input| format!("`{input}`"))
1039                        .collect::<Vec<_>>()
1040                        .join(", ")
1041                )
1042                .expect("write to string");
1043            }
1044            if !plan.source_signals.is_empty() {
1045                writeln!(
1046                    &mut out,
1047                    "- Source Signals: {}",
1048                    plan.source_signals
1049                        .iter()
1050                        .map(|signal| format!("`{signal}`"))
1051                        .collect::<Vec<_>>()
1052                        .join(", ")
1053                )
1054                .expect("write to string");
1055            }
1056            if !plan.transitions.is_empty() {
1057                writeln!(
1058                    &mut out,
1059                    "- Transitions: {}",
1060                    plan.transitions
1061                        .iter()
1062                        .map(|transition| format!("`{transition}`"))
1063                        .collect::<Vec<_>>()
1064                        .join(", ")
1065                )
1066                .expect("write to string");
1067                pushln!(&mut out, "- Guard Expansion:");
1068                for transition_id in &plan.transitions {
1069                    if let Some(transition) = transitions_by_name.get(transition_id.as_str()) {
1070                        let guards = if transition.guards.is_empty() {
1071                            "`<none>`".to_owned()
1072                        } else {
1073                            transition
1074                                .guards
1075                                .iter()
1076                                .map(|guard| format!("`{}`", guard.name))
1077                                .collect::<Vec<_>>()
1078                                .join(", ")
1079                        };
1080                        pushln!(&mut out, "  - `{transition_id}`: {guards}");
1081                    }
1082                }
1083            }
1084            if !plan.effects.is_empty() {
1085                writeln!(
1086                    &mut out,
1087                    "- Command Effects: {}",
1088                    plan.effects
1089                        .iter()
1090                        .map(|effect| format!("`{effect}`"))
1091                        .collect::<Vec<_>>()
1092                        .join(", ")
1093                )
1094                .expect("write to string");
1095            }
1096            if !plan.effect_closures.is_empty() {
1097                pushln!(&mut out, "- Effect Closure:");
1098                for closure in &plan.effect_closures {
1099                    writeln!(
1100                        &mut out,
1101                        "  - `{}` via `{}` ({}) states: {}",
1102                        closure.effect,
1103                        closure.authority_type,
1104                        closure.closure_policy,
1105                        closure
1106                            .lifecycle
1107                            .iter()
1108                            .map(|state| format!("`{state}`"))
1109                            .collect::<Vec<_>>()
1110                            .join(", ")
1111                    )
1112                    .expect("write to string");
1113                }
1114            }
1115            let emitted_effects = plan
1116                .transitions
1117                .iter()
1118                .filter_map(|transition_id| transitions_by_name.get(transition_id.as_str()))
1119                .flat_map(|transition| transition.emit.iter().map(|effect| &effect.variant))
1120                .collect::<BTreeSet<_>>();
1121            if !emitted_effects.is_empty() {
1122                writeln!(
1123                    &mut out,
1124                    "- Emitted By Transitions: {}",
1125                    emitted_effects
1126                        .iter()
1127                        .map(|effect| format!("`{effect}`"))
1128                        .collect::<Vec<_>>()
1129                        .join(", ")
1130                )
1131                .expect("write to string");
1132            }
1133            pushln!(&mut out);
1134        }
1135    }
1136
1137    pushln!(&mut out, "## Invariants");
1138    for invariant in &schema.invariants {
1139        pushln!(&mut out, "- `{}`", invariant.name);
1140    }
1141    pushln!(&mut out);
1142
1143    pushln!(&mut out, "## Transitions");
1144    for transition in &schema.transitions {
1145        pushln!(&mut out, "### `{}`", transition.name);
1146        writeln!(
1147            &mut out,
1148            "- From: {}",
1149            transition
1150                .from
1151                .iter()
1152                .map(|item| format!("`{item}`"))
1153                .collect::<Vec<_>>()
1154                .join(", ")
1155        )
1156        .expect("write to string");
1157        writeln!(
1158            &mut out,
1159            "- On: `{}`({})",
1160            transition.on.variant_str(),
1161            transition
1162                .on
1163                .bindings()
1164                .iter()
1165                .map(meerkat_machine_schema::identity::FieldId::as_str)
1166                .collect::<Vec<_>>()
1167                .join(", ")
1168        )
1169        .expect("write to string");
1170        if !transition.guards.is_empty() {
1171            pushln!(&mut out, "- Guards:");
1172            for guard in &transition.guards {
1173                pushln!(&mut out, "  - `{}`", guard.name);
1174            }
1175        }
1176        if !transition.emit.is_empty() {
1177            writeln!(
1178                &mut out,
1179                "- Emits: {}",
1180                transition
1181                    .emit
1182                    .iter()
1183                    .map(|effect| format!("`{}`", effect.variant))
1184                    .collect::<Vec<_>>()
1185                    .join(", ")
1186            )
1187            .expect("write to string");
1188        }
1189        pushln!(&mut out, "- To: `{}`", transition.to);
1190        pushln!(&mut out);
1191    }
1192
1193    pushln!(&mut out, "## Coverage");
1194    pushln!(&mut out, "### Code Anchors");
1195    for anchor in &coverage.code_anchors {
1196        pushln!(
1197            &mut out,
1198            "{}",
1199            render_contract_coverage_anchor_bullet(anchor)
1200        );
1201    }
1202    pushln!(&mut out);
1203    pushln!(&mut out, "### Scenarios");
1204    for scenario in &coverage.scenarios {
1205        pushln!(&mut out, "- `{}` — {}", scenario.id, scenario.summary);
1206    }
1207
1208    out
1209}
1210
1211pub fn render_composition_contract_markdown(
1212    schema: &CompositionSchema,
1213    coverage: &CompositionCoverageManifest,
1214) -> String {
1215    let mut out = String::new();
1216
1217    pushln!(&mut out, "# {}", schema.name);
1218    pushln!(&mut out);
1219    writeln!(
1220        &mut out,
1221        "_Generated from the Rust composition catalog. Do not edit by hand._"
1222    )
1223    .expect("write to string");
1224    pushln!(&mut out);
1225
1226    pushln!(&mut out, "## Machines");
1227    for machine in &schema.machines {
1228        writeln!(
1229            &mut out,
1230            "- `{}`: `{}` @ actor `{}`",
1231            machine.instance_id, machine.machine_name, machine.actor
1232        )
1233        .expect("write to string");
1234    }
1235    pushln!(&mut out);
1236
1237    pushln!(&mut out, "## Routes");
1238    for route in &schema.routes {
1239        writeln!(
1240            &mut out,
1241            "- `{}`: `{}`.`{}` -> `{}`.`{}` [{}]",
1242            route.name,
1243            route.from_machine,
1244            route.effect_variant,
1245            route.to.machine,
1246            route.to.input_variant,
1247            render_route_delivery(route)
1248        )
1249        .expect("write to string");
1250    }
1251    pushln!(&mut out);
1252
1253    pushln!(&mut out, "## Target Selectors");
1254    if schema.route_target_selectors.is_empty() {
1255        pushln!(&mut out, "- `(none)`");
1256    } else {
1257        for selector in &schema.route_target_selectors {
1258            pushln!(
1259                &mut out,
1260                "- `{}` selects `{}` from `{:?}`",
1261                selector.route_name,
1262                selector.selector_field,
1263                selector.source
1264            );
1265        }
1266    }
1267    pushln!(&mut out);
1268
1269    pushln!(&mut out, "## Driver");
1270    if let Some(driver) = &schema.driver {
1271        pushln!(
1272            &mut out,
1273            "- `{}` (`{}` in `{}`)",
1274            driver.name,
1275            driver.rust.driver_type,
1276            driver.rust.module_path
1277        );
1278        if !driver.watched_effects.is_empty() {
1279            pushln!(&mut out, "  - watches:");
1280            for watched in &driver.watched_effects {
1281                pushln!(
1282                    &mut out,
1283                    "    - `{}::{}`",
1284                    watched.producer_instance,
1285                    watched.effect_variant
1286                );
1287            }
1288        }
1289        if !driver.dispatch_routes.is_empty() {
1290            pushln!(&mut out, "  - dispatches:");
1291            for dispatch in &driver.dispatch_routes {
1292                pushln!(
1293                    &mut out,
1294                    "    - `{}` → `{}::{}` ({:?})",
1295                    dispatch.name,
1296                    dispatch.target_instance,
1297                    dispatch.input_variant,
1298                    dispatch.target_kind
1299                );
1300            }
1301        }
1302        if !driver.refusal_closures.is_empty() {
1303            pushln!(&mut out, "  - consumer-refusal closures:");
1304            for closure in &driver.refusal_closures {
1305                pushln!(
1306                    &mut out,
1307                    "    - `{}` refusal → `{}::{}`",
1308                    closure.dispatch_route,
1309                    closure.feedback_instance,
1310                    closure.feedback_input
1311                );
1312            }
1313        }
1314    } else {
1315        pushln!(&mut out, "- `(none)`");
1316    }
1317    pushln!(&mut out);
1318
1319    pushln!(&mut out, "## Transaction Plans");
1320    if schema.transaction_plans.is_empty() {
1321        pushln!(&mut out, "- `(none)`");
1322    } else {
1323        for plan in &schema.transaction_plans {
1324            pushln!(
1325                &mut out,
1326                "- `{}` via `{}` / `{}` — {}",
1327                plan.name,
1328                plan.trigger,
1329                plan.store_primitive,
1330                plan.description
1331            );
1332        }
1333    }
1334    pushln!(&mut out);
1335
1336    pushln!(&mut out, "## Scheduler Rules");
1337    if schema.scheduler_rules.is_empty() {
1338        pushln!(&mut out, "- `(none)`");
1339    } else {
1340        for rule in &schema.scheduler_rules {
1341            pushln!(&mut out, "- `{}`", render_scheduler_rule(rule));
1342        }
1343    }
1344    pushln!(&mut out);
1345
1346    let structural_invariants = schema
1347        .invariants
1348        .iter()
1349        .filter(|invariant| invariant.kind.is_structural())
1350        .collect::<Vec<_>>();
1351    let behavioral_invariants = schema
1352        .invariants
1353        .iter()
1354        .filter(|invariant| invariant.kind.is_behavioral())
1355        .collect::<Vec<_>>();
1356
1357    pushln!(&mut out, "## Structural Requirements");
1358    if structural_invariants.is_empty() {
1359        pushln!(&mut out, "- `(none)`");
1360    } else {
1361        for invariant in &structural_invariants {
1362            pushln!(&mut out, "- `{}` — {}", invariant.name, invariant.statement);
1363        }
1364    }
1365    pushln!(&mut out);
1366
1367    writeln!(&mut out, "## Behavioral Invariants");
1368    if behavioral_invariants.is_empty() {
1369        pushln!(&mut out, "- `(none)`");
1370    } else {
1371        for invariant in &behavioral_invariants {
1372            pushln!(&mut out, "- `{}` — {}", invariant.name, invariant.statement);
1373        }
1374    }
1375    pushln!(&mut out);
1376
1377    writeln!(&mut out, "## Coverage");
1378    pushln!(&mut out, "### Code Anchors");
1379    for anchor in &coverage.code_anchors {
1380        pushln!(
1381            &mut out,
1382            "{}",
1383            render_contract_coverage_anchor_bullet(anchor)
1384        );
1385    }
1386    pushln!(&mut out);
1387    pushln!(&mut out, "### Scenarios");
1388    for scenario in &coverage.scenarios {
1389        pushln!(&mut out, "- `{}` — {}", scenario.id, scenario.summary);
1390    }
1391
1392    out
1393}
1394
1395pub fn render_machine_ci_cfg(
1396    schema: &MachineSchema,
1397    deep: bool,
1398) -> Result<String, CompositionTlaError> {
1399    if schema.tlc_model.is_some() {
1400        validate_machine_model(schema)?;
1401    }
1402    let mut out = String::new();
1403    let domains = collect_binding_domains(schema);
1404    let named_samples = collect_machine_named_type_samples(schema);
1405    let deep_named_samples = with_guard_binding_string_samples(&named_samples, schema);
1406    // The native SessionId/String bridge deliberately substitutes its sample
1407    // into a fixed-size Deep string pool; keep that bound for bridge machines.
1408    let deep_guard_string_samples = deep && !machine_uses_session_id_string_bridge(schema);
1409    let named_bindings = collect_machine_named_bindings(schema);
1410    let sample_cardinality = machine_cfg_sample_cardinality(schema, deep);
1411    let operator_suffix = if deep { "Deep" } else { "Ci" };
1412    let uses_u64_max = machine_uses_u64_max(schema);
1413    let session_id_cardinality = if deep {
1414        schema
1415            .deep_domain_overrides
1416            .get("SessionIdValues")
1417            .copied()
1418            .unwrap_or(sample_cardinality)
1419    } else {
1420        sample_cardinality
1421    };
1422    let session_id_string_bridge_sample = session_id_string_bridge_sample(
1423        deep && machine_uses_session_id_string_bridge(schema),
1424        &domains,
1425        session_id_cardinality,
1426        &named_samples,
1427        &named_bindings,
1428    );
1429    let input_samples = machine_input_sample_constants(schema);
1430    let typed_samples = machine_input_typed_sample_constants(schema);
1431
1432    pushln!(&mut out, "SPECIFICATION Spec");
1433    if !domains.is_empty() || uses_u64_max || !input_samples.is_empty() || !typed_samples.is_empty()
1434    {
1435        pushln!(&mut out, "CONSTANTS");
1436        if uses_u64_max {
1437            push_u64_max_cfg_assignment(&mut out);
1438        }
1439        for (name, ty) in domains {
1440            if matches!(
1441                ty,
1442                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1443            ) {
1444                continue;
1445            }
1446            if machine_explicit_values(schema, deep, &ty).is_some()
1447                || cfg_assignment_requires_model_operator(&ty, &named_bindings)
1448            {
1449                writeln!(
1450                    &mut out,
1451                    "  {} <- {}",
1452                    name,
1453                    cfg_assignment_operator_name(&name, operator_suffix),
1454                )
1455                .expect("write to string");
1456            } else {
1457                // Deep-profile per-domain override (machine analog of the
1458                // composition path): absent keys use the profile default.
1459                let domain_cardinality = if deep {
1460                    schema
1461                        .deep_domain_overrides
1462                        .get(name.as_str())
1463                        .copied()
1464                        .unwrap_or(sample_cardinality)
1465                } else {
1466                    sample_cardinality
1467                };
1468                writeln!(
1469                    &mut out,
1470                    "  {} = {}",
1471                    name,
1472                    render_cfg_domain_assignment(
1473                        &ty,
1474                        domain_cardinality,
1475                        if deep_guard_string_samples {
1476                            &deep_named_samples
1477                        } else {
1478                            &named_samples
1479                        },
1480                        &named_bindings,
1481                        deep_guard_string_samples,
1482                        session_id_string_bridge_sample.as_deref(),
1483                    )
1484                )
1485                .expect("write to string");
1486            }
1487        }
1488        // A `CiValues` input field: the CI profile explores exactly its
1489        // declared values, the Deep profile those and the default `0..2`.
1490        for (constant, ci_values) in &input_samples {
1491            let values: BTreeSet<u64> = if deep {
1492                broad_input_samples(ci_values)
1493            } else {
1494                ci_values.iter().copied().collect()
1495            };
1496            writeln!(&mut out, "  {} = {}", constant, render_u64_set(&values))
1497                .expect("write to string");
1498        }
1499        // A `CiSamples` input field: the CI profile explores exactly its
1500        // declared values, the Deep profile the field type's whole domain,
1501        // through the operators the generated model defines.
1502        for (constant, _, _) in &typed_samples {
1503            writeln!(
1504                &mut out,
1505                "  {} <- {}",
1506                constant,
1507                cfg_assignment_operator_name(constant, operator_suffix)
1508            )
1509            .expect("write to string");
1510        }
1511    }
1512    if !schema.invariants.is_empty() {
1513        pushln!(&mut out, "INVARIANTS");
1514        for invariant in &schema.invariants {
1515            pushln!(&mut out, "  {}", invariant.name);
1516        }
1517    }
1518    pushln!(&mut out, "CONSTRAINTS");
1519    writeln!(
1520        &mut out,
1521        "  {}",
1522        if deep {
1523            "DeepStateConstraint"
1524        } else {
1525            "CiStateConstraint"
1526        }
1527    )
1528    .expect("write to string");
1529
1530    Ok(out)
1531}
1532
1533pub fn render_composition_ci_cfg(schema: &CompositionSchema, deep: bool) -> String {
1534    render_composition_ci_cfg_from_catalog(schema, deep, &canonical_machine_schemas())
1535}
1536
1537/// [`render_composition_ci_cfg`] against an explicitly supplied machine
1538/// catalog, for compositions whose machines live outside Meerkat's catalog.
1539pub fn render_composition_ci_cfg_with_catalog(
1540    schema: &CompositionSchema,
1541    deep: bool,
1542    machine_catalog: &[MachineSchema],
1543) -> std::result::Result<String, CompositionTlaError> {
1544    validate_supplied_catalog(schema, machine_catalog)?;
1545    Ok(render_composition_ci_cfg_from_catalog(
1546        schema,
1547        deep,
1548        machine_catalog,
1549    ))
1550}
1551
1552fn render_composition_ci_cfg_from_catalog(
1553    schema: &CompositionSchema,
1554    deep: bool,
1555    machine_catalog: &[MachineSchema],
1556) -> String {
1557    let mut out = String::new();
1558    let machine_by_name = machine_catalog
1559        .iter()
1560        .map(|machine| (machine.machine.as_str(), machine))
1561        .collect::<BTreeMap<_, _>>();
1562    let machine_by_instance = schema
1563        .machines
1564        .iter()
1565        .filter_map(|instance| {
1566            machine_by_name
1567                .get(instance.machine_name.as_str())
1568                .copied()
1569                .map(|machine| (instance.instance_id.as_str(), machine))
1570        })
1571        .collect::<BTreeMap<_, _>>();
1572    let domains = collect_composition_binding_domains(schema, &machine_by_instance);
1573    let named_samples = collect_composition_named_type_samples(schema, &machine_by_instance);
1574    let named_bindings = collect_composition_named_bindings(machine_by_instance.values().copied());
1575    let operator_suffix = if deep { "Deep" } else { "Ci" };
1576    let mut instance_invariants = Vec::new();
1577    let mut obligation_invariants = Vec::new();
1578    let uses_u64_max = composition_uses_u64_max(schema, &machine_by_instance);
1579    let session_id_cardinality = if deep {
1580        schema
1581            .deep_domain_overrides
1582            .get("SessionIdValues")
1583            .copied()
1584            .unwrap_or(schema.deep_domain_cardinality)
1585    } else {
1586        default_sample_cardinality(false)
1587    };
1588    let session_id_string_bridge_sample = session_id_string_bridge_sample(
1589        deep && composition_uses_session_id_string_bridge(&machine_by_instance),
1590        &domains,
1591        session_id_cardinality,
1592        &named_samples,
1593        &named_bindings,
1594    );
1595
1596    for instance in &schema.machines {
1597        let Some(machine) = machine_by_instance
1598            .get(instance.instance_id.as_str())
1599            .copied()
1600        else {
1601            continue;
1602        };
1603        for invariant in &machine.invariants {
1604            instance_invariants.push(format!(
1605                "{}_{}",
1606                tla_ident(&instance.instance_id),
1607                tla_ident(&invariant.name)
1608            ));
1609        }
1610    }
1611    for protocol in &schema.handoff_protocols {
1612        let suffix = format!(
1613            "{}_{}",
1614            tla_ident(&protocol.producer_instance),
1615            tla_ident(&protocol.name)
1616        );
1617        if machine_by_instance
1618            .get(protocol.producer_instance.as_str())
1619            .is_some_and(|machine| terminal_closure_required(protocol, machine))
1620        {
1621            obligation_invariants.push(format!("NoOpenObligationsOnTerminal_{suffix}"));
1622        }
1623    }
1624    if schema
1625        .handoff_protocols
1626        .iter()
1627        .any(|protocol| !protocol.allowed_feedback_inputs.is_empty())
1628    {
1629        obligation_invariants.push("OwnerFeedbackHasProtocolProvenance".to_string());
1630    }
1631    pushln!(&mut out, "SPECIFICATION Spec");
1632    if !domains.is_empty() || uses_u64_max {
1633        pushln!(&mut out, "CONSTANTS");
1634        if uses_u64_max {
1635            push_u64_max_cfg_assignment(&mut out);
1636        }
1637        for (name, ty) in domains {
1638            if matches!(
1639                ty,
1640                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1641            ) {
1642                continue;
1643            }
1644            let cardinality = if deep {
1645                schema
1646                    .deep_domain_overrides
1647                    .get(name.as_str())
1648                    .copied()
1649                    .unwrap_or(schema.deep_domain_cardinality)
1650            } else {
1651                default_sample_cardinality(false)
1652            };
1653            if cfg_assignment_requires_model_operator(&ty, &named_bindings) {
1654                writeln!(
1655                    &mut out,
1656                    "  {} <- {}",
1657                    name,
1658                    cfg_assignment_operator_name(&name, operator_suffix),
1659                )
1660                .expect("write to string");
1661            } else {
1662                writeln!(
1663                    &mut out,
1664                    "  {} = {}",
1665                    name,
1666                    render_cfg_domain_assignment(
1667                        &ty,
1668                        cardinality,
1669                        &named_samples,
1670                        &named_bindings,
1671                        false,
1672                        session_id_string_bridge_sample.as_deref(),
1673                    )
1674                )
1675                .expect("write to string");
1676            }
1677        }
1678    }
1679    let behavioral_invariants = schema
1680        .invariants
1681        .iter()
1682        .filter(|invariant| invariant.kind.is_behavioral())
1683        .collect::<Vec<_>>();
1684    // Structural requirements (route/scheduler/priority presence, etc.) are
1685    // static, cheap-to-check predicates over the generated topology. They were
1686    // previously only validated in the Deep witness lane; emit them into the
1687    // standard INVARIANTS block unconditionally so the default (Ci) verify
1688    // profile fails closed on a missing structural requirement instead of
1689    // deferring the check to a Deep-only run.
1690    let structural_invariants = schema
1691        .invariants
1692        .iter()
1693        .filter(|invariant| invariant.kind.is_structural())
1694        .collect::<Vec<_>>();
1695    if !behavioral_invariants.is_empty()
1696        || !structural_invariants.is_empty()
1697        || !instance_invariants.is_empty()
1698        || !obligation_invariants.is_empty()
1699        || deep
1700    {
1701        pushln!(&mut out, "INVARIANTS");
1702        for invariant in behavioral_invariants {
1703            pushln!(&mut out, "  {}", invariant.name);
1704        }
1705        for invariant in structural_invariants {
1706            pushln!(&mut out, "  {}", invariant.name);
1707        }
1708        for invariant_name in instance_invariants {
1709            pushln!(&mut out, "  {}", invariant_name);
1710        }
1711        for invariant_name in obligation_invariants {
1712            pushln!(&mut out, "  {}", invariant_name);
1713        }
1714        if deep {
1715            pushln!(&mut out, "  CoverageInstrumentation");
1716        }
1717    }
1718    pushln!(&mut out, "CONSTRAINTS");
1719    writeln!(
1720        &mut out,
1721        "  {}",
1722        if deep {
1723            "DeepStateConstraint"
1724        } else {
1725            "CiStateConstraint"
1726        }
1727    )
1728    .expect("write to string");
1729
1730    out
1731}
1732
1733pub fn render_composition_witness_cfg(
1734    schema: &CompositionSchema,
1735    witness: &CompositionWitness,
1736) -> String {
1737    render_composition_witness_cfg_from_catalog(schema, witness, &canonical_machine_schemas())
1738}
1739
1740/// [`render_composition_witness_cfg`] against an explicitly supplied machine
1741/// catalog, for compositions whose machines live outside Meerkat's catalog.
1742pub fn render_composition_witness_cfg_with_catalog(
1743    schema: &CompositionSchema,
1744    witness: &CompositionWitness,
1745    machine_catalog: &[MachineSchema],
1746) -> std::result::Result<String, CompositionTlaError> {
1747    validate_supplied_catalog(schema, machine_catalog)?;
1748    Ok(render_composition_witness_cfg_from_catalog(
1749        schema,
1750        witness,
1751        machine_catalog,
1752    ))
1753}
1754
1755fn render_composition_witness_cfg_from_catalog(
1756    schema: &CompositionSchema,
1757    witness: &CompositionWitness,
1758    machine_catalog: &[MachineSchema],
1759) -> String {
1760    let mut out = String::new();
1761    let machine_by_name = machine_catalog
1762        .iter()
1763        .map(|machine| (machine.machine.as_str(), machine))
1764        .collect::<BTreeMap<_, _>>();
1765    let machine_by_instance = schema
1766        .machines
1767        .iter()
1768        .filter_map(|instance| {
1769            machine_by_name
1770                .get(instance.machine_name.as_str())
1771                .copied()
1772                .map(|machine| (instance.instance_id.as_str(), machine))
1773        })
1774        .collect::<BTreeMap<_, _>>();
1775    let domains = collect_composition_binding_domains(schema, &machine_by_instance);
1776    let named_samples =
1777        collect_composition_witness_named_type_samples(schema, witness, &machine_by_instance);
1778    let named_bindings = collect_composition_named_bindings(machine_by_instance.values().copied());
1779    let witness_sample_cardinality = schema
1780        .witness_domain_cardinality
1781        .max(max_named_sample_cardinality(&named_samples));
1782    let operator_suffix = witness_cfg_operator_suffix(witness);
1783    let mut instance_invariants = Vec::new();
1784    let mut obligation_invariants = Vec::new();
1785    let uses_u64_max = composition_uses_u64_max(schema, &machine_by_instance);
1786
1787    for instance in &schema.machines {
1788        let Some(machine) = machine_by_instance
1789            .get(instance.instance_id.as_str())
1790            .copied()
1791        else {
1792            continue;
1793        };
1794        for invariant in &machine.invariants {
1795            instance_invariants.push(format!(
1796                "{}_{}",
1797                tla_ident(&instance.instance_id),
1798                tla_ident(&invariant.name)
1799            ));
1800        }
1801    }
1802    for protocol in &schema.handoff_protocols {
1803        let suffix = format!(
1804            "{}_{}",
1805            tla_ident(&protocol.producer_instance),
1806            tla_ident(&protocol.name)
1807        );
1808        if machine_by_instance
1809            .get(protocol.producer_instance.as_str())
1810            .is_some_and(|machine| terminal_closure_required(protocol, machine))
1811        {
1812            obligation_invariants.push(format!("NoOpenObligationsOnTerminal_{suffix}"));
1813        }
1814    }
1815    if schema
1816        .handoff_protocols
1817        .iter()
1818        .any(|protocol| !protocol.allowed_feedback_inputs.is_empty())
1819    {
1820        obligation_invariants.push("OwnerFeedbackHasProtocolProvenance".to_string());
1821    }
1822
1823    writeln!(
1824        &mut out,
1825        "SPECIFICATION {}",
1826        composition_witness_spec_name(&witness.name)
1827    )
1828    .expect("write to string");
1829    if !domains.is_empty() || uses_u64_max {
1830        pushln!(&mut out, "CONSTANTS");
1831        if uses_u64_max {
1832            push_u64_max_cfg_assignment(&mut out);
1833        }
1834        for (name, ty) in domains {
1835            if matches!(
1836                ty,
1837                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1838            ) {
1839                continue;
1840            }
1841            if cfg_assignment_requires_model_operator(&ty, &named_bindings) {
1842                writeln!(
1843                    &mut out,
1844                    "  {} <- {}",
1845                    name,
1846                    cfg_assignment_operator_name(&name, &operator_suffix),
1847                )
1848                .expect("write to string");
1849            } else {
1850                writeln!(
1851                    &mut out,
1852                    "  {} = {}",
1853                    name,
1854                    render_default_domain_assignment(
1855                        &ty,
1856                        witness_sample_cardinality,
1857                        &named_samples,
1858                        &named_bindings,
1859                        true,
1860                    )
1861                )
1862                .expect("write to string");
1863            }
1864        }
1865    }
1866    let witness_properties = witness
1867        .expected_routes
1868        .iter()
1869        .map(|route| composition_witness_route_property_name(&witness.name, route))
1870        .chain(
1871            witness
1872                .expected_scheduler_rules
1873                .iter()
1874                .map(|rule| composition_witness_scheduler_property_name(&witness.name, rule)),
1875        )
1876        .chain(
1877            witness
1878                .expected_states
1879                .iter()
1880                .enumerate()
1881                .map(|(idx, _)| composition_witness_state_property_name(&witness.name, idx)),
1882        )
1883        .chain(witness.expected_transitions.iter().map(|transition| {
1884            composition_witness_transition_property_name(
1885                &witness.name,
1886                &transition.machine,
1887                &transition.transition,
1888            )
1889        }))
1890        .chain(
1891            witness
1892                .expected_transition_order
1893                .iter()
1894                .enumerate()
1895                .map(|(idx, _)| {
1896                    composition_witness_transition_order_property_name(&witness.name, idx)
1897                }),
1898        )
1899        .collect::<Vec<_>>();
1900    let explicit_witness = CompositionTlaCompiler::witness_has_explicit_progress(witness);
1901    if !schema.invariants.is_empty()
1902        || !instance_invariants.is_empty()
1903        || !obligation_invariants.is_empty()
1904        || (explicit_witness && !witness_properties.is_empty())
1905    {
1906        pushln!(&mut out, "INVARIANTS");
1907        for invariant in &schema.invariants {
1908            pushln!(&mut out, "  {}", invariant.name);
1909        }
1910        for invariant_name in instance_invariants {
1911            pushln!(&mut out, "  {}", invariant_name);
1912        }
1913        for invariant_name in obligation_invariants {
1914            pushln!(&mut out, "  {}", invariant_name);
1915        }
1916        pushln!(&mut out, "  CoverageInstrumentation");
1917        if explicit_witness {
1918            for property in &witness_properties {
1919                pushln!(&mut out, "  {property}");
1920            }
1921        }
1922    }
1923    if !explicit_witness && !witness_properties.is_empty() {
1924        pushln!(&mut out, "PROPERTIES");
1925        for property in witness_properties {
1926            pushln!(&mut out, "  {property}");
1927        }
1928    }
1929    if explicit_witness {
1930        pushln!(&mut out, "ACTION_CONSTRAINTS");
1931        pushln!(
1932            &mut out,
1933            "  {}",
1934            composition_witness_action_constraint_name(&witness.name)
1935        );
1936    }
1937    pushln!(&mut out, "CONSTRAINTS");
1938    writeln!(
1939        &mut out,
1940        "  {}",
1941        composition_witness_state_constraint_name(&witness.name)
1942    )
1943    .expect("write to string");
1944
1945    out
1946}
1947
1948pub fn composition_route_observed_operator_name(route_name: impl AsRef<str>) -> String {
1949    format!("RouteObserved_{}", tla_ident(route_name))
1950}
1951
1952pub fn composition_route_coverage_operator_name(route_name: impl AsRef<str>) -> String {
1953    format!("RouteCoverage_{}", tla_ident(route_name))
1954}
1955
1956pub fn composition_scheduler_triggered_operator_name(rule: &SchedulerRule) -> String {
1957    match rule {
1958        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
1959            "SchedulerTriggered_PreemptWhenReady_{}_{}",
1960            tla_ident(higher),
1961            tla_ident(lower)
1962        ),
1963    }
1964}
1965
1966pub fn composition_scheduler_coverage_operator_name(rule: &SchedulerRule) -> String {
1967    match rule {
1968        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
1969            "SchedulerCoverage_PreemptWhenReady_{}_{}",
1970            tla_ident(higher),
1971            tla_ident(lower)
1972        ),
1973    }
1974}
1975
1976fn max_named_sample_cardinality(named_samples: &BTreeMap<String, BTreeSet<String>>) -> usize {
1977    named_samples.values().map(BTreeSet::len).max().unwrap_or(1)
1978}
1979
1980struct CfgAssignmentOperatorProfile<'a> {
1981    suffix: String,
1982    explicit_values: Option<&'a meerkat_machine_schema::MachineTlcProfile>,
1983    sample_cardinality: usize,
1984    domain_overrides: Option<&'a BTreeMap<String, usize>>,
1985    named_samples: &'a BTreeMap<String, BTreeSet<String>>,
1986    include_string_samples: bool,
1987}
1988
1989fn cfg_assignment_operator_name(domain_name: &str, suffix: impl AsRef<str>) -> String {
1990    format!("{}{}", tla_ident(domain_name), tla_ident(suffix))
1991}
1992
1993fn push_u64_max_cfg_assignment(out: &mut String) {
1994    pushln!(
1995        out,
1996        "  \\* Rust u64::MAX, supplied as a finite TLC model-checking value."
1997    );
1998    writeln!(
1999        out,
2000        "  {} = {}",
2001        TLA_RUST_U64_MAX_CONSTANT, TLC_SAFE_RUST_U64_MAX_VALUE
2002    )
2003    .expect("write to string");
2004}
2005
2006fn witness_cfg_operator_suffix(witness: &CompositionWitness) -> String {
2007    format!("Witness{}", tla_ident(&witness.name))
2008}
2009
2010fn profile_sample_cardinality(
2011    profile: &CfgAssignmentOperatorProfile<'_>,
2012    domain_name: &str,
2013) -> usize {
2014    profile
2015        .domain_overrides
2016        .and_then(|overrides| overrides.get(domain_name).copied())
2017        .unwrap_or(profile.sample_cardinality)
2018}
2019
2020fn profile_sample_cardinality_for_domain(
2021    profile: &CfgAssignmentOperatorProfile<'_>,
2022    domain_name: &str,
2023    ty: &TypeRef,
2024    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2025) -> usize {
2026    let sample_cardinality = profile_sample_cardinality(profile, domain_name);
2027    if profile.suffix == "Ci" && cfg_assignment_requires_model_operator(ty, named_bindings) {
2028        return 0;
2029    }
2030
2031    sample_cardinality
2032}
2033
2034fn machine_cfg_sample_cardinality(schema: &MachineSchema, deep: bool) -> usize {
2035    if !deep && schema.ci_step_limit == Some(1) {
2036        0
2037    } else {
2038        default_sample_cardinality(deep)
2039    }
2040}
2041
2042fn session_id_string_bridge_sample(
2043    enabled: bool,
2044    domains: &BTreeMap<String, TypeRef>,
2045    session_id_cardinality: usize,
2046    named_samples: &BTreeMap<String, BTreeSet<String>>,
2047    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2048) -> Option<String> {
2049    if !enabled {
2050        return None;
2051    }
2052
2053    assert!(
2054        matches!(
2055            domains.get("SessionIdValues"),
2056            Some(TypeRef::Named(name)) if name.as_str() == "SessionId"
2057        ) && matches!(domains.get("StringValues"), Some(TypeRef::String)),
2058        "the SessionId/String native bridge requires both model domains"
2059    );
2060
2061    let sample = sample_values_for_named_type(
2062        "SessionId",
2063        session_id_cardinality.max(1),
2064        named_samples,
2065        named_bindings,
2066    )
2067    .into_iter()
2068    .next();
2069    assert!(
2070        sample.is_some(),
2071        "the SessionId/String native bridge requires a SessionId sample"
2072    );
2073    sample
2074}
2075
2076fn render_cfg_domain_assignment(
2077    ty: &TypeRef,
2078    sample_cardinality: usize,
2079    named_samples: &BTreeMap<String, BTreeSet<String>>,
2080    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2081    include_string_samples: bool,
2082    session_id_string_bridge_sample: Option<&str>,
2083) -> String {
2084    let bridge_applies_to_session_id = matches!(
2085        ty,
2086        TypeRef::Named(name) if name.as_str() == "SessionId"
2087    );
2088    let effective_cardinality = if session_id_string_bridge_sample.is_some()
2089        && (matches!(ty, TypeRef::String) || bridge_applies_to_session_id)
2090    {
2091        sample_cardinality.max(1)
2092    } else {
2093        sample_cardinality
2094    };
2095
2096    if let (TypeRef::String, Some(bridge_sample)) = (ty, session_id_string_bridge_sample) {
2097        let mut samples =
2098            collected_string_samples(effective_cardinality, named_samples, include_string_samples)
2099                .into_iter()
2100                .map(|sample| tla_string(&sample))
2101                .collect::<Vec<_>>();
2102        let baseline_sample_count = samples.len();
2103        samples.retain(|sample| sample != bridge_sample);
2104        samples.insert(0, bridge_sample.to_owned());
2105        // Deep transition coverage makes the equality branch a non-vacuity
2106        // gate. Substitute the shared SessionId value into StringValues rather
2107        // than growing the renderer's actual baseline pool (which can be
2108        // smaller than a configured cardinality) and multiplying the explored
2109        // state space.
2110        if !include_string_samples {
2111            samples.truncate(baseline_sample_count);
2112        }
2113        return format!("{{{}}}", samples.join(", "));
2114    }
2115
2116    render_default_domain_assignment(
2117        ty,
2118        effective_cardinality,
2119        named_samples,
2120        named_bindings,
2121        include_string_samples,
2122    )
2123}
2124
2125fn push_cfg_assignment_operator_definitions(
2126    out: &mut String,
2127    domains: &BTreeMap<String, TypeRef>,
2128    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2129    profile: &CfgAssignmentOperatorProfile<'_>,
2130) -> bool {
2131    let mut wrote = false;
2132    for (name, ty) in domains {
2133        let explicit = profile
2134            .explicit_values
2135            .and_then(|values| profile_explicit_values(values, ty));
2136        if cfg_domain_is_skipped_in_cfg(ty)
2137            || (explicit.is_none() && !cfg_assignment_requires_model_operator(ty, named_bindings))
2138        {
2139            continue;
2140        }
2141        let sample_cardinality =
2142            profile_sample_cardinality_for_domain(profile, name, ty, named_bindings);
2143        let assignment = explicit.map(render_explicit_values).unwrap_or_else(|| {
2144            render_default_domain_assignment(
2145                ty,
2146                sample_cardinality,
2147                profile.named_samples,
2148                named_bindings,
2149                profile.include_string_samples,
2150            )
2151        });
2152        writeln!(
2153            out,
2154            "{} == {}",
2155            cfg_assignment_operator_name(name, &profile.suffix),
2156            assignment
2157        )
2158        .expect("write to string");
2159        wrote = true;
2160    }
2161    if wrote {
2162        pushln!(out);
2163    }
2164    wrote
2165}
2166
2167fn validate_machine_model(schema: &MachineSchema) -> Result<(), CompositionTlaError> {
2168    let invalid = |reason| CompositionTlaError::InvalidTlcModel {
2169        machine: schema.machine.to_string(),
2170        reason,
2171    };
2172    schema
2173        .validate()
2174        .map_err(|error| invalid(error.to_string()))?;
2175    if let Some(model) = &schema.tlc_model {
2176        let domains = collect_binding_domains(schema);
2177        for profile in [&model.ci, &model.deep] {
2178            for name in profile.named_values.keys() {
2179                if !domains.values().any(|ty| match ty {
2180                    TypeRef::Named(id) => id == name,
2181                    TypeRef::Enum(id) => id.as_str() == name.as_str(),
2182                    _ => false,
2183                }) {
2184                    return Err(invalid(format!(
2185                        "explicit sample type {name} has no standalone model domain"
2186                    )));
2187                }
2188            }
2189        }
2190    }
2191    Ok(())
2192}
2193
2194fn profile_explicit_values<'a>(
2195    profile: &'a meerkat_machine_schema::MachineTlcProfile,
2196    ty: &TypeRef,
2197) -> Option<&'a [meerkat_machine_schema::TlcValue]> {
2198    let name = match ty {
2199        TypeRef::Named(name) => name.as_str(),
2200        TypeRef::Enum(name) => name.as_str(),
2201        _ => return None,
2202    };
2203    profile
2204        .named_values
2205        .iter()
2206        .find(|(id, _)| id.as_str() == name)
2207        .map(|(_, values)| values.as_slice())
2208}
2209
2210fn machine_explicit_values<'a>(
2211    schema: &'a MachineSchema,
2212    deep: bool,
2213    ty: &TypeRef,
2214) -> Option<&'a [meerkat_machine_schema::TlcValue]> {
2215    let model = schema.tlc_model.as_ref()?;
2216    profile_explicit_values(if deep { &model.deep } else { &model.ci }, ty)
2217}
2218
2219fn render_explicit_values(values: &[meerkat_machine_schema::TlcValue]) -> String {
2220    format!(
2221        "{{{}}}",
2222        values
2223            .iter()
2224            .map(render_explicit_value)
2225            .collect::<Vec<_>>()
2226            .join(", ")
2227    )
2228}
2229
2230fn render_explicit_value(value: &meerkat_machine_schema::TlcValue) -> String {
2231    use meerkat_machine_schema::TlcValue;
2232    match value {
2233        TlcValue::Bool(value) => if *value { "TRUE" } else { "FALSE" }.into(),
2234        TlcValue::U64(value) if *value == u64::MAX => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
2235        TlcValue::U64(value) => value.to_string(),
2236        TlcValue::String(value) => tla_string(value),
2237        TlcValue::None => "None".into(),
2238        TlcValue::Some(value) => format!("Some({})", render_explicit_value(value)),
2239        TlcValue::Set(values) => render_explicit_values(values),
2240        TlcValue::Record(fields) => format!(
2241            "[{}]",
2242            fields
2243                .iter()
2244                .map(|(field, value)| format!(
2245                    "{} |-> {}",
2246                    tla_ident(field.as_str()),
2247                    render_explicit_value(value)
2248                ))
2249                .collect::<Vec<_>>()
2250                .join(", ")
2251        ),
2252    }
2253}
2254
2255fn cfg_domain_is_skipped_in_cfg(ty: &TypeRef) -> bool {
2256    matches!(
2257        ty,
2258        TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
2259    )
2260}
2261
2262fn cfg_assignment_requires_model_operator(
2263    ty: &TypeRef,
2264    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2265) -> bool {
2266    match ty {
2267        TypeRef::Named(name) => {
2268            require_named_binding(named_bindings, name.as_str()).renders_cfg_hostile_record()
2269        }
2270        TypeRef::Enum(name) => {
2271            require_named_binding(named_bindings, name.as_str()).renders_cfg_hostile_record()
2272        }
2273        TypeRef::Set(inner) | TypeRef::Seq(inner) => {
2274            cfg_assignment_requires_model_operator(inner, named_bindings)
2275        }
2276        TypeRef::Option(_) | TypeRef::Map(_, _) => true,
2277        TypeRef::Bool | TypeRef::U32 | TypeRef::U64 | TypeRef::String => false,
2278    }
2279}
2280
2281trait CfgRecordRendering {
2282    fn renders_cfg_hostile_record(&self) -> bool;
2283}
2284
2285impl CfgRecordRendering for meerkat_machine_schema::RustTypeAtom {
2286    fn renders_cfg_hostile_record(&self) -> bool {
2287        match self {
2288            meerkat_machine_schema::RustTypeAtom::TypePathStruct { .. } => true,
2289            meerkat_machine_schema::RustTypeAtom::TypePathEnum {
2290                structural_variants,
2291                ..
2292            } => !structural_variants.is_empty(),
2293            _ => false,
2294        }
2295    }
2296}
2297
2298pub fn composition_witness_cfg_name(name: impl AsRef<str>) -> String {
2299    format!("witness-{}.cfg", tla_ident(name.as_ref()))
2300}
2301
2302fn composition_witness_route_property_name(
2303    witness: impl AsRef<str>,
2304    route_name: impl AsRef<str>,
2305) -> String {
2306    format!(
2307        "WitnessRouteObserved_{}_{}",
2308        tla_ident(witness.as_ref()),
2309        tla_ident(route_name)
2310    )
2311}
2312
2313fn composition_witness_scheduler_property_name(
2314    witness: impl AsRef<str>,
2315    rule: &SchedulerRule,
2316) -> String {
2317    format!(
2318        "WitnessSchedulerTriggered_{}_{}",
2319        tla_ident(witness.as_ref()),
2320        tla_ident(witness_scheduler_rule_label(rule))
2321    )
2322}
2323
2324fn composition_witness_state_property_name(witness: impl AsRef<str>, index: usize) -> String {
2325    format!(
2326        "WitnessStateObserved_{}_{}",
2327        tla_ident(witness.as_ref()),
2328        index + 1
2329    )
2330}
2331
2332fn composition_witness_transition_property_name(
2333    witness: impl AsRef<str>,
2334    machine: impl AsRef<str>,
2335    transition: impl AsRef<str>,
2336) -> String {
2337    format!(
2338        "WitnessTransitionObserved_{}_{}_{}",
2339        tla_ident(witness.as_ref()),
2340        tla_ident(machine),
2341        tla_ident(transition)
2342    )
2343}
2344
2345fn composition_witness_transition_order_property_name(
2346    witness: impl AsRef<str>,
2347    index: usize,
2348) -> String {
2349    format!(
2350        "WitnessTransitionOrder_{}_{}",
2351        tla_ident(witness.as_ref()),
2352        index + 1
2353    )
2354}
2355
2356fn witness_scheduler_rule_label(rule: &SchedulerRule) -> String {
2357    match rule {
2358        SchedulerRule::PreemptWhenReady { higher, lower } => {
2359            format!("PreemptWhenReady_{}_{}", higher, lower)
2360        }
2361    }
2362}
2363
2364fn composition_witness_init_name(name: impl AsRef<str>) -> String {
2365    format!("WitnessInit_{}", tla_ident(name.as_ref()))
2366}
2367
2368fn composition_witness_next_name(name: impl AsRef<str>) -> String {
2369    format!("WitnessNext_{}", tla_ident(name.as_ref()))
2370}
2371
2372fn composition_witness_spec_name(name: impl AsRef<str>) -> String {
2373    format!("WitnessSpec_{}", tla_ident(name.as_ref()))
2374}
2375
2376fn composition_witness_fairness_name(name: impl AsRef<str>, index: usize) -> String {
2377    format!("WitnessFairness_{}_{}", tla_ident(name.as_ref()), index + 1)
2378}
2379
2380fn composition_witness_completion_name(name: impl AsRef<str>) -> String {
2381    format!("WitnessScriptComplete_{}", tla_ident(name.as_ref()))
2382}
2383
2384fn composition_witness_action_constraint_name(name: impl AsRef<str>) -> String {
2385    format!("WitnessNoPrematureStutter_{}", tla_ident(name.as_ref()))
2386}
2387
2388fn composition_witness_state_constraint_name(name: impl AsRef<str>) -> String {
2389    format!("WitnessStateConstraint_{}", tla_ident(name.as_ref()))
2390}
2391
2392pub fn render_composition_semantic_model(
2393    schema: &CompositionSchema,
2394) -> std::result::Result<String, CompositionTlaError> {
2395    render_composition_semantic_model_from_catalog(schema, &canonical_machine_schemas())
2396}
2397
2398/// [`render_composition_semantic_model`] against an explicitly supplied
2399/// machine catalog, for compositions whose machines live outside Meerkat's
2400/// catalog.
2401pub fn render_composition_semantic_model_with_catalog(
2402    schema: &CompositionSchema,
2403    machine_catalog: &[MachineSchema],
2404) -> std::result::Result<String, CompositionTlaError> {
2405    validate_supplied_catalog(schema, machine_catalog)?;
2406    render_composition_semantic_model_from_catalog(schema, machine_catalog)
2407}
2408
2409fn render_composition_semantic_model_from_catalog(
2410    schema: &CompositionSchema,
2411    machine_catalog: &[MachineSchema],
2412) -> std::result::Result<String, CompositionTlaError> {
2413    // Fail closed: compiler construction (unknown machine schema, empty
2414    // catalog) and rendering (unresolved route component, helper-call cycle,
2415    // absent obligation field) used to be swallowed into `String::new()`,
2416    // producing a broken-but-passing model. Propagate the typed error so
2417    // `machine-generate` / `machine-check-drift` fail on malformed input.
2418    let compiler = CompositionTlaCompiler::new(schema, machine_catalog)
2419        .map_err(CompositionTlaError::Compile)?;
2420    compiler.render()
2421}
2422
2423/// Renders the generated per-composition Rust module (Track-B wave-b V2).
2424///
2425/// The emitted module is the typed seam between the composition's route
2426/// schema and the runtime composition dispatcher. It declares:
2427///
2428/// * generated producer/effect/input/signal/field identity facts,
2429/// * `TypedRoutedInput` / `TypedRoutedSignal` descriptors carrying typed
2430///   route targets and `(FieldId, FieldId)` binding pairs,
2431/// * a `route_to_input(instance, effect_variant) -> Option<TypedRoutedInput>`
2432///   fact resolver for input-kind routes, and
2433/// * a `route_to_signal(instance, effect_variant) -> Option<TypedRoutedSignal>`
2434///   fact resolver for signal-kind routes.
2435///
2436/// Returns `None` when the composition declares no driver descriptor; the
2437/// driver descriptor continues to carry the Rust emission path for xtask
2438/// consumers.
2439pub fn render_composition_driver(schema: &CompositionSchema) -> Option<String> {
2440    render_composition_driver_from_catalog(schema, &canonical_machine_schemas())
2441}
2442
2443/// [`render_composition_driver`] against an explicitly supplied machine
2444/// catalog, for compositions whose machines live outside Meerkat's catalog.
2445pub fn render_composition_driver_with_catalog(
2446    schema: &CompositionSchema,
2447    machine_catalog: &[MachineSchema],
2448) -> std::result::Result<Option<String>, CompositionTlaError> {
2449    validate_supplied_catalog(schema, machine_catalog)?;
2450    Ok(render_composition_driver_from_catalog(
2451        schema,
2452        machine_catalog,
2453    ))
2454}
2455
2456fn render_composition_driver_from_catalog(
2457    schema: &CompositionSchema,
2458    machine_catalog: &[MachineSchema],
2459) -> Option<String> {
2460    let driver = schema.driver.as_ref()?;
2461
2462    let machine_by_name = machine_catalog
2463        .iter()
2464        .map(|machine| (machine.machine.as_str(), machine))
2465        .collect::<BTreeMap<_, _>>();
2466
2467    let mut producers: Vec<(&str, &MachineSchema)> = Vec::new();
2468    let mut seen: BTreeSet<&str> = BTreeSet::new();
2469    for instance in &schema.machines {
2470        if !seen.insert(instance.instance_id.as_str()) {
2471            continue;
2472        }
2473        let Some(machine) = machine_by_name.get(instance.machine_name.as_str()).copied() else {
2474            continue;
2475        };
2476        producers.push((instance.instance_id.as_str(), machine));
2477    }
2478
2479    let composition_name = schema.name.as_str();
2480    let mut effect_variants_by_producer: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
2481    let mut input_variants: BTreeSet<&str> = BTreeSet::new();
2482    let mut signal_variants: BTreeSet<&str> = BTreeSet::new();
2483    let mut fields: BTreeSet<&str> = BTreeSet::new();
2484
2485    for route in &schema.routes {
2486        effect_variants_by_producer
2487            .entry(route.from_machine.as_str())
2488            .or_default()
2489            .insert(route.effect_variant.as_str());
2490
2491        match route.to.kind {
2492            RouteTargetKind::Input => {
2493                input_variants.insert(route.to.input_variant.as_str());
2494            }
2495            RouteTargetKind::Signal => {
2496                signal_variants.insert(route.to.input_variant.as_str());
2497            }
2498        }
2499
2500        for binding in &route.bindings {
2501            fields.insert(binding.to_field.as_str());
2502            if let RouteBindingSource::Field { from_field, .. } = &binding.source {
2503                fields.insert(from_field.as_str());
2504            }
2505        }
2506    }
2507    for closure in &driver.refusal_closures {
2508        input_variants.insert(closure.feedback_input.as_str());
2509        for binding in &closure.field_bindings {
2510            fields.insert(binding.input_field.as_str());
2511            if let DriverRefusalFieldSource::EffectField(source_field) = &binding.source {
2512                fields.insert(source_field.as_str());
2513            }
2514        }
2515    }
2516
2517    let mut out = String::new();
2518    pushln!(
2519        &mut out,
2520        "// @generated — composition module for `{composition_name}`"
2521    );
2522    pushln!(
2523        &mut out,
2524        "// DO NOT EDIT. Emitted by meerkat_machine_codegen::render_composition_driver."
2525    );
2526    pushln!(
2527        &mut out,
2528        "// Source of truth: catalog::compositions::{composition_name}"
2529    );
2530    pushln!(
2531        &mut out,
2532        "// Driver: `{}` (rust path: `{}`).",
2533        driver.name,
2534        driver.rust.module_path
2535    );
2536    pushln!(&mut out, "#![allow(clippy::expect_used)]");
2537    out.push('\n');
2538
2539    pushln!(
2540        &mut out,
2541        "use meerkat_machine_schema::identity::{{CompositionId, EffectVariantId, FieldId, InputVariantId, MachineId, MachineInstanceId, RouteId, SignalVariantId}};"
2542    );
2543    for import in &driver.rust.required_imports {
2544        pushln!(&mut out, "{import}");
2545    }
2546    out.push('\n');
2547
2548    pushln!(
2549        &mut out,
2550        "/// Typed route descriptor resolved from generated composition facts."
2551    );
2552    pushln!(&mut out, "///");
2553    pushln!(
2554        &mut out,
2555        "/// `bindings` lists producer-field → consumer-field pairs in the"
2556    );
2557    pushln!(&mut out, "/// order declared by the composition schema.");
2558    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2559    pushln!(&mut out, "pub struct TypedRoutedInput {{");
2560    pushln!(&mut out, "    pub route_id: RouteId,");
2561    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2562    pushln!(&mut out, "    pub variant: InputVariantId,");
2563    pushln!(&mut out, "    pub bindings: Vec<(FieldId, FieldId)>,");
2564    pushln!(&mut out, "}}");
2565    out.push('\n');
2566
2567    pushln!(
2568        &mut out,
2569        "/// Typed signal-route descriptor resolved from generated composition facts."
2570    );
2571    pushln!(&mut out, "///");
2572    pushln!(
2573        &mut out,
2574        "/// `bindings` lists producer-field → consumer-field pairs in the"
2575    );
2576    pushln!(&mut out, "/// order declared by the composition schema.");
2577    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2578    pushln!(&mut out, "pub struct TypedRoutedSignal {{");
2579    pushln!(&mut out, "    pub route_id: RouteId,");
2580    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2581    pushln!(&mut out, "    pub variant: SignalVariantId,");
2582    pushln!(&mut out, "    pub bindings: Vec<(FieldId, FieldId)>,");
2583    pushln!(&mut out, "}}");
2584    out.push('\n');
2585
2586    pushln!(
2587        &mut out,
2588        "/// Generated source for one consumer-refusal feedback field."
2589    );
2590    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2591    pushln!(&mut out, "pub enum GeneratedRefusalFieldSource {{");
2592    pushln!(&mut out, "    EffectField(FieldId),");
2593    pushln!(&mut out, "    ConsumerErrorCode,");
2594    pushln!(&mut out, "    ConsumerErrorMessage,");
2595    pushln!(&mut out, "}}");
2596    out.push('\n');
2597
2598    pushln!(
2599        &mut out,
2600        "/// Generated feedback closure for a consumer-refused dispatch."
2601    );
2602    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2603    pushln!(&mut out, "pub struct TypedDispatchRefusalClosure {{");
2604    pushln!(&mut out, "    pub route_id: RouteId,");
2605    pushln!(&mut out, "    pub producer_instance: MachineInstanceId,");
2606    pushln!(&mut out, "    pub effect_variant: EffectVariantId,");
2607    pushln!(&mut out, "    pub feedback_instance: MachineInstanceId,");
2608    pushln!(&mut out, "    pub feedback_input: InputVariantId,");
2609    pushln!(
2610        &mut out,
2611        "    pub field_bindings: Vec<(GeneratedRefusalFieldSource, FieldId)>,"
2612    );
2613    pushln!(&mut out, "}}");
2614    out.push('\n');
2615
2616    pushln!(
2617        &mut out,
2618        "/// Generated producer identity declared by this composition."
2619    );
2620    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2621    pushln!(&mut out, "pub struct ProducerFacts {{");
2622    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2623    pushln!(&mut out, "    pub machine: MachineId,");
2624    pushln!(&mut out, "}}");
2625    out.push('\n');
2626
2627    pushln!(&mut out, "/// Composition id for this generated fact set.");
2628    pushln!(&mut out, "pub fn composition_id() -> CompositionId {{");
2629    pushln!(
2630        &mut out,
2631        "    CompositionId::parse(\"{composition_name}\").expect(\"composition slug\")"
2632    );
2633    pushln!(&mut out, "}}");
2634    out.push('\n');
2635
2636    pushln!(&mut out, "/// Generated producer instance facts.");
2637    pushln!(&mut out, "pub mod producers {{");
2638    pushln!(&mut out, "    use super::*;");
2639    for (instance_id, machine) in &producers {
2640        let fn_name = to_snake_case_local(instance_id);
2641        let machine_name = machine.machine.as_str();
2642        pushln!(&mut out);
2643        pushln!(&mut out, "    pub fn {fn_name}() -> ProducerFacts {{");
2644        pushln!(&mut out, "        ProducerFacts {{");
2645        pushln!(
2646            &mut out,
2647            "            instance_id: {fn_name}_instance_id(),"
2648        );
2649        pushln!(&mut out, "            machine: {fn_name}_machine_id(),");
2650        pushln!(&mut out, "        }}");
2651        pushln!(&mut out, "    }}");
2652        pushln!(&mut out);
2653        pushln!(
2654            &mut out,
2655            "    pub fn {fn_name}_instance_id() -> MachineInstanceId {{"
2656        );
2657        pushln!(
2658            &mut out,
2659            "        MachineInstanceId::parse(\"{instance_id}\").expect(\"producer instance slug\")"
2660        );
2661        pushln!(&mut out, "    }}");
2662        pushln!(&mut out);
2663        pushln!(
2664            &mut out,
2665            "    pub fn {fn_name}_machine_id() -> MachineId {{"
2666        );
2667        pushln!(
2668            &mut out,
2669            "        MachineId::parse(\"{machine_name}\").expect(\"producer machine slug\")"
2670        );
2671        pushln!(&mut out, "    }}");
2672    }
2673    pushln!(&mut out, "}}");
2674    out.push('\n');
2675
2676    pushln!(&mut out, "/// Generated producer-side effect variant ids.");
2677    pushln!(&mut out, "pub mod effects {{");
2678    for (instance_id, _) in &producers {
2679        let producer_mod = to_snake_case_local(instance_id);
2680        pushln!(&mut out);
2681        pushln!(&mut out, "    pub mod {producer_mod} {{");
2682        pushln!(&mut out, "        use super::super::*;");
2683        if let Some(effect_variants) = effect_variants_by_producer.get(instance_id) {
2684            for effect_variant in effect_variants {
2685                let fn_name = to_snake_case_local(effect_variant);
2686                pushln!(&mut out);
2687                pushln!(&mut out, "        pub fn {fn_name}() -> EffectVariantId {{");
2688                pushln!(
2689                    &mut out,
2690                    "            EffectVariantId::parse(\"{effect_variant}\").expect(\"effect variant slug\")"
2691                );
2692                pushln!(&mut out, "        }}");
2693            }
2694        }
2695        pushln!(&mut out, "    }}");
2696    }
2697    pushln!(&mut out, "}}");
2698    out.push('\n');
2699
2700    pushln!(&mut out, "/// Generated consumer input variant ids.");
2701    pushln!(&mut out, "pub mod inputs {{");
2702    pushln!(&mut out, "    use super::*;");
2703    for input_variant in &input_variants {
2704        let fn_name = to_snake_case_local(input_variant);
2705        pushln!(&mut out);
2706        pushln!(&mut out, "    pub fn {fn_name}() -> InputVariantId {{");
2707        pushln!(
2708            &mut out,
2709            "        InputVariantId::parse(\"{input_variant}\").expect(\"input variant slug\")"
2710        );
2711        pushln!(&mut out, "    }}");
2712    }
2713    pushln!(&mut out, "}}");
2714    out.push('\n');
2715
2716    pushln!(&mut out, "/// Generated consumer signal variant ids.");
2717    pushln!(&mut out, "pub mod signals {{");
2718    pushln!(&mut out, "    use super::*;");
2719    for signal_variant in &signal_variants {
2720        let fn_name = to_snake_case_local(signal_variant);
2721        pushln!(&mut out);
2722        pushln!(&mut out, "    pub fn {fn_name}() -> SignalVariantId {{");
2723        pushln!(
2724            &mut out,
2725            "        SignalVariantId::parse(\"{signal_variant}\").expect(\"signal variant slug\")"
2726        );
2727        pushln!(&mut out, "    }}");
2728    }
2729    pushln!(&mut out, "}}");
2730    out.push('\n');
2731
2732    pushln!(
2733        &mut out,
2734        "/// Generated field ids referenced by route bindings."
2735    );
2736    pushln!(&mut out, "pub mod fields {{");
2737    pushln!(&mut out, "    use super::*;");
2738    for field in &fields {
2739        let fn_name = to_snake_case_local(field);
2740        pushln!(&mut out);
2741        pushln!(&mut out, "    pub fn {fn_name}() -> FieldId {{");
2742        pushln!(
2743            &mut out,
2744            "        FieldId::parse(\"{field}\").expect(\"field slug\")"
2745        );
2746        pushln!(&mut out, "    }}");
2747    }
2748    pushln!(&mut out, "}}");
2749    out.push('\n');
2750
2751    for route in schema
2752        .routes
2753        .iter()
2754        .filter(|route| route.to.kind == RouteTargetKind::Input)
2755    {
2756        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2757        let target_machine = route.to.machine.as_str();
2758        let target_variant = route.to.input_variant.as_str();
2759        pushln!(
2760            &mut out,
2761            "/// Generated facts for input route `{}`.",
2762            route.name.as_str()
2763        );
2764        pushln!(&mut out, "pub fn {route_fn}() -> TypedRoutedInput {{");
2765        pushln!(&mut out, "    TypedRoutedInput {{");
2766        pushln!(
2767            &mut out,
2768            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2769            route.name.as_str()
2770        );
2771        pushln!(
2772            &mut out,
2773            "        instance_id: MachineInstanceId::parse(\"{target_machine}\").expect(\"composition instance slug\"),"
2774        );
2775        pushln!(
2776            &mut out,
2777            "        variant: InputVariantId::parse(\"{target_variant}\").expect(\"composition input slug\"),"
2778        );
2779        if route.bindings.is_empty() {
2780            pushln!(&mut out, "        bindings: Vec::new(),");
2781        } else {
2782            pushln!(&mut out, "        bindings: vec![");
2783            for binding in &route.bindings {
2784                let from_field = match &binding.source {
2785                    RouteBindingSource::Field { from_field, .. } => from_field.as_str(),
2786                    RouteBindingSource::Literal(_) | RouteBindingSource::OwnerProvided => {
2787                        continue;
2788                    }
2789                };
2790                let to_field = binding.to_field.as_str();
2791                pushln!(
2792                    &mut out,
2793                    "            (FieldId::parse(\"{from_field}\").expect(\"route producer field slug\"), FieldId::parse(\"{to_field}\").expect(\"route consumer field slug\")),"
2794                );
2795            }
2796            pushln!(&mut out, "        ],");
2797        }
2798        pushln!(&mut out, "    }}");
2799        pushln!(&mut out, "}}");
2800        out.push('\n');
2801    }
2802
2803    for closure in &driver.refusal_closures {
2804        let route = schema
2805            .routes
2806            .iter()
2807            .find(|route| route.name == closure.dispatch_route)?;
2808        let closure_fn = format!(
2809            "refusal_closure_{}",
2810            to_snake_case_local(closure.dispatch_route.as_str())
2811        );
2812        pushln!(
2813            &mut out,
2814            "/// Generated consumer-refusal closure for route `{}`.",
2815            closure.dispatch_route
2816        );
2817        pushln!(
2818            &mut out,
2819            "pub fn {closure_fn}() -> TypedDispatchRefusalClosure {{"
2820        );
2821        pushln!(&mut out, "    TypedDispatchRefusalClosure {{");
2822        pushln!(
2823            &mut out,
2824            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2825            closure.dispatch_route
2826        );
2827        pushln!(
2828            &mut out,
2829            "        producer_instance: MachineInstanceId::parse(\"{}\").expect(\"producer instance slug\"),",
2830            route.from_machine
2831        );
2832        pushln!(
2833            &mut out,
2834            "        effect_variant: EffectVariantId::parse(\"{}\").expect(\"effect variant slug\"),",
2835            route.effect_variant
2836        );
2837        pushln!(
2838            &mut out,
2839            "        feedback_instance: MachineInstanceId::parse(\"{}\").expect(\"feedback instance slug\"),",
2840            closure.feedback_instance
2841        );
2842        pushln!(
2843            &mut out,
2844            "        feedback_input: InputVariantId::parse(\"{}\").expect(\"feedback input slug\"),",
2845            closure.feedback_input
2846        );
2847        pushln!(&mut out, "        field_bindings: vec![");
2848        for binding in &closure.field_bindings {
2849            let source = match &binding.source {
2850                DriverRefusalFieldSource::EffectField(field) => format!(
2851                    "GeneratedRefusalFieldSource::EffectField(FieldId::parse(\"{}\").expect(\"effect field slug\"))",
2852                    field
2853                ),
2854                DriverRefusalFieldSource::ConsumerErrorCode => {
2855                    "GeneratedRefusalFieldSource::ConsumerErrorCode".to_owned()
2856                }
2857                DriverRefusalFieldSource::ConsumerErrorMessage => {
2858                    "GeneratedRefusalFieldSource::ConsumerErrorMessage".to_owned()
2859                }
2860            };
2861            pushln!(
2862                &mut out,
2863                "            ({source}, FieldId::parse(\"{}\").expect(\"feedback field slug\")),",
2864                binding.input_field
2865            );
2866        }
2867        pushln!(&mut out, "        ],");
2868        pushln!(&mut out, "    }}");
2869        pushln!(&mut out, "}}");
2870        out.push('\n');
2871    }
2872
2873    pushln!(
2874        &mut out,
2875        "/// Resolve a generated route to its consumer-refusal feedback closure."
2876    );
2877    pushln!(
2878        &mut out,
2879        "pub fn refusal_closure_for_route(route_id: &RouteId) -> Option<TypedDispatchRefusalClosure> {{"
2880    );
2881    for closure in &driver.refusal_closures {
2882        let closure_fn = format!(
2883            "refusal_closure_{}",
2884            to_snake_case_local(closure.dispatch_route.as_str())
2885        );
2886        pushln!(
2887            &mut out,
2888            "    if route_id == &RouteId::parse(\"{}\").expect(\"route slug\") {{",
2889            closure.dispatch_route
2890        );
2891        pushln!(&mut out, "        return Some({closure_fn}());");
2892        pushln!(&mut out, "    }}");
2893    }
2894    pushln!(&mut out, "    None");
2895    pushln!(&mut out, "}}");
2896    out.push('\n');
2897
2898    for route in schema
2899        .routes
2900        .iter()
2901        .filter(|route| route.to.kind == RouteTargetKind::Signal)
2902    {
2903        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2904        let target_machine = route.to.machine.as_str();
2905        let target_variant = route.to.input_variant.as_str();
2906        pushln!(
2907            &mut out,
2908            "/// Generated facts for signal route `{}`.",
2909            route.name.as_str()
2910        );
2911        pushln!(&mut out, "pub fn {route_fn}() -> TypedRoutedSignal {{");
2912        pushln!(&mut out, "    TypedRoutedSignal {{");
2913        pushln!(
2914            &mut out,
2915            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2916            route.name.as_str()
2917        );
2918        pushln!(
2919            &mut out,
2920            "        instance_id: MachineInstanceId::parse(\"{target_machine}\").expect(\"composition instance slug\"),"
2921        );
2922        pushln!(
2923            &mut out,
2924            "        variant: SignalVariantId::parse(\"{target_variant}\").expect(\"composition signal slug\"),"
2925        );
2926        if route.bindings.is_empty() {
2927            pushln!(&mut out, "        bindings: Vec::new(),");
2928        } else {
2929            pushln!(&mut out, "        bindings: vec![");
2930            for binding in &route.bindings {
2931                let from_field = match &binding.source {
2932                    RouteBindingSource::Field { from_field, .. } => from_field.as_str(),
2933                    RouteBindingSource::Literal(_) | RouteBindingSource::OwnerProvided => {
2934                        continue;
2935                    }
2936                };
2937                let to_field = binding.to_field.as_str();
2938                pushln!(
2939                    &mut out,
2940                    "            (FieldId::parse(\"{from_field}\").expect(\"route producer field slug\"), FieldId::parse(\"{to_field}\").expect(\"route consumer field slug\")),"
2941                );
2942            }
2943            pushln!(&mut out, "        ],");
2944        }
2945        pushln!(&mut out, "    }}");
2946        pushln!(&mut out, "}}");
2947        out.push('\n');
2948    }
2949
2950    pushln!(
2951        &mut out,
2952        "/// Resolve a producer `(instance, effect_variant)` to generated input-route facts."
2953    );
2954    pushln!(&mut out, "pub fn route_to_input(");
2955    pushln!(&mut out, "    producer_instance: &MachineInstanceId,");
2956    pushln!(&mut out, "    effect_variant: &EffectVariantId,");
2957    pushln!(&mut out, ") -> Option<TypedRoutedInput> {{");
2958    for route in schema
2959        .routes
2960        .iter()
2961        .filter(|route| route.to.kind == RouteTargetKind::Input)
2962    {
2963        let producer_mod = to_snake_case_local(route.from_machine.as_str());
2964        let effect_fn = to_snake_case_local(route.effect_variant.as_str());
2965        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2966        pushln!(
2967            &mut out,
2968            "    if producer_instance == &producers::{producer_mod}_instance_id() && effect_variant == &effects::{producer_mod}::{effect_fn}() {{"
2969        );
2970        pushln!(&mut out, "        return Some({route_fn}());");
2971        pushln!(&mut out, "    }}");
2972    }
2973    pushln!(&mut out, "    None");
2974    pushln!(&mut out, "}}");
2975    out.push('\n');
2976
2977    pushln!(
2978        &mut out,
2979        "/// Resolve a producer `(instance, effect_variant)` to generated signal-route facts."
2980    );
2981    pushln!(&mut out, "pub fn route_to_signal(");
2982    pushln!(&mut out, "    producer_instance: &MachineInstanceId,");
2983    pushln!(&mut out, "    effect_variant: &EffectVariantId,");
2984    pushln!(&mut out, ") -> Option<TypedRoutedSignal> {{");
2985    for route in schema
2986        .routes
2987        .iter()
2988        .filter(|route| route.to.kind == RouteTargetKind::Signal)
2989    {
2990        let producer_mod = to_snake_case_local(route.from_machine.as_str());
2991        let effect_fn = to_snake_case_local(route.effect_variant.as_str());
2992        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2993        pushln!(
2994            &mut out,
2995            "    if producer_instance == &producers::{producer_mod}_instance_id() && effect_variant == &effects::{producer_mod}::{effect_fn}() {{"
2996        );
2997        pushln!(&mut out, "        return Some({route_fn}());");
2998        pushln!(&mut out, "    }}");
2999    }
3000    pushln!(&mut out, "    None");
3001    pushln!(&mut out, "}}");
3002    out.push('\n');
3003
3004    let driver_type = driver.rust.driver_type.as_ref();
3005    let store_plan_type = driver.rust.store_plan_type.as_ref();
3006    let work_type = driver.rust.work_type.as_ref();
3007    let decision_type = driver.rust.decision_type.as_ref();
3008
3009    pushln!(
3010        &mut out,
3011        "/// Generated route target selected by `{driver_type}`."
3012    );
3013    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3014    pushln!(&mut out, "pub enum GeneratedRouteTarget {{");
3015    pushln!(&mut out, "    Input(TypedRoutedInput),");
3016    pushln!(&mut out, "    Signal(TypedRoutedSignal),");
3017    pushln!(&mut out, "}}");
3018    out.push('\n');
3019
3020    pushln!(
3021        &mut out,
3022        "/// Generated store plan emitted by `{driver_type}`."
3023    );
3024    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3025    pushln!(&mut out, "pub struct {store_plan_type} {{");
3026    pushln!(&mut out, "    pub target: GeneratedRouteTarget,");
3027    pushln!(&mut out, "}}");
3028    pushln!(&mut out);
3029    pushln!(&mut out, "impl {store_plan_type} {{");
3030    pushln!(
3031        &mut out,
3032        "    pub fn input(route: TypedRoutedInput) -> Self {{"
3033    );
3034    pushln!(
3035        &mut out,
3036        "        Self {{ target: GeneratedRouteTarget::Input(route) }}"
3037    );
3038    pushln!(&mut out, "    }}");
3039    pushln!(&mut out);
3040    pushln!(
3041        &mut out,
3042        "    pub fn signal(route: TypedRoutedSignal) -> Self {{"
3043    );
3044    pushln!(
3045        &mut out,
3046        "        Self {{ target: GeneratedRouteTarget::Signal(route) }}"
3047    );
3048    pushln!(&mut out, "    }}");
3049    pushln!(&mut out);
3050    pushln!(&mut out, "    pub fn route_id(&self) -> &RouteId {{");
3051    pushln!(&mut out, "        match &self.target {{");
3052    pushln!(
3053        &mut out,
3054        "            GeneratedRouteTarget::Input(route) => &route.route_id,"
3055    );
3056    pushln!(
3057        &mut out,
3058        "            GeneratedRouteTarget::Signal(route) => &route.route_id,"
3059    );
3060    pushln!(&mut out, "        }}");
3061    pushln!(&mut out, "    }}");
3062    pushln!(&mut out, "}}");
3063    out.push('\n');
3064
3065    pushln!(
3066        &mut out,
3067        "/// Generated work packet consumed by `{driver_type}`."
3068    );
3069    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3070    pushln!(&mut out, "pub struct {work_type} {{");
3071    pushln!(&mut out, "    pub producer_instance: MachineInstanceId,");
3072    pushln!(&mut out, "    pub effect_variant: EffectVariantId,");
3073    pushln!(&mut out, "}}");
3074    pushln!(&mut out);
3075    pushln!(&mut out, "impl {work_type} {{");
3076    pushln!(
3077        &mut out,
3078        "    pub fn new(producer_instance: MachineInstanceId, effect_variant: EffectVariantId) -> Self {{"
3079    );
3080    pushln!(
3081        &mut out,
3082        "        Self {{ producer_instance, effect_variant }}"
3083    );
3084    pushln!(&mut out, "    }}");
3085    pushln!(&mut out, "}}");
3086    out.push('\n');
3087
3088    pushln!(
3089        &mut out,
3090        "/// Generated routing decision emitted by `{driver_type}`."
3091    );
3092    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3093    pushln!(&mut out, "pub enum {decision_type} {{");
3094    pushln!(&mut out, "    DispatchInput(TypedRoutedInput),");
3095    pushln!(&mut out, "    DispatchSignal(TypedRoutedSignal),");
3096    pushln!(&mut out, "    NoRoute,");
3097    pushln!(&mut out, "}}");
3098    out.push('\n');
3099
3100    pushln!(
3101        &mut out,
3102        "/// Generated composition driver constrained by the catalog driver descriptor."
3103    );
3104    pushln!(&mut out, "#[derive(Debug, Clone, Copy, PartialEq, Eq)]");
3105    pushln!(&mut out, "pub struct {driver_type};");
3106    pushln!(&mut out);
3107    pushln!(&mut out, "impl {driver_type} {{");
3108    pushln!(
3109        &mut out,
3110        "    pub fn decide(work: &{work_type}) -> {decision_type} {{"
3111    );
3112    pushln!(
3113        &mut out,
3114        "        if let Some(route) = route_to_input(&work.producer_instance, &work.effect_variant) {{"
3115    );
3116    pushln!(
3117        &mut out,
3118        "            return {decision_type}::DispatchInput(route);"
3119    );
3120    pushln!(&mut out, "        }}");
3121    pushln!(
3122        &mut out,
3123        "        if let Some(route) = route_to_signal(&work.producer_instance, &work.effect_variant) {{"
3124    );
3125    pushln!(
3126        &mut out,
3127        "            return {decision_type}::DispatchSignal(route);"
3128    );
3129    pushln!(&mut out, "        }}");
3130    pushln!(&mut out, "        {decision_type}::NoRoute");
3131    pushln!(&mut out, "    }}");
3132    pushln!(&mut out);
3133    pushln!(
3134        &mut out,
3135        "    pub fn store_plan(decision: {decision_type}) -> Option<{store_plan_type}> {{"
3136    );
3137    pushln!(&mut out, "        match decision {{");
3138    pushln!(
3139        &mut out,
3140        "            {decision_type}::DispatchInput(route) => Some({store_plan_type}::input(route)),"
3141    );
3142    pushln!(
3143        &mut out,
3144        "            {decision_type}::DispatchSignal(route) => Some({store_plan_type}::signal(route)),"
3145    );
3146    pushln!(&mut out, "            {decision_type}::NoRoute => None,");
3147    pushln!(&mut out, "        }}");
3148    pushln!(&mut out, "    }}");
3149    pushln!(&mut out, "}}");
3150
3151    Some(out)
3152}
3153
3154fn to_snake_case_local(value: &str) -> String {
3155    let mut out = String::new();
3156    let mut previous_is_sep = true;
3157    for ch in value.chars() {
3158        if ch == '_' || ch == '-' || ch == ' ' {
3159            if !previous_is_sep {
3160                out.push('_');
3161                previous_is_sep = true;
3162            }
3163            continue;
3164        }
3165        if ch.is_ascii_uppercase() {
3166            if !out.is_empty() && !previous_is_sep {
3167                out.push('_');
3168            }
3169            out.push(ch.to_ascii_lowercase());
3170            previous_is_sep = false;
3171        } else {
3172            out.push(ch.to_ascii_lowercase());
3173            previous_is_sep = false;
3174        }
3175    }
3176    out.trim_matches('_').to_owned()
3177}
3178
3179pub fn render_machine_semantic_model(
3180    schema: &MachineSchema,
3181) -> std::result::Result<String, CompositionTlaError> {
3182    check_canonical_named_bindings(schema)?;
3183    if schema.tlc_model.is_some() {
3184        validate_machine_model(schema)?;
3185    }
3186    let mut compiler = MachineTlaCompiler::new(schema);
3187    compiler.render()
3188}
3189
3190fn render_state_markdown(out: &mut String, schema: &MachineSchema) {
3191    pushln!(out, "## State");
3192    writeln!(
3193        out,
3194        "- Phase enum: `{}`",
3195        schema
3196            .state
3197            .phase
3198            .variants
3199            .iter()
3200            .map(|variant| variant.name.as_str())
3201            .collect::<Vec<_>>()
3202            .join(" | ")
3203    )
3204    .expect("write to string");
3205    for field in &schema.state.fields {
3206        pushln!(out, "- `{}`: `{}`", field.name, render_type_ref(&field.ty));
3207    }
3208    pushln!(out);
3209}
3210
3211fn render_enum_markdown(out: &mut String, label: &str, schema: &EnumSchema) {
3212    writeln!(out, "## {label}");
3213    for variant in &schema.variants {
3214        if variant.fields.is_empty() {
3215            pushln!(out, "- `{}`", variant.name);
3216        } else {
3217            writeln!(
3218                out,
3219                "- `{}`({})",
3220                variant.name,
3221                render_field_list(&variant.fields)
3222            )
3223            .expect("write to string");
3224        }
3225    }
3226    pushln!(out);
3227}
3228
3229/// The input fields a machine's CI profile samples (`CiSamples`), in
3230/// declaration order, as one sentence of the generated contract; nothing for
3231/// a machine that declares none.
3232fn render_ci_samples_markdown(out: &mut String, schema: &MachineSchema) {
3233    let samples = schema
3234        .input_field_domains
3235        .iter()
3236        .filter_map(|declaration| match &declaration.domain {
3237            meerkat_machine_schema::InputFieldDomainKind::CiSamples(values) => Some(format!(
3238                "`{}`.`{}` as `{}`",
3239                declaration.input,
3240                declaration.field,
3241                render_explicit_values(values)
3242            )),
3243            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
3244            | meerkat_machine_schema::InputFieldDomainKind::StateField(_)
3245            | meerkat_machine_schema::InputFieldDomainKind::CiValues(_) => None,
3246        })
3247        .collect::<Vec<_>>();
3248    let Some((last, rest)) = samples.split_last() else {
3249        return;
3250    };
3251    let listed = if rest.is_empty() {
3252        last.clone()
3253    } else {
3254        format!("{} and {last}", rest.join(", "))
3255    };
3256    pushln!(out, "## CI Profile Samples");
3257    writeln!(
3258        out,
3259        "The CI profile samples {listed}; the Deep profile and every composition explore each field's whole domain."
3260    )
3261    .expect("write to string");
3262    pushln!(out);
3263}
3264
3265/// Render a labelled subset of an input enum's variants, keeping only those whose
3266/// name satisfies `keep`. Used to split the public command surface from the
3267/// runtime-internal inputs in the generated machine contract.
3268fn render_input_subset(
3269    out: &mut String,
3270    label: &str,
3271    schema: &EnumSchema,
3272    keep: impl Fn(&str) -> bool,
3273) {
3274    writeln!(out, "## {label}");
3275    for variant in schema
3276        .variants
3277        .iter()
3278        .filter(|variant| keep(variant.name.as_str()))
3279    {
3280        if variant.fields.is_empty() {
3281            pushln!(out, "- `{}`", variant.name);
3282        } else {
3283            writeln!(
3284                out,
3285                "- `{}`({})",
3286                variant.name,
3287                render_field_list(&variant.fields)
3288            )
3289            .expect("write to string");
3290        }
3291    }
3292    pushln!(out);
3293}
3294
3295fn render_field_list(fields: &[meerkat_machine_schema::FieldSchema]) -> String {
3296    fields
3297        .iter()
3298        .map(|field| format!("{}: {}", field.name, render_type_ref(&field.ty)))
3299        .collect::<Vec<_>>()
3300        .join(", ")
3301}
3302
3303fn collect_binding_domains(schema: &MachineSchema) -> BTreeMap<String, TypeRef> {
3304    let mut domains = BTreeMap::new();
3305
3306    for field in &schema.state.fields {
3307        collect_type_domains(&field.ty, &mut domains);
3308    }
3309
3310    for transition in &schema.transitions {
3311        if let Some(variant) = transition_trigger_variant(schema, transition) {
3312            for binding in transition.on.bindings() {
3313                if let Some(field) = variant.fields.iter().find(|field| field.name == *binding) {
3314                    collect_type_domains(&field.ty, &mut domains);
3315                }
3316            }
3317        }
3318    }
3319
3320    for variant in &schema.effects.variants {
3321        for field in &variant.fields {
3322            collect_type_domains(&field.ty, &mut domains);
3323        }
3324    }
3325
3326    domains
3327}
3328
3329fn collect_composition_binding_domains(
3330    schema: &CompositionSchema,
3331    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3332) -> BTreeMap<String, TypeRef> {
3333    let mut domains = BTreeMap::new();
3334
3335    for machine in machine_by_instance.values() {
3336        for (name, ty) in collect_binding_domains(machine) {
3337            domains.entry(name).or_insert(ty);
3338        }
3339    }
3340
3341    for entry_input in &schema.entry_inputs {
3342        let Some(machine) = machine_by_instance
3343            .get(entry_input.machine.as_str())
3344            .copied()
3345        else {
3346            continue;
3347        };
3348        let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
3349            continue;
3350        };
3351        for field in &variant.fields {
3352            collect_type_domains(&field.ty, &mut domains);
3353        }
3354    }
3355
3356    domains
3357}
3358
3359fn collect_type_domains(ty: &TypeRef, domains: &mut BTreeMap<String, TypeRef>) {
3360    let name = domain_constant_name(ty);
3361    domains.entry(name).or_insert_with(|| ty.clone());
3362    match ty {
3363        TypeRef::Option(inner) | TypeRef::Seq(inner) | TypeRef::Set(inner) => {
3364            collect_type_domains(inner, domains);
3365        }
3366        TypeRef::Map(key, value) => {
3367            collect_type_domains(key, domains);
3368            collect_type_domains(value, domains);
3369        }
3370        TypeRef::Bool
3371        | TypeRef::U32
3372        | TypeRef::U64
3373        | TypeRef::String
3374        | TypeRef::Named(_)
3375        | TypeRef::Enum(_) => {}
3376    }
3377}
3378
3379/// Named samples for a machine Deep profile: every named bucket unchanged, but
3380/// the generic `String` bucket holds only the string literals a transition
3381/// guard requires an input binding to equal (`delivery_id == "terminal"`,
3382/// `claim_id == ""`). Without them a transition guarded on such a literal is
3383/// unreachable under the generic `"alpha"`/`"beta"` samples and Deep coverage
3384/// reports it as zero-hit. Literals from updates, effects or init (messages,
3385/// error codes) are deliberately not added, so unrelated machines keep their
3386/// sample domains.
3387fn with_guard_binding_string_samples(
3388    named_samples: &BTreeMap<String, BTreeSet<String>>,
3389    schema: &MachineSchema,
3390) -> BTreeMap<String, BTreeSet<String>> {
3391    let mut samples = named_samples.clone();
3392    let literals = collect_guard_binding_string_literals(schema);
3393    if literals.is_empty() {
3394        samples.remove("String");
3395    } else {
3396        samples.insert("String".to_owned(), literals);
3397    }
3398    samples
3399}
3400
3401fn collect_guard_binding_string_literals(schema: &MachineSchema) -> BTreeSet<String> {
3402    let mut literals = BTreeSet::new();
3403    for transition in &schema.transitions {
3404        let string_bindings = transition_trigger_variant(schema, transition)
3405            .map(|variant| {
3406                variant
3407                    .fields
3408                    .iter()
3409                    .filter(|field| {
3410                        matches!(field.ty, TypeRef::String)
3411                            && transition
3412                                .on
3413                                .bindings()
3414                                .iter()
3415                                .any(|binding| binding == &field.name)
3416                    })
3417                    .map(|field| field.name.as_str().to_owned())
3418                    .collect::<BTreeSet<_>>()
3419            })
3420            .unwrap_or_default();
3421        if string_bindings.is_empty() {
3422            continue;
3423        }
3424        for guard in &transition.guards {
3425            collect_binding_literal_comparisons(&guard.expr, &string_bindings, &mut literals);
3426        }
3427    }
3428    literals
3429}
3430
3431fn collect_binding_literal_comparisons(
3432    expr: &Expr,
3433    string_bindings: &BTreeSet<String>,
3434    literals: &mut BTreeSet<String>,
3435) {
3436    match expr {
3437        // Only equality makes a guard unreachable without its literal. An
3438        // inequality such as `attempt_id != ""` is already satisfied by the
3439        // generic samples, so its literal would only add rejection-path states.
3440        Expr::Eq(left, right) => {
3441            match (left.as_ref(), right.as_ref()) {
3442                (Expr::Binding(binding), Expr::String(literal))
3443                | (Expr::String(literal), Expr::Binding(binding))
3444                    if string_bindings.contains(binding) =>
3445                {
3446                    literals.insert(literal.clone());
3447                }
3448                _ => {}
3449            }
3450            collect_binding_literal_comparisons(left, string_bindings, literals);
3451            collect_binding_literal_comparisons(right, string_bindings, literals);
3452        }
3453        Expr::Neq(left, right) => {
3454            collect_binding_literal_comparisons(left, string_bindings, literals);
3455            collect_binding_literal_comparisons(right, string_bindings, literals);
3456        }
3457        Expr::Not(inner) => collect_binding_literal_comparisons(inner, string_bindings, literals),
3458        Expr::And(items) | Expr::Or(items) => {
3459            for item in items {
3460                collect_binding_literal_comparisons(item, string_bindings, literals);
3461            }
3462        }
3463        Expr::IfElse {
3464            condition,
3465            then_expr,
3466            else_expr,
3467        } => {
3468            for item in [condition, then_expr, else_expr] {
3469                collect_binding_literal_comparisons(item, string_bindings, literals);
3470            }
3471        }
3472        _ => {}
3473    }
3474}
3475
3476fn collect_machine_named_type_samples(
3477    schema: &MachineSchema,
3478) -> BTreeMap<String, BTreeSet<String>> {
3479    let field_types = schema
3480        .state
3481        .fields
3482        .iter()
3483        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3484        .collect::<BTreeMap<String, _>>();
3485    let helper_returns = schema
3486        .helpers
3487        .iter()
3488        .chain(schema.derived.iter())
3489        .map(|helper| (helper.name.clone(), helper.returns.clone()))
3490        .collect::<BTreeMap<String, _>>();
3491    let mut samples = BTreeMap::new();
3492
3493    for init in &schema.state.init.fields {
3494        if let Some(field_ty) = field_types.get(init.field.as_str()) {
3495            collect_named_literals_from_expr(
3496                &mut samples,
3497                &init.expr,
3498                Some(field_ty),
3499                &field_types,
3500                &helper_returns,
3501                &BTreeMap::new(),
3502            );
3503        }
3504    }
3505
3506    for helper in schema.helpers.iter().chain(schema.derived.iter()) {
3507        let bindings = helper
3508            .params
3509            .iter()
3510            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3511            .collect::<BTreeMap<String, _>>();
3512        collect_named_literals_from_expr(
3513            &mut samples,
3514            &helper.body,
3515            Some(&helper.returns),
3516            &field_types,
3517            &helper_returns,
3518            &bindings,
3519        );
3520    }
3521
3522    for invariant in &schema.invariants {
3523        collect_named_literals_from_expr(
3524            &mut samples,
3525            &invariant.expr,
3526            None,
3527            &field_types,
3528            &helper_returns,
3529            &BTreeMap::new(),
3530        );
3531    }
3532
3533    for transition in &schema.transitions {
3534        let binding_types = transition_trigger_variant(schema, transition)
3535            .map(|variant| {
3536                variant
3537                    .fields
3538                    .iter()
3539                    .filter(|field| {
3540                        transition
3541                            .on
3542                            .bindings()
3543                            .iter()
3544                            .any(|binding| binding == &field.name)
3545                    })
3546                    .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3547                    .collect::<BTreeMap<_, _>>()
3548            })
3549            .unwrap_or_default();
3550
3551        for guard in &transition.guards {
3552            collect_named_literals_from_expr(
3553                &mut samples,
3554                &guard.expr,
3555                None,
3556                &field_types,
3557                &helper_returns,
3558                &binding_types,
3559            );
3560        }
3561        for update in &transition.updates {
3562            collect_named_literals_from_update(
3563                &mut samples,
3564                update,
3565                &field_types,
3566                &helper_returns,
3567                &binding_types,
3568            );
3569        }
3570        for effect in &transition.emit {
3571            let Ok(effect_variant) = schema.effects.variant_named(effect.variant.as_str()) else {
3572                continue;
3573            };
3574            for field in &effect_variant.fields {
3575                if let Some(expr) = effect.fields.get(&field.name) {
3576                    collect_named_literals_from_expr(
3577                        &mut samples,
3578                        expr,
3579                        Some(&field.ty),
3580                        &field_types,
3581                        &helper_returns,
3582                        &binding_types,
3583                    );
3584                }
3585            }
3586        }
3587    }
3588
3589    samples
3590}
3591
3592fn collect_composition_named_type_samples(
3593    schema: &CompositionSchema,
3594    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3595) -> BTreeMap<String, BTreeSet<String>> {
3596    let mut samples = BTreeMap::new();
3597    for machine in machine_by_instance.values() {
3598        merge_named_type_samples(&mut samples, collect_machine_named_type_samples(machine));
3599    }
3600
3601    for entry_input in &schema.entry_inputs {
3602        let Some(machine) = machine_by_instance
3603            .get(entry_input.machine.as_str())
3604            .copied()
3605        else {
3606            continue;
3607        };
3608        merge_named_type_samples(&mut samples, collect_machine_named_type_samples(machine));
3609    }
3610
3611    for route in &schema.routes {
3612        let Some(source_machine) = machine_by_instance
3613            .get(route.from_machine.as_str())
3614            .copied()
3615        else {
3616            continue;
3617        };
3618        let Ok(source_variant) = source_machine.effects.variant_named(&route.effect_variant) else {
3619            continue;
3620        };
3621        let source_field_types = source_variant
3622            .fields
3623            .iter()
3624            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3625            .collect::<BTreeMap<String, _>>();
3626        let Some(target_machine) = machine_by_instance.get(route.to.machine.as_str()).copied()
3627        else {
3628            continue;
3629        };
3630        let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
3631            continue;
3632        };
3633        let field_types = target_variant
3634            .fields
3635            .iter()
3636            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3637            .collect::<BTreeMap<String, _>>();
3638
3639        for binding in &route.bindings {
3640            if let RouteBindingSource::Literal(expr) = &binding.source
3641                && let Some(field_ty) = field_types.get(binding.to_field.as_str())
3642            {
3643                collect_named_literals_from_expr(
3644                    &mut samples,
3645                    expr,
3646                    Some(field_ty),
3647                    &field_types,
3648                    &BTreeMap::new(),
3649                    &BTreeMap::new(),
3650                );
3651            }
3652            if let RouteBindingSource::Field { from_field, .. } = &binding.source
3653                && let (Some(source_ty), Some(target_ty)) = (
3654                    source_field_types.get(from_field.as_str()),
3655                    field_types.get(binding.to_field.as_str()),
3656                )
3657            {
3658                propagate_named_samples_between_types(&mut samples, source_ty, target_ty);
3659            }
3660        }
3661    }
3662
3663    for witness in &schema.witnesses {
3664        for preload in &witness.preload_inputs {
3665            let Some(machine) = machine_by_instance.get(preload.machine.as_str()).copied() else {
3666                continue;
3667            };
3668            let Ok(variant) = machine
3669                .inputs
3670                .variant_named(&preload.input_variant)
3671                .or_else(|_| machine.signals.variant_named(&preload.input_variant))
3672            else {
3673                continue;
3674            };
3675            let field_types = variant
3676                .fields
3677                .iter()
3678                .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3679                .collect::<BTreeMap<String, _>>();
3680
3681            for field in &preload.fields {
3682                if let Some(field_ty) = field_types.get(field.field.as_str()) {
3683                    collect_named_literals_from_expr(
3684                        &mut samples,
3685                        &field.expr,
3686                        Some(field_ty),
3687                        &field_types,
3688                        &BTreeMap::new(),
3689                        &BTreeMap::new(),
3690                    );
3691                }
3692            }
3693        }
3694    }
3695
3696    samples
3697}
3698
3699fn collect_composition_witness_named_type_samples(
3700    schema: &CompositionSchema,
3701    witness: &CompositionWitness,
3702    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3703) -> BTreeMap<String, BTreeSet<String>> {
3704    let mut samples = BTreeMap::new();
3705
3706    for preload in &witness.preload_inputs {
3707        let Some(machine) = machine_by_instance.get(preload.machine.as_str()).copied() else {
3708            continue;
3709        };
3710        let Ok(variant) = machine
3711            .inputs
3712            .variant_named(&preload.input_variant)
3713            .or_else(|_| machine.signals.variant_named(&preload.input_variant))
3714        else {
3715            continue;
3716        };
3717        let field_types = variant
3718            .fields
3719            .iter()
3720            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3721            .collect::<BTreeMap<String, _>>();
3722
3723        for field in &preload.fields {
3724            if let Some(field_ty) = field_types.get(field.field.as_str()) {
3725                collect_named_literals_from_expr(
3726                    &mut samples,
3727                    &field.expr,
3728                    Some(field_ty),
3729                    &field_types,
3730                    &BTreeMap::new(),
3731                    &BTreeMap::new(),
3732                );
3733            }
3734        }
3735    }
3736
3737    let witness_routes = schema
3738        .routes
3739        .iter()
3740        .filter(|route| {
3741            witness
3742                .expected_routes
3743                .iter()
3744                .any(|name| name == &route.name)
3745        })
3746        .collect::<Vec<_>>();
3747    collect_route_binding_named_type_samples_to_fixpoint(
3748        &mut samples,
3749        &witness_routes,
3750        machine_by_instance,
3751    );
3752
3753    samples
3754}
3755
3756fn merge_named_type_samples(
3757    target: &mut BTreeMap<String, BTreeSet<String>>,
3758    source: BTreeMap<String, BTreeSet<String>>,
3759) {
3760    for (name, values) in source {
3761        target.entry(name).or_default().extend(values);
3762    }
3763}
3764
3765fn collect_route_binding_named_type_samples_to_fixpoint(
3766    samples: &mut BTreeMap<String, BTreeSet<String>>,
3767    routes: &[&Route],
3768    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3769) {
3770    loop {
3771        let mut changed = false;
3772        for route in routes {
3773            changed |=
3774                collect_route_binding_named_type_samples(samples, route, machine_by_instance);
3775        }
3776        if !changed {
3777            break;
3778        }
3779    }
3780}
3781
3782fn collect_route_binding_named_type_samples(
3783    samples: &mut BTreeMap<String, BTreeSet<String>>,
3784    route: &Route,
3785    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3786) -> bool {
3787    let Some(source_machine) = machine_by_instance
3788        .get(route.from_machine.as_str())
3789        .copied()
3790    else {
3791        return false;
3792    };
3793    let Ok(source_variant) = source_machine.effects.variant_named(&route.effect_variant) else {
3794        return false;
3795    };
3796    let source_field_types = source_variant
3797        .fields
3798        .iter()
3799        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3800        .collect::<BTreeMap<String, _>>();
3801    let Some(target_machine) = machine_by_instance.get(route.to.machine.as_str()).copied() else {
3802        return false;
3803    };
3804    let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
3805        return false;
3806    };
3807    let target_field_types = target_variant
3808        .fields
3809        .iter()
3810        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3811        .collect::<BTreeMap<String, _>>();
3812
3813    let mut changed = false;
3814    for binding in &route.bindings {
3815        if let RouteBindingSource::Literal(expr) = &binding.source
3816            && let Some(field_ty) = target_field_types.get(binding.to_field.as_str())
3817        {
3818            let before = samples.clone();
3819            collect_named_literals_from_expr(
3820                samples,
3821                expr,
3822                Some(field_ty),
3823                &target_field_types,
3824                &BTreeMap::new(),
3825                &BTreeMap::new(),
3826            );
3827            changed |= *samples != before;
3828        }
3829        if let RouteBindingSource::Field { from_field, .. } = &binding.source
3830            && let (Some(source_ty), Some(target_ty)) = (
3831                source_field_types.get(from_field.as_str()),
3832                target_field_types.get(binding.to_field.as_str()),
3833            )
3834        {
3835            changed |= propagate_named_samples_between_types(samples, source_ty, target_ty);
3836        }
3837    }
3838
3839    changed
3840}
3841
3842fn propagate_named_samples_between_types(
3843    samples: &mut BTreeMap<String, BTreeSet<String>>,
3844    source_ty: &TypeRef,
3845    target_ty: &TypeRef,
3846) -> bool {
3847    match (source_ty, target_ty) {
3848        (TypeRef::Option(source_inner), TypeRef::Option(target_inner))
3849        | (TypeRef::Seq(source_inner), TypeRef::Seq(target_inner))
3850        | (TypeRef::Set(source_inner), TypeRef::Set(target_inner)) => {
3851            propagate_named_samples_between_types(samples, source_inner, target_inner)
3852        }
3853        _ => {
3854            let (Some(source_bucket), Some(target_bucket)) =
3855                (type_sample_bucket(source_ty), type_sample_bucket(target_ty))
3856            else {
3857                return false;
3858            };
3859            if let Some(source_samples) = samples.get(&source_bucket).cloned() {
3860                let target_samples = samples.entry(target_bucket).or_default();
3861                let before = target_samples.len();
3862                target_samples.extend(source_samples);
3863                target_samples.len() != before
3864            } else {
3865                false
3866            }
3867        }
3868    }
3869}
3870
3871fn collect_named_literals_from_update(
3872    samples: &mut BTreeMap<String, BTreeSet<String>>,
3873    update: &Update,
3874    field_types: &BTreeMap<String, TypeRef>,
3875    helper_returns: &BTreeMap<String, TypeRef>,
3876    binding_types: &BTreeMap<String, TypeRef>,
3877) {
3878    match update {
3879        Update::Assign { field, expr } => {
3880            collect_named_literals_from_expr(
3881                samples,
3882                expr,
3883                field_types.get(field.as_str()),
3884                field_types,
3885                helper_returns,
3886                binding_types,
3887            );
3888        }
3889        Update::MapInsert { field, key, value } => {
3890            if let Some(TypeRef::Map(key_ty, value_ty)) = field_types.get(field.as_str()) {
3891                collect_named_literals_from_expr(
3892                    samples,
3893                    key,
3894                    Some(key_ty),
3895                    field_types,
3896                    helper_returns,
3897                    binding_types,
3898                );
3899                collect_named_literals_from_expr(
3900                    samples,
3901                    value,
3902                    Some(value_ty),
3903                    field_types,
3904                    helper_returns,
3905                    binding_types,
3906                );
3907            }
3908        }
3909        Update::MapRemove { field, key } => {
3910            if let Some(TypeRef::Map(key_ty, _)) = field_types.get(field.as_str()) {
3911                collect_named_literals_from_expr(
3912                    samples,
3913                    key,
3914                    Some(key_ty),
3915                    field_types,
3916                    helper_returns,
3917                    binding_types,
3918                );
3919            }
3920        }
3921        Update::MapIncrement { field, key, .. } | Update::MapDecrement { field, key, .. } => {
3922            if let Some(TypeRef::Map(key_ty, _)) = field_types.get(field.as_str()) {
3923                collect_named_literals_from_expr(
3924                    samples,
3925                    key,
3926                    Some(key_ty),
3927                    field_types,
3928                    helper_returns,
3929                    binding_types,
3930                );
3931            }
3932        }
3933        Update::SetInsert { field, value } | Update::SetRemove { field, value } => {
3934            if let Some(TypeRef::Set(inner_ty)) = field_types.get(field.as_str()) {
3935                collect_named_literals_from_expr(
3936                    samples,
3937                    value,
3938                    Some(inner_ty),
3939                    field_types,
3940                    helper_returns,
3941                    binding_types,
3942                );
3943            }
3944        }
3945        Update::SeqAppend { field, value } | Update::SeqRemoveValue { field, value } => {
3946            if let Some(TypeRef::Seq(inner_ty)) = field_types.get(field.as_str()) {
3947                collect_named_literals_from_expr(
3948                    samples,
3949                    value,
3950                    Some(inner_ty),
3951                    field_types,
3952                    helper_returns,
3953                    binding_types,
3954                );
3955            }
3956        }
3957        Update::SeqPrepend { field, values } | Update::SeqRemoveAll { field, values } => {
3958            if let Some(field_ty) = field_types.get(field.as_str()) {
3959                collect_named_literals_from_expr(
3960                    samples,
3961                    values,
3962                    Some(field_ty),
3963                    field_types,
3964                    helper_returns,
3965                    binding_types,
3966                );
3967            }
3968        }
3969        Update::Conditional {
3970            condition,
3971            then_updates,
3972            else_updates,
3973        } => {
3974            collect_named_literals_from_expr(
3975                samples,
3976                condition,
3977                None,
3978                field_types,
3979                helper_returns,
3980                binding_types,
3981            );
3982            for nested in then_updates {
3983                collect_named_literals_from_update(
3984                    samples,
3985                    nested,
3986                    field_types,
3987                    helper_returns,
3988                    binding_types,
3989                );
3990            }
3991            for nested in else_updates {
3992                collect_named_literals_from_update(
3993                    samples,
3994                    nested,
3995                    field_types,
3996                    helper_returns,
3997                    binding_types,
3998                );
3999            }
4000        }
4001        Update::ForEach {
4002            binding,
4003            over,
4004            updates,
4005        } => {
4006            collect_named_literals_from_expr(
4007                samples,
4008                over,
4009                None,
4010                field_types,
4011                helper_returns,
4012                binding_types,
4013            );
4014            let mut nested_bindings = binding_types.clone();
4015            if let Some(over_ty) = infer_expr_type(over, field_types, helper_returns, binding_types)
4016            {
4017                match over_ty {
4018                    TypeRef::Seq(inner_ty) | TypeRef::Set(inner_ty) => {
4019                        nested_bindings.insert(binding.clone(), (*inner_ty).clone());
4020                    }
4021                    TypeRef::Map(key_ty, _) => {
4022                        nested_bindings.insert(binding.clone(), (*key_ty).clone());
4023                    }
4024                    _ => {}
4025                }
4026            }
4027            for nested in updates {
4028                collect_named_literals_from_update(
4029                    samples,
4030                    nested,
4031                    field_types,
4032                    helper_returns,
4033                    &nested_bindings,
4034                );
4035            }
4036        }
4037        Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
4038    }
4039}
4040
4041fn collect_named_literals_from_expr(
4042    samples: &mut BTreeMap<String, BTreeSet<String>>,
4043    expr: &Expr,
4044    expected_ty: Option<&TypeRef>,
4045    field_types: &BTreeMap<String, TypeRef>,
4046    helper_returns: &BTreeMap<String, TypeRef>,
4047    binding_types: &BTreeMap<String, TypeRef>,
4048) {
4049    if let Expr::String(value) = expr
4050        && let Some(bucket) = expected_ty.and_then(type_sample_bucket)
4051    {
4052        samples.entry(bucket).or_default().insert(value.clone());
4053    }
4054
4055    if let (Expr::NamedVariant { variant, .. }, Some(expected_ty)) = (expr, expected_ty)
4056        && let Some(bucket) = type_sample_bucket(expected_ty)
4057    {
4058        samples
4059            .entry(bucket)
4060            .or_default()
4061            .insert(variant.as_str().to_owned());
4062    }
4063
4064    match expr {
4065        Expr::Eq(left, right) | Expr::Neq(left, right) => {
4066            let left_ty = infer_expr_type(left, field_types, helper_returns, binding_types);
4067            let right_ty = infer_expr_type(right, field_types, helper_returns, binding_types);
4068            if let (Some(left_ty), Expr::String(value)) = (&left_ty, right.as_ref())
4069                && let Some(bucket) = type_sample_bucket(left_ty)
4070            {
4071                samples.entry(bucket).or_default().insert(value.clone());
4072            }
4073            if let (Some(right_ty), Expr::String(value)) = (&right_ty, left.as_ref())
4074                && let Some(bucket) = type_sample_bucket(right_ty)
4075            {
4076                samples.entry(bucket).or_default().insert(value.clone());
4077            }
4078            if let (Some(left_ty), Expr::NamedVariant { variant, .. }) = (&left_ty, right.as_ref())
4079                && let Some(bucket) = type_sample_bucket(left_ty)
4080            {
4081                samples
4082                    .entry(bucket)
4083                    .or_default()
4084                    .insert(variant.as_str().to_owned());
4085            }
4086            if let (Some(right_ty), Expr::NamedVariant { variant, .. }) = (&right_ty, left.as_ref())
4087                && let Some(bucket) = type_sample_bucket(right_ty)
4088            {
4089                samples
4090                    .entry(bucket)
4091                    .or_default()
4092                    .insert(variant.as_str().to_owned());
4093            }
4094            collect_named_literals_from_expr(
4095                samples,
4096                left,
4097                left_ty.as_ref(),
4098                field_types,
4099                helper_returns,
4100                binding_types,
4101            );
4102            collect_named_literals_from_expr(
4103                samples,
4104                right,
4105                right_ty.as_ref(),
4106                field_types,
4107                helper_returns,
4108                binding_types,
4109            );
4110        }
4111        Expr::IfElse {
4112            condition,
4113            then_expr,
4114            else_expr,
4115        } => {
4116            collect_named_literals_from_expr(
4117                samples,
4118                condition,
4119                Some(&TypeRef::Bool),
4120                field_types,
4121                helper_returns,
4122                binding_types,
4123            );
4124            collect_named_literals_from_expr(
4125                samples,
4126                then_expr,
4127                expected_ty,
4128                field_types,
4129                helper_returns,
4130                binding_types,
4131            );
4132            collect_named_literals_from_expr(
4133                samples,
4134                else_expr,
4135                expected_ty,
4136                field_types,
4137                helper_returns,
4138                binding_types,
4139            );
4140        }
4141        Expr::Not(inner)
4142        | Expr::SeqElements(inner)
4143        | Expr::Len(inner)
4144        | Expr::Head(inner)
4145        | Expr::MapKeys(inner)
4146        | Expr::Some(inner)
4147        | Expr::FieldAccess { base: inner, .. }
4148        | Expr::EnumVariantIs { value: inner, .. }
4149        | Expr::EnumStringSetPayload { value: inner, .. } => {
4150            let nested_ty = infer_expr_type(inner, field_types, helper_returns, binding_types);
4151            collect_named_literals_from_expr(
4152                samples,
4153                inner,
4154                nested_ty.as_ref(),
4155                field_types,
4156                helper_returns,
4157                binding_types,
4158            );
4159        }
4160        Expr::And(items) | Expr::Or(items) => {
4161            for item in items {
4162                collect_named_literals_from_expr(
4163                    samples,
4164                    item,
4165                    None,
4166                    field_types,
4167                    helper_returns,
4168                    binding_types,
4169                );
4170            }
4171        }
4172        Expr::SeqLiteral(items) => {
4173            let item_expected_ty = match expected_ty {
4174                Some(TypeRef::Seq(inner)) => Some(inner.as_ref()),
4175                _ => None,
4176            };
4177            for item in items {
4178                collect_named_literals_from_expr(
4179                    samples,
4180                    item,
4181                    item_expected_ty,
4182                    field_types,
4183                    helper_returns,
4184                    binding_types,
4185                );
4186            }
4187        }
4188        Expr::Add(left, right)
4189        | Expr::Sub(left, right)
4190        | Expr::Gt(left, right)
4191        | Expr::Gte(left, right)
4192        | Expr::Lt(left, right)
4193        | Expr::Lte(left, right) => {
4194            collect_named_literals_from_expr(
4195                samples,
4196                left,
4197                infer_expr_type(left, field_types, helper_returns, binding_types).as_ref(),
4198                field_types,
4199                helper_returns,
4200                binding_types,
4201            );
4202            collect_named_literals_from_expr(
4203                samples,
4204                right,
4205                infer_expr_type(right, field_types, helper_returns, binding_types).as_ref(),
4206                field_types,
4207                helper_returns,
4208                binding_types,
4209            );
4210        }
4211        Expr::Contains { collection, value } => {
4212            let collection_ty =
4213                infer_expr_type(collection, field_types, helper_returns, binding_types);
4214            let value_ty = match collection_ty {
4215                Some(TypeRef::Set(inner_ty) | TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4216                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4217                _ => None,
4218            };
4219            collect_named_literals_from_expr(
4220                samples,
4221                collection,
4222                None,
4223                field_types,
4224                helper_returns,
4225                binding_types,
4226            );
4227            collect_named_literals_from_expr(
4228                samples,
4229                value,
4230                value_ty.as_ref(),
4231                field_types,
4232                helper_returns,
4233                binding_types,
4234            );
4235        }
4236        Expr::Count { collection, value } => {
4237            let collection_ty =
4238                infer_expr_type(collection, field_types, helper_returns, binding_types);
4239            let value_ty = match collection_ty {
4240                Some(TypeRef::Set(inner_ty) | TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4241                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4242                _ => None,
4243            };
4244            collect_named_literals_from_expr(
4245                samples,
4246                collection,
4247                None,
4248                field_types,
4249                helper_returns,
4250                binding_types,
4251            );
4252            collect_named_literals_from_expr(
4253                samples,
4254                value,
4255                value_ty.as_ref(),
4256                field_types,
4257                helper_returns,
4258                binding_types,
4259            );
4260        }
4261        Expr::MapContainsKey { map, key } => {
4262            let map_ty = infer_expr_type(map, field_types, helper_returns, binding_types);
4263            let key_ty = match map_ty {
4264                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4265                _ => None,
4266            };
4267            collect_named_literals_from_expr(
4268                samples,
4269                map,
4270                None,
4271                field_types,
4272                helper_returns,
4273                binding_types,
4274            );
4275            collect_named_literals_from_expr(
4276                samples,
4277                key,
4278                key_ty.as_ref(),
4279                field_types,
4280                helper_returns,
4281                binding_types,
4282            );
4283        }
4284        Expr::SeqStartsWith { seq, prefix } => {
4285            let seq_ty = infer_expr_type(seq, field_types, helper_returns, binding_types);
4286            collect_named_literals_from_expr(
4287                samples,
4288                seq,
4289                seq_ty.as_ref(),
4290                field_types,
4291                helper_returns,
4292                binding_types,
4293            );
4294            collect_named_literals_from_expr(
4295                samples,
4296                prefix,
4297                seq_ty.as_ref(),
4298                field_types,
4299                helper_returns,
4300                binding_types,
4301            );
4302        }
4303        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
4304            let map_ty = infer_expr_type(map, field_types, helper_returns, binding_types);
4305            let key_ty = match map_ty {
4306                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4307                _ => None,
4308            };
4309            collect_named_literals_from_expr(
4310                samples,
4311                map,
4312                None,
4313                field_types,
4314                helper_returns,
4315                binding_types,
4316            );
4317            collect_named_literals_from_expr(
4318                samples,
4319                key,
4320                key_ty.as_ref(),
4321                field_types,
4322                helper_returns,
4323                binding_types,
4324            );
4325        }
4326        Expr::MapLiteral(entries) => {
4327            let (key_ty, value_ty) = match expected_ty {
4328                Some(TypeRef::Map(key_ty, value_ty)) => {
4329                    (Some(key_ty.as_ref()), Some(value_ty.as_ref()))
4330                }
4331                _ => (None, None),
4332            };
4333            for (key, value) in entries {
4334                collect_named_literals_from_expr(
4335                    samples,
4336                    key,
4337                    key_ty,
4338                    field_types,
4339                    helper_returns,
4340                    binding_types,
4341                );
4342                collect_named_literals_from_expr(
4343                    samples,
4344                    value,
4345                    value_ty,
4346                    field_types,
4347                    helper_returns,
4348                    binding_types,
4349                );
4350            }
4351        }
4352        Expr::Call { helper: _, args } => {
4353            for arg in args {
4354                collect_named_literals_from_expr(
4355                    samples,
4356                    arg,
4357                    infer_expr_type(arg, field_types, helper_returns, binding_types).as_ref(),
4358                    field_types,
4359                    helper_returns,
4360                    binding_types,
4361                );
4362            }
4363        }
4364        Expr::Quantified {
4365            binding,
4366            over,
4367            body,
4368            ..
4369        } => {
4370            collect_named_literals_from_expr(
4371                samples,
4372                over,
4373                None,
4374                field_types,
4375                helper_returns,
4376                binding_types,
4377            );
4378            // Thread the quantifier binding's element type into the body so
4379            // literals compared against the binding land in the element's
4380            // named sample domain (e.g. `exists(name in <Set<ToolName>>,
4381            // name == "view_image")` buckets the literal under `ToolName`).
4382            let element_ty = infer_expr_type(over, field_types, helper_returns, binding_types)
4383                .and_then(|ty| match ty {
4384                    TypeRef::Set(inner) | TypeRef::Seq(inner) => Some(*inner),
4385                    _ => None,
4386                });
4387            let mut body_binding_types = binding_types.clone();
4388            if let Some(element_ty) = element_ty {
4389                body_binding_types.insert(binding.clone(), element_ty);
4390            }
4391            collect_named_literals_from_expr(
4392                samples,
4393                body,
4394                Some(&TypeRef::Bool),
4395                field_types,
4396                helper_returns,
4397                &body_binding_types,
4398            );
4399        }
4400        Expr::Bool(_)
4401        | Expr::U64(_)
4402        | Expr::U64Max
4403        | Expr::String(_)
4404        | Expr::NamedVariant { .. }
4405        | Expr::EmptySet
4406        | Expr::EmptyMap
4407        | Expr::CurrentPhase
4408        | Expr::Phase(_)
4409        | Expr::Field(_)
4410        | Expr::Binding(_)
4411        | Expr::Variant(_)
4412        | Expr::None => {}
4413    }
4414}
4415
4416fn infer_expr_type(
4417    expr: &Expr,
4418    field_types: &BTreeMap<String, TypeRef>,
4419    helper_returns: &BTreeMap<String, TypeRef>,
4420    binding_types: &BTreeMap<String, TypeRef>,
4421) -> Option<TypeRef> {
4422    match expr {
4423        Expr::Bool(_) => Some(TypeRef::Bool),
4424        Expr::U64(_) | Expr::U64Max => Some(TypeRef::U64),
4425        Expr::String(_) | Expr::CurrentPhase | Expr::Phase(_) | Expr::Variant(_) => {
4426            Some(TypeRef::String)
4427        }
4428        Expr::NamedVariant { enum_name, .. } => Some(TypeRef::Enum(enum_name.clone())),
4429        Expr::FieldAccess { .. } => None,
4430        Expr::EnumVariantIs { .. } => Some(TypeRef::Bool),
4431        Expr::EnumStringSetPayload { .. } => Some(TypeRef::Set(Box::new(TypeRef::String))),
4432        Expr::Field(name) => field_types.get(name.as_str()).cloned(),
4433        Expr::Binding(name) => binding_types.get(name).cloned(),
4434        Expr::None => None,
4435        Expr::IfElse {
4436            then_expr,
4437            else_expr,
4438            ..
4439        } => {
4440            let then_ty = infer_expr_type(then_expr, field_types, helper_returns, binding_types);
4441            let else_ty = infer_expr_type(else_expr, field_types, helper_returns, binding_types);
4442            if then_ty == else_ty {
4443                then_ty
4444            } else {
4445                then_ty.or(else_ty)
4446            }
4447        }
4448        Expr::Not(_)
4449        | Expr::And(_)
4450        | Expr::Or(_)
4451        | Expr::Eq(_, _)
4452        | Expr::Neq(_, _)
4453        | Expr::Gt(_, _)
4454        | Expr::Gte(_, _)
4455        | Expr::Lt(_, _)
4456        | Expr::Lte(_, _)
4457        | Expr::Contains { .. }
4458        | Expr::MapContainsKey { .. }
4459        | Expr::SeqStartsWith { .. }
4460        | Expr::Quantified { .. } => Some(TypeRef::Bool),
4461        Expr::Add(_, _) | Expr::Sub(_, _) | Expr::Len(_) | Expr::Count { .. } => Some(TypeRef::U64),
4462        Expr::SeqElements(inner) => {
4463            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4464                Some(TypeRef::Seq(inner_ty)) => Some(TypeRef::Set(inner_ty)),
4465                _ => None,
4466            }
4467        }
4468        Expr::Head(inner) => {
4469            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4470                Some(TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4471                _ => None,
4472            }
4473        }
4474        Expr::MapKeys(inner) => {
4475            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4476                Some(TypeRef::Map(key_ty, _)) => Some(TypeRef::Set(key_ty)),
4477                _ => None,
4478            }
4479        }
4480        Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
4481            match infer_expr_type(map, field_types, helper_returns, binding_types) {
4482                Some(TypeRef::Map(_, value_ty)) => Some(*value_ty),
4483                _ => None,
4484            }
4485        }
4486        Expr::MapLiteral(entries) => entries.first().and_then(|(key, value)| {
4487            let key_ty = infer_expr_type(key, field_types, helper_returns, binding_types)?;
4488            let value_ty = infer_expr_type(value, field_types, helper_returns, binding_types)?;
4489            Some(TypeRef::Map(Box::new(key_ty), Box::new(value_ty)))
4490        }),
4491        Expr::Some(inner) => infer_expr_type(inner, field_types, helper_returns, binding_types)
4492            .map(|inner_ty| TypeRef::Option(Box::new(inner_ty))),
4493        Expr::Call { helper, .. } if helper == "mob_machine_step_status_from_frame_node_status" => {
4494            meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4495                .ok()
4496                .map(TypeRef::Enum)
4497        }
4498        Expr::Call { helper, args } if helper == "session_document_instruction_slot_after_set" => {
4499            args.first().and_then(|current| {
4500                infer_expr_type(current, field_types, helper_returns, binding_types)
4501            })
4502        }
4503        Expr::Call { helper, .. } if helper == "session_document_instruction_active_bytes" => {
4504            Some(TypeRef::U64)
4505        }
4506        // The widest member snapshot of a mob's operator instruction
4507        // records, and the widest a write changes with the write applied,
4508        // in records and in Active body bytes.
4509        Expr::Call { helper, .. }
4510            if helper == "mob_machine_instruction_widest_snapshot_slots"
4511                || helper == "mob_machine_instruction_widest_snapshot_active_bytes"
4512                || helper == "mob_machine_instruction_write_snapshot_slots"
4513                || helper == "mob_machine_instruction_write_snapshot_active_bytes" =>
4514        {
4515            Some(TypeRef::U64)
4516        }
4517        // The Active entries of a slot map: the type of the map it filters.
4518        Expr::Call { helper, args } if helper == "session_document_instruction_active_slots" => {
4519            args.get(1).and_then(|values| {
4520                infer_expr_type(values, field_types, helper_returns, binding_types)
4521            })
4522        }
4523        // The retired count per activation key: the type of the row counts.
4524        Expr::Call { helper, args } if helper == "session_document_activation_retired_after" => {
4525            args.first()
4526                .and_then(|rows| infer_expr_type(rows, field_types, helper_returns, binding_types))
4527        }
4528        Expr::Call { helper, .. } if helper == "runtime_delivery_recipient_outcomes_after_set" => {
4529            Some(TypeRef::Map(
4530                Box::new(TypeRef::String),
4531                Box::new(TypeRef::Enum(
4532                    meerkat_machine_schema::identity::EnumTypeId::parse("DeliveryRecipientOutcome")
4533                        .ok()?,
4534                )),
4535            ))
4536        }
4537        Expr::Call { helper, .. } if helper == "mob_machine_run_step_status_after_set" => {
4538            Some(TypeRef::Map(
4539                Box::new(TypeRef::Named(
4540                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4541                )),
4542                Box::new(TypeRef::Map(
4543                    Box::new(TypeRef::Named(
4544                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4545                    )),
4546                    Box::new(TypeRef::Option(Box::new(TypeRef::Enum(
4547                        meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4548                            .ok()?,
4549                    )))),
4550                )),
4551            ))
4552        }
4553        Expr::Call { helper, .. }
4554            if helper == "mob_machine_run_step_status_after_cancel_unfinished" =>
4555        {
4556            Some(TypeRef::Map(
4557                Box::new(TypeRef::Named(
4558                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4559                )),
4560                Box::new(TypeRef::Map(
4561                    Box::new(TypeRef::Named(
4562                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4563                    )),
4564                    Box::new(TypeRef::Option(Box::new(TypeRef::Enum(
4565                        meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4566                            .ok()?,
4567                    )))),
4568                )),
4569            ))
4570        }
4571        Expr::Call { helper, .. } if helper == "mob_machine_run_step_bool_after_set" => {
4572            Some(TypeRef::Map(
4573                Box::new(TypeRef::Named(
4574                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4575                )),
4576                Box::new(TypeRef::Map(
4577                    Box::new(TypeRef::Named(
4578                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4579                    )),
4580                    Box::new(TypeRef::Bool),
4581                )),
4582            ))
4583        }
4584        Expr::Call { helper, .. }
4585            if helper == "mob_machine_run_step_condition_result_after_set" =>
4586        {
4587            Some(TypeRef::Map(
4588                Box::new(TypeRef::Named(
4589                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4590                )),
4591                Box::new(TypeRef::Map(
4592                    Box::new(TypeRef::Named(
4593                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4594                    )),
4595                    Box::new(TypeRef::Option(Box::new(TypeRef::Bool))),
4596                )),
4597            ))
4598        }
4599        Expr::Call { helper, .. }
4600            if helper == "mob_machine_run_step_u64_after_set"
4601                || helper == "mob_machine_run_step_u64_after_increment" =>
4602        {
4603            Some(TypeRef::Map(
4604                Box::new(TypeRef::Named(
4605                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4606                )),
4607                Box::new(TypeRef::Map(
4608                    Box::new(TypeRef::Named(
4609                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4610                    )),
4611                    Box::new(TypeRef::U64),
4612                )),
4613            ))
4614        }
4615        Expr::Call { helper, .. } if helper == "mob_machine_run_retry_count_after_increment" => {
4616            Some(TypeRef::Map(
4617                Box::new(TypeRef::Named(
4618                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4619                )),
4620                Box::new(TypeRef::Map(
4621                    Box::new(TypeRef::String),
4622                    Box::new(TypeRef::U64),
4623                )),
4624            ))
4625        }
4626        Expr::Call { helper, .. } if helper == "mob_machine_frame_node_bool_after_set" => {
4627            Some(TypeRef::Map(
4628                Box::new(TypeRef::Named(
4629                    meerkat_machine_schema::identity::NamedTypeId::parse("FrameId").ok()?,
4630                )),
4631                Box::new(TypeRef::Map(
4632                    Box::new(TypeRef::Named(
4633                        meerkat_machine_schema::identity::NamedTypeId::parse("FlowNodeId").ok()?,
4634                    )),
4635                    Box::new(TypeRef::Bool),
4636                )),
4637            ))
4638        }
4639        Expr::Call { helper, .. } => helper_returns.get(helper).cloned(),
4640        Expr::SeqLiteral(items) => items.first().and_then(|item| {
4641            infer_expr_type(item, field_types, helper_returns, binding_types)
4642                .map(|inner_ty| TypeRef::Seq(Box::new(inner_ty)))
4643        }),
4644        Expr::EmptySet => None,
4645        Expr::EmptyMap => None,
4646    }
4647}
4648
4649fn default_sample_cardinality(deep: bool) -> usize {
4650    if deep { 2 } else { 1 }
4651}
4652
4653fn type_sample_bucket(ty: &TypeRef) -> Option<String> {
4654    match ty {
4655        TypeRef::String => Some("String".into()),
4656        TypeRef::Named(name) => Some(name.as_str().to_owned()),
4657        TypeRef::Enum(name) => Some(name.as_str().to_owned()),
4658        _ => None,
4659    }
4660}
4661
4662fn collected_sample_literals(
4663    bucket: &str,
4664    sample_cardinality: usize,
4665    named_samples: &BTreeMap<String, BTreeSet<String>>,
4666) -> Option<Vec<String>> {
4667    let samples = named_samples.get(bucket)?;
4668    let limit = sample_cardinality.max(1);
4669    let rendered = samples
4670        .iter()
4671        .take(limit)
4672        .map(tla_string)
4673        .collect::<Vec<_>>();
4674    (!rendered.is_empty()).then_some(rendered)
4675}
4676
4677fn generic_string_samples(sample_cardinality: usize) -> Vec<String> {
4678    if sample_cardinality > 1 {
4679        vec!["alpha".into(), "beta".into()]
4680    } else {
4681        vec!["alpha".into()]
4682    }
4683}
4684
4685fn collected_string_samples(
4686    sample_cardinality: usize,
4687    named_samples: &BTreeMap<String, BTreeSet<String>>,
4688    include_named_samples: bool,
4689) -> Vec<String> {
4690    let mut values = generic_string_samples(sample_cardinality);
4691    if include_named_samples && let Some(samples) = named_samples.get("String") {
4692        for sample in samples {
4693            if !values.iter().any(|existing| existing == sample) {
4694                values.push(sample.clone());
4695            }
4696        }
4697    }
4698    values
4699}
4700
4701fn render_default_domain_assignment(
4702    ty: &TypeRef,
4703    sample_cardinality: usize,
4704    named_samples: &BTreeMap<String, BTreeSet<String>>,
4705    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4706    include_string_samples: bool,
4707) -> String {
4708    match ty {
4709        TypeRef::Bool => "{TRUE, FALSE}".into(),
4710        TypeRef::U32 | TypeRef::U64 => {
4711            if sample_cardinality > 1 {
4712                "{0, 1, 2}".into()
4713            } else {
4714                // CI uses {1} to avoid state explosion from zero-as-unlimited
4715                // semantics in scheduler guards (Or(max==0, count<max)).
4716                // Counter fields that start at 0 get it via Init, not NatValues.
4717                // Deep uses {0, 1} to cover the full range.
4718                "{1}".into()
4719            }
4720        }
4721        TypeRef::String if sample_cardinality == 0 => "{}".into(),
4722        TypeRef::String => format!(
4723            "{{{}}}",
4724            collected_string_samples(sample_cardinality, named_samples, include_string_samples)
4725                .into_iter()
4726                .map(|sample| tla_string(&sample))
4727                .collect::<Vec<_>>()
4728                .join(", ")
4729        ),
4730        TypeRef::Named(name) => render_named_type_domain_assignment(
4731            name.as_str(),
4732            sample_cardinality,
4733            named_samples,
4734            named_bindings,
4735        ),
4736        TypeRef::Enum(name) => render_enum_type_domain_assignment(
4737            name.as_str(),
4738            sample_cardinality,
4739            named_samples,
4740            named_bindings,
4741        ),
4742        TypeRef::Seq(inner) => {
4743            let samples = sample_values(
4744                inner,
4745                sample_cardinality,
4746                named_samples,
4747                named_bindings,
4748                include_string_samples,
4749            );
4750            if samples.len() >= 2 {
4751                format!(
4752                    "{{<<>>, <<{}>>, <<{}, {}>>}}",
4753                    samples[0], samples[0], samples[1]
4754                )
4755            } else if let Some(sample) = samples.first() {
4756                format!("{{<<>>, <<{}>>}}", sample)
4757            } else {
4758                "{<<>>}".into()
4759            }
4760        }
4761        TypeRef::Set(inner) => {
4762            let samples = sample_values(
4763                inner,
4764                sample_cardinality,
4765                named_samples,
4766                named_bindings,
4767                include_string_samples,
4768            );
4769            if samples.len() >= 2 {
4770                format!(
4771                    "{{{{}}, {{{}}}, {{{}, {}}}}}",
4772                    samples[0], samples[0], samples[1]
4773                )
4774            } else if let Some(sample) = samples.first() {
4775                format!("{{{{}}, {{{}}}}}", sample)
4776            } else {
4777                "{{}}".into()
4778            }
4779        }
4780        TypeRef::Option(inner) => {
4781            let samples = sample_values(
4782                inner,
4783                sample_cardinality,
4784                named_samples,
4785                named_bindings,
4786                include_string_samples,
4787            )
4788            .into_iter()
4789            .map(|sample| format!("[tag |-> {}, value |-> {}]", tla_string("some"), sample))
4790            .collect::<Vec<_>>();
4791            if samples.is_empty() {
4792                format!(
4793                    "{{[tag |-> {}, value |-> {}]}}",
4794                    tla_string("none"),
4795                    tla_string("none")
4796                )
4797            } else {
4798                format!(
4799                    "{{[tag |-> {}, value |-> {}], {}}}",
4800                    tla_string("none"),
4801                    tla_string("none"),
4802                    samples.join(", ")
4803                )
4804            }
4805        }
4806        TypeRef::Map(_, _) => "{}".into(),
4807    }
4808}
4809
4810fn render_named_type_domain_assignment(
4811    name: impl AsRef<str>,
4812    sample_cardinality: usize,
4813    named_samples: &BTreeMap<String, BTreeSet<String>>,
4814    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4815) -> String {
4816    use meerkat_machine_schema::RustTypeAtom;
4817
4818    let name = name.as_ref();
4819    if name == "OperationSource" {
4820        return format!(
4821            "{{{}}}",
4822            operation_source_samples(sample_cardinality).join(", ")
4823        );
4824    }
4825    match require_named_binding(named_bindings, name) {
4826        RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8 => {
4827            if sample_cardinality > 1 {
4828                "{1, 2}".into()
4829            } else {
4830                "{1}".into()
4831            }
4832        }
4833        RustTypeAtom::Bool => "{TRUE, FALSE}".into(),
4834        RustTypeAtom::StringEnum { variants } => {
4835            format!(
4836                "{{{}}}",
4837                string_enum_variant_samples(name, variants).join(", ")
4838            )
4839        }
4840        RustTypeAtom::TypePathEnum {
4841            unit_variants,
4842            structural_variants,
4843            ..
4844        } => format!(
4845            "{{{}}}",
4846            type_path_enum_variant_samples(
4847                unit_variants,
4848                structural_variants,
4849                sample_cardinality,
4850                named_samples,
4851                named_bindings,
4852            )
4853            .join(", ")
4854        ),
4855        RustTypeAtom::TypePathFieldPresenceSet { fields, .. } => format!(
4856            "{{{}}}",
4857            field_presence_set_samples(fields, sample_cardinality).join(", ")
4858        ),
4859        RustTypeAtom::TypePathStruct { fields, .. } => format!(
4860            "{{{}}}",
4861            type_path_struct_samples(fields, sample_cardinality, named_samples, named_bindings)
4862                .join(", ")
4863        ),
4864        RustTypeAtom::String | RustTypeAtom::TypePath(_) => {
4865            if sample_cardinality == 0 {
4866                return "{}".into();
4867            }
4868
4869            if let Some(rendered) =
4870                collected_sample_literals(name, sample_cardinality, named_samples)
4871            {
4872                return format!("{{{}}}", rendered.join(", "));
4873            }
4874
4875            let values = (1..=sample_cardinality.max(1))
4876                .map(|idx| tla_string(format!("{}_{}", tla_ident(name).to_lowercase(), idx)))
4877                .collect::<Vec<_>>()
4878                .join(", ");
4879            format!("{{{values}}}")
4880        }
4881    }
4882}
4883
4884#[allow(clippy::panic)]
4885fn render_enum_type_domain_assignment(
4886    name: impl AsRef<str>,
4887    sample_cardinality: usize,
4888    named_samples: &BTreeMap<String, BTreeSet<String>>,
4889    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4890) -> String {
4891    use meerkat_machine_schema::RustTypeAtom;
4892
4893    let name = name.as_ref();
4894    match require_named_binding(named_bindings, name) {
4895        RustTypeAtom::StringEnum { variants } => {
4896            format!(
4897                "{{{}}}",
4898                string_enum_variant_samples(name, variants).join(", ")
4899            )
4900        }
4901        RustTypeAtom::TypePathEnum {
4902            unit_variants,
4903            structural_variants,
4904            ..
4905        } => format!(
4906            "{{{}}}",
4907            type_path_enum_variant_samples(
4908                unit_variants,
4909                structural_variants,
4910                sample_cardinality,
4911                named_samples,
4912                named_bindings,
4913            )
4914            .join(", ")
4915        ),
4916        other => {
4917            panic!(
4918                "generated enum domain `{name}` requires StringEnum or TypePathEnum binding, found {other:?}"
4919            );
4920        }
4921    }
4922}
4923
4924fn sample_values(
4925    ty: &TypeRef,
4926    sample_cardinality: usize,
4927    named_samples: &BTreeMap<String, BTreeSet<String>>,
4928    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4929    include_string_samples: bool,
4930) -> Vec<String> {
4931    match ty {
4932        TypeRef::Bool => vec!["TRUE".into(), "FALSE".into()],
4933        TypeRef::U32 | TypeRef::U64 => {
4934            if sample_cardinality > 1 {
4935                vec!["1".into(), "2".into()]
4936            } else {
4937                vec!["1".into()]
4938            }
4939        }
4940        TypeRef::String if sample_cardinality == 0 => Vec::new(),
4941        TypeRef::String => {
4942            collected_string_samples(sample_cardinality, named_samples, include_string_samples)
4943                .into_iter()
4944                .map(|sample| tla_string(&sample))
4945                .collect()
4946        }
4947        TypeRef::Named(name) if named_type_uses_nat_domain(named_bindings, name.as_str()) => {
4948            if sample_cardinality > 1 {
4949                vec!["1".into(), "2".into()]
4950            } else {
4951                vec!["1".into()]
4952            }
4953        }
4954        TypeRef::Named(name) => {
4955            let name = name.as_str();
4956            sample_values_for_named_type(name, sample_cardinality, named_samples, named_bindings)
4957        }
4958        TypeRef::Enum(name) => {
4959            let name = name.as_str();
4960            sample_values_for_enum_type(name, sample_cardinality, named_samples, named_bindings)
4961        }
4962        TypeRef::Option(inner) => {
4963            let mut values = vec![format!(
4964                "[tag |-> {}, value |-> {}]",
4965                tla_string("none"),
4966                tla_string("none")
4967            )];
4968            values.extend(
4969                sample_values(
4970                    inner,
4971                    sample_cardinality,
4972                    named_samples,
4973                    named_bindings,
4974                    include_string_samples,
4975                )
4976                .into_iter()
4977                .map(|sample| format!("[tag |-> {}, value |-> {}]", tla_string("some"), sample)),
4978            );
4979            values
4980        }
4981        TypeRef::Seq(inner) => sample_values(
4982            inner,
4983            sample_cardinality,
4984            named_samples,
4985            named_bindings,
4986            include_string_samples,
4987        ),
4988        TypeRef::Set(inner) => sample_values(
4989            inner,
4990            sample_cardinality,
4991            named_samples,
4992            named_bindings,
4993            include_string_samples,
4994        ),
4995        TypeRef::Map(_, _) => vec![],
4996    }
4997}
4998
4999fn sample_values_for_named_type(
5000    name: &str,
5001    sample_cardinality: usize,
5002    named_samples: &BTreeMap<String, BTreeSet<String>>,
5003    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5004) -> Vec<String> {
5005    use meerkat_machine_schema::RustTypeAtom;
5006
5007    if name == "OperationSource" {
5008        return operation_source_samples(sample_cardinality);
5009    }
5010    match require_named_binding(bindings, name) {
5011        RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8 => {
5012            if sample_cardinality > 1 {
5013                vec!["1".into(), "2".into()]
5014            } else {
5015                vec!["1".into()]
5016            }
5017        }
5018        RustTypeAtom::Bool => vec!["TRUE".into(), "FALSE".into()],
5019        RustTypeAtom::StringEnum { variants } => string_enum_variant_samples(name, variants),
5020        RustTypeAtom::TypePathEnum {
5021            unit_variants,
5022            structural_variants,
5023            ..
5024        } => type_path_enum_variant_samples(
5025            unit_variants,
5026            structural_variants,
5027            sample_cardinality,
5028            named_samples,
5029            bindings,
5030        ),
5031        RustTypeAtom::TypePathFieldPresenceSet { fields, .. } => {
5032            field_presence_set_samples(fields, sample_cardinality)
5033        }
5034        RustTypeAtom::TypePathStruct { fields, .. } => {
5035            type_path_struct_samples(fields, sample_cardinality, named_samples, bindings)
5036        }
5037        RustTypeAtom::String | RustTypeAtom::TypePath(_) => {
5038            if sample_cardinality == 0 {
5039                return Vec::new();
5040            }
5041            if let Some(samples) = named_samples.get(name) {
5042                let limit = sample_cardinality.max(1);
5043                let rendered = samples
5044                    .iter()
5045                    .take(limit)
5046                    .map(tla_string)
5047                    .collect::<Vec<_>>();
5048                if !rendered.is_empty() {
5049                    return rendered;
5050                }
5051            }
5052            (1..=sample_cardinality.max(1))
5053                .map(|idx| tla_string(format!("{}_{}", tla_ident(name).to_lowercase(), idx)))
5054                .collect()
5055        }
5056    }
5057}
5058
5059#[allow(clippy::panic)]
5060fn sample_values_for_enum_type(
5061    name: &str,
5062    sample_cardinality: usize,
5063    named_samples: &BTreeMap<String, BTreeSet<String>>,
5064    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5065) -> Vec<String> {
5066    use meerkat_machine_schema::RustTypeAtom;
5067
5068    match require_named_binding(bindings, name) {
5069        RustTypeAtom::StringEnum { variants } => string_enum_variant_samples(name, variants),
5070        RustTypeAtom::TypePathEnum {
5071            unit_variants,
5072            structural_variants,
5073            ..
5074        } => type_path_enum_variant_samples(
5075            unit_variants,
5076            structural_variants,
5077            sample_cardinality,
5078            named_samples,
5079            bindings,
5080        ),
5081        other => {
5082            panic!(
5083                "generated enum domain `{name}` requires StringEnum or TypePathEnum binding, found {other:?}"
5084            );
5085        }
5086    }
5087}
5088
5089#[allow(clippy::panic)]
5090fn require_named_binding<'a>(
5091    bindings: &'a BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5092    name: &str,
5093) -> &'a meerkat_machine_schema::RustTypeAtom {
5094    bindings
5095        .get(name)
5096        .unwrap_or_else(|| panic!("missing NamedTypeBinding for generated domain `{name}`"))
5097}
5098
5099fn string_enum_variant_samples(
5100    name: &str,
5101    variants: &[meerkat_machine_schema::identity::EnumVariantId],
5102) -> Vec<String> {
5103    variants
5104        .iter()
5105        .map(|variant| tla_string(string_enum_wire_label(name, variant.as_str())))
5106        .collect()
5107}
5108
5109fn render_named_variant_value(
5110    enum_name: &str,
5111    variant: &str,
5112    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5113) -> String {
5114    let label = tla_string(string_enum_wire_label(enum_name, variant));
5115    if named_bindings
5116        .get(enum_name)
5117        .is_some_and(CfgRecordRendering::renders_cfg_hostile_record)
5118    {
5119        format!("[tag |-> {label}]")
5120    } else {
5121        label
5122    }
5123}
5124
5125fn type_path_enum_variant_samples(
5126    unit_variants: &[meerkat_machine_schema::identity::EnumVariantId],
5127    structural_variants: &[TypePathEnumStructuralVariant],
5128    sample_cardinality: usize,
5129    named_samples: &BTreeMap<String, BTreeSet<String>>,
5130    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5131) -> Vec<String> {
5132    let unit_variants_are_records = !structural_variants.is_empty();
5133    let mut samples = unit_variants
5134        .iter()
5135        .map(|variant| {
5136            let tag = tla_string(variant.as_str());
5137            if unit_variants_are_records {
5138                format!("[tag |-> {tag}]")
5139            } else {
5140                tag
5141            }
5142        })
5143        .collect::<Vec<_>>();
5144    if sample_cardinality > 0 {
5145        samples.extend(structural_variants.iter().flat_map(|variant| {
5146            render_type_path_enum_structural_samples(
5147                variant,
5148                sample_cardinality,
5149                named_samples,
5150                named_bindings,
5151            )
5152        }));
5153    }
5154    samples
5155}
5156
5157fn field_presence_set_samples(
5158    fields: &[meerkat_machine_schema::identity::FieldId],
5159    sample_cardinality: usize,
5160) -> Vec<String> {
5161    if sample_cardinality == 0 {
5162        return Vec::new();
5163    }
5164    let limit = sample_cardinality.max(1);
5165    let rendered_fields = fields
5166        .iter()
5167        .map(|field| tla_string(field.as_str()))
5168        .collect::<Vec<_>>();
5169    let mut samples = rendered_fields
5170        .iter()
5171        .take(limit)
5172        .map(|field| format!("{{{field}}}"))
5173        .collect::<Vec<_>>();
5174    if limit > rendered_fields.len() && rendered_fields.len() >= 2 {
5175        samples.push(format!("{{{}}}", rendered_fields.join(", ")));
5176    }
5177    samples
5178}
5179
5180fn operation_source_samples(sample_cardinality: usize) -> Vec<String> {
5181    let mut samples = vec![
5182        format!(
5183            "[kind |-> {}, session_id |-> Some({}), peer_id |-> None, address |-> None]",
5184            tla_string("SessionChild"),
5185            tla_string("sessionid_1")
5186        ),
5187        format!(
5188            "[kind |-> {}, session_id |-> None, peer_id |-> Some({}), address |-> Some({})]",
5189            tla_string("BackendPeer"),
5190            tla_string("peerid_1"),
5191            tla_string("peeraddress_1")
5192        ),
5193    ];
5194    if sample_cardinality > 2 {
5195        samples.push(format!(
5196            "[kind |-> {}, session_id |-> Some({}), peer_id |-> None, address |-> None]",
5197            tla_string("SessionChild"),
5198            tla_string("sessionid_2")
5199        ));
5200    }
5201    samples
5202}
5203
5204fn type_path_struct_samples(
5205    fields: &[TypePathStructField],
5206    sample_cardinality: usize,
5207    named_samples: &BTreeMap<String, BTreeSet<String>>,
5208    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5209) -> Vec<String> {
5210    if sample_cardinality == 0 {
5211        return Vec::new();
5212    }
5213    if fields.is_empty() {
5214        return vec!["[]".to_owned()];
5215    }
5216
5217    let limit = sample_cardinality.max(1);
5218    let mut field_values = Vec::new();
5219    for field in fields {
5220        let values =
5221            type_path_struct_field_samples(field, sample_cardinality, named_samples, bindings);
5222        if values.is_empty() {
5223            return Vec::new();
5224        }
5225        field_values.push((field.name.as_str().to_owned(), values));
5226    }
5227
5228    (0..limit)
5229        .map(|idx| {
5230            let fields = field_values
5231                .iter()
5232                .map(|(name, values)| {
5233                    let value = &values[idx % values.len()];
5234                    format!("{name} |-> {value}")
5235                })
5236                .collect::<Vec<_>>();
5237            format!("[{}]", fields.join(", "))
5238        })
5239        .collect()
5240}
5241
5242fn type_path_struct_field_samples(
5243    field: &TypePathStructField,
5244    sample_cardinality: usize,
5245    named_samples: &BTreeMap<String, BTreeSet<String>>,
5246    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5247) -> Vec<String> {
5248    match &field.atom {
5249        TypePathStructFieldAtom::String => {
5250            if sample_cardinality == 0 {
5251                Vec::new()
5252            } else {
5253                generic_string_samples(sample_cardinality)
5254                    .into_iter()
5255                    .map(tla_string)
5256                    .collect()
5257            }
5258        }
5259        TypePathStructFieldAtom::Named(name) => {
5260            sample_values_for_named_type(name.as_str(), sample_cardinality, named_samples, bindings)
5261        }
5262        TypePathStructFieldAtom::OptionalNamed(name) => {
5263            let mut values = vec!["None".to_owned()];
5264            values.extend(
5265                sample_values_for_named_type(
5266                    name.as_str(),
5267                    sample_cardinality,
5268                    named_samples,
5269                    bindings,
5270                )
5271                .into_iter()
5272                .map(|value| format!("Some({value})")),
5273            );
5274            values
5275        }
5276    }
5277}
5278
5279fn render_type_path_enum_structural_samples(
5280    variant: &TypePathEnumStructuralVariant,
5281    sample_cardinality: usize,
5282    named_samples: &BTreeMap<String, BTreeSet<String>>,
5283    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5284) -> Vec<String> {
5285    let mut samples = vec![vec![format!(
5286        "tag |-> {}",
5287        tla_string(variant.variant.as_str())
5288    )]];
5289    for field in &variant.fields {
5290        let values = match &field.atom {
5291            TypePathEnumPayloadAtom::StringSet => string_set_payload_samples(sample_cardinality),
5292            TypePathEnumPayloadAtom::NamedSet(type_name) => named_set_payload_samples(
5293                type_name.as_str(),
5294                sample_cardinality,
5295                named_samples,
5296                named_bindings,
5297            ),
5298            TypePathEnumPayloadAtom::String => {
5299                if sample_cardinality == 0 {
5300                    Vec::new()
5301                } else {
5302                    generic_string_samples(sample_cardinality)
5303                        .into_iter()
5304                        .map(tla_string)
5305                        .collect()
5306                }
5307            }
5308            TypePathEnumPayloadAtom::OptionalString => {
5309                let mut values = vec![format!(
5310                    "[tag |-> {}, value |-> {}]",
5311                    tla_string("none"),
5312                    tla_string("none")
5313                )];
5314                if sample_cardinality > 0 {
5315                    values.extend(generic_string_samples(sample_cardinality).into_iter().map(
5316                        |sample| {
5317                            format!(
5318                                "[tag |-> {}, value |-> {}]",
5319                                tla_string("some"),
5320                                tla_string(&sample)
5321                            )
5322                        },
5323                    ));
5324                }
5325                values
5326            }
5327            TypePathEnumPayloadAtom::Named(type_name) => sample_values_for_named_type(
5328                type_name.as_str(),
5329                sample_cardinality,
5330                named_samples,
5331                named_bindings,
5332            ),
5333        };
5334        let mut next_samples = Vec::new();
5335        for sample in &samples {
5336            for value in &values {
5337                let mut next = sample.clone();
5338                next.push(format!("{} |-> {value}", field.name));
5339                next_samples.push(next);
5340            }
5341        }
5342        samples = next_samples;
5343    }
5344    samples
5345        .into_iter()
5346        .map(|fields| format!("[{}]", fields.join(", ")))
5347        .collect()
5348}
5349
5350/// TLA sample sets for a structural enum payload carrying a finite set of
5351/// values from a named value domain. Mirrors [`string_set_payload_samples`]
5352/// shape (empty / one-member / two-member sets) over the named domain's
5353/// sample pool so payload sets stay aligned with catalog key domains.
5354fn named_set_payload_samples(
5355    type_name: &str,
5356    sample_cardinality: usize,
5357    named_samples: &BTreeMap<String, BTreeSet<String>>,
5358    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5359) -> Vec<String> {
5360    let mut values = if sample_cardinality == 0 {
5361        Vec::new()
5362    } else {
5363        sample_values_for_named_type(type_name, sample_cardinality, named_samples, named_bindings)
5364    };
5365    // Pad the payload element pool with synthetic domain members up to the
5366    // requested cardinality so the deep model still covers differing
5367    // same-variant multi-member payloads when the collected named-sample
5368    // pool is smaller than the cardinality.
5369    let mut synthetic_idx = 0usize;
5370    while sample_cardinality > 0 && values.len() < sample_cardinality {
5371        synthetic_idx += 1;
5372        let synthetic = tla_string(format!(
5373            "{}_{synthetic_idx}",
5374            tla_ident(type_name).to_lowercase()
5375        ));
5376        if !values.contains(&synthetic) {
5377            values.push(synthetic);
5378        }
5379    }
5380    let mut samples = vec!["{}".to_owned()];
5381    if let Some(first) = values.first() {
5382        samples.push(format!("{{{first}}}"));
5383    }
5384    if values.len() >= 2 {
5385        samples.push(format!("{{{}, {}}}", values[0], values[1]));
5386    }
5387    samples
5388}
5389
5390fn string_set_payload_samples(sample_cardinality: usize) -> Vec<String> {
5391    let values = if sample_cardinality == 0 {
5392        Vec::new()
5393    } else {
5394        generic_string_samples(sample_cardinality)
5395            .into_iter()
5396            .map(tla_string)
5397            .collect::<Vec<_>>()
5398    };
5399    let mut samples = vec!["{}".to_owned()];
5400    if let Some(first) = values.first() {
5401        samples.push(format!("{{{first}}}"));
5402    }
5403    if values.len() >= 2 {
5404        samples.push(format!("{{{}, {}}}", values[0], values[1]));
5405    }
5406    samples
5407}
5408
5409fn string_enum_wire_label(name: &str, variant: &str) -> String {
5410    if name == meerkat_core::turn_execution_authority::ContentShape::SCHEMA_TYPE_NAME
5411        && let Some(shape) =
5412            meerkat_core::turn_execution_authority::ContentShape::from_schema_variant(variant)
5413    {
5414        return shape.as_str().to_owned();
5415    }
5416
5417    variant.to_owned()
5418}
5419
5420/// Consult the schema's named-type binding table to decide whether a
5421/// named type's TLA domain is `Nat` (numeric) rather than string-like.
5422///
5423/// A named type resolves to a `Nat` TLA domain when its Rust atom lowers
5424/// to an unsigned integer width — the TLA projection mirrors the Rust
5425/// atom. Schemas reach codegen only after validation, so every
5426/// referenced named type has a binding; an unbound name here is a
5427/// codegen invariant violation.
5428fn named_type_uses_nat_domain(
5429    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5430    name: &str,
5431) -> bool {
5432    use meerkat_machine_schema::RustTypeAtom;
5433    matches!(
5434        bindings.get(name),
5435        Some(RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8)
5436    )
5437}
5438
5439/// Collect the `NamedTypeId → RustTypeAtom` map for a single machine.
5440fn collect_machine_named_bindings(
5441    schema: &MachineSchema,
5442) -> BTreeMap<String, meerkat_machine_schema::RustTypeAtom> {
5443    assert_machine_named_bindings_match_canonical(schema);
5444    schema
5445        .named_types
5446        .iter()
5447        .map(|binding| (binding.name.as_str().to_owned(), binding.rust.clone()))
5448        .collect()
5449}
5450
5451/// A machine that shares a canonical machine's id must bind every canonical
5452/// struct named type, and bind each shared named type with the canonical
5453/// generated domain shape.
5454fn check_canonical_named_bindings(schema: &MachineSchema) -> Result<(), CompositionTlaError> {
5455    let Some(canonical) = canonical_machine_schemas()
5456        .into_iter()
5457        .find(|canonical| canonical.machine == schema.machine)
5458    else {
5459        return Ok(());
5460    };
5461    let mismatch = |named_type: &str, reason| CompositionTlaError::CanonicalNamedTypeMismatch {
5462        machine: schema.machine.as_str().to_owned(),
5463        named_type: named_type.to_owned(),
5464        reason,
5465    };
5466    for canonical_binding in canonical.named_types.iter().filter(|binding| {
5467        matches!(
5468            binding.rust,
5469            meerkat_machine_schema::RustTypeAtom::TypePathStruct { .. }
5470        )
5471    }) {
5472        if !schema
5473            .named_types
5474            .iter()
5475            .any(|binding| binding.name == canonical_binding.name)
5476        {
5477            return Err(mismatch(
5478                canonical_binding.name.as_str(),
5479                CanonicalNamedTypeMismatchKind::MissingStructBinding,
5480            ));
5481        }
5482    }
5483    for binding in &schema.named_types {
5484        let Some(canonical_binding) = canonical
5485            .named_types
5486            .iter()
5487            .find(|candidate| candidate.name == binding.name)
5488        else {
5489            continue;
5490        };
5491        if !canonical_binding
5492            .rust
5493            .has_same_composition_domain_shape(&binding.rust)
5494        {
5495            return Err(mismatch(
5496                binding.name.as_str(),
5497                CanonicalNamedTypeMismatchKind::DomainShape,
5498            ));
5499        }
5500    }
5501    Ok(())
5502}
5503
5504/// Internal invariant for the infallible renderers, whose callers pass
5505/// canonical machines; the public fallible entry points check first.
5506fn assert_machine_named_bindings_match_canonical(schema: &MachineSchema) {
5507    if let Err(CompositionTlaError::CanonicalNamedTypeMismatch {
5508        machine,
5509        named_type,
5510        reason,
5511    }) = check_canonical_named_bindings(schema)
5512    {
5513        assert!(
5514            reason != CanonicalNamedTypeMismatchKind::MissingStructBinding,
5515            "generated machine `{machine}` missing canonical named-type `{named_type}` binding"
5516        );
5517        assert!(
5518            reason != CanonicalNamedTypeMismatchKind::DomainShape,
5519            "generated machine `{machine}` named-type `{named_type}` binding must match canonical domain shape"
5520        );
5521    }
5522}
5523
5524/// Validate a caller-supplied machine catalog before rendering a composition
5525/// against it: every machine validates, ids are unique, no machine shadows a
5526/// canonical Meerkat machine with a different schema, the composition's
5527/// machines agree on shared named types, and the composition validates
5528/// against the catalog. The render paths behind this never panic on a
5529/// supplied catalog.
5530fn validate_supplied_catalog(
5531    schema: &CompositionSchema,
5532    machine_catalog: &[MachineSchema],
5533) -> Result<(), CompositionTlaError> {
5534    let canonical = canonical_machine_schemas();
5535    let mut seen = BTreeSet::new();
5536    for machine in machine_catalog {
5537        machine
5538            .validate()
5539            .map_err(|error| CompositionTlaError::InvalidSuppliedMachine {
5540                machine: machine.machine.as_str().to_owned(),
5541                error: error.to_string(),
5542            })?;
5543        if !seen.insert(machine.machine.as_str()) {
5544            return Err(CompositionTlaError::DuplicateSuppliedMachine {
5545                machine: machine.machine.as_str().to_owned(),
5546            });
5547        }
5548        if canonical
5549            .iter()
5550            .any(|candidate| candidate.machine == machine.machine && candidate != machine)
5551        {
5552            return Err(CompositionTlaError::ShadowsCanonicalMachine {
5553                machine: machine.machine.as_str().to_owned(),
5554            });
5555        }
5556    }
5557    let mut merged: BTreeMap<&str, &meerkat_machine_schema::RustTypeAtom> = BTreeMap::new();
5558    for instance in &schema.machines {
5559        let Some(machine) = machine_catalog
5560            .iter()
5561            .find(|machine| machine.machine.as_str() == instance.machine_name.as_str())
5562        else {
5563            continue;
5564        };
5565        for binding in &machine.named_types {
5566            match merged.get(binding.name.as_str()) {
5567                Some(existing) if !existing.has_same_composition_domain_shape(&binding.rust) => {
5568                    return Err(CompositionTlaError::DivergentNamedTypeBinding {
5569                        composition: schema.name.as_str().to_owned(),
5570                        named_type: binding.name.as_str().to_owned(),
5571                    });
5572                }
5573                Some(_) => {}
5574                None => {
5575                    merged.insert(binding.name.as_str(), &binding.rust);
5576                }
5577            }
5578        }
5579    }
5580    let machines = machine_catalog.iter().collect::<Vec<_>>();
5581    schema.validate_against(&machines).map_err(|error| {
5582        CompositionTlaError::InvalidCompositionForCatalog {
5583            composition: schema.name.as_str().to_owned(),
5584            error: error.to_string(),
5585        }
5586    })
5587}
5588
5589/// Merge every machine's named-type bindings into one map for
5590/// composition-level TLA rendering. Duplicate names must agree on generated
5591/// domain shape across machines (validation enforces this by construction).
5592fn collect_composition_named_bindings<'a>(
5593    machines_by_instance: impl IntoIterator<Item = &'a MachineSchema>,
5594) -> BTreeMap<String, meerkat_machine_schema::RustTypeAtom> {
5595    let mut merged: BTreeMap<String, meerkat_machine_schema::RustTypeAtom> = BTreeMap::new();
5596    for machine in machines_by_instance {
5597        assert_machine_named_bindings_match_canonical(machine);
5598        for binding in &machine.named_types {
5599            let slug = binding.name.as_str().to_owned();
5600            if let Some(existing) = merged.get(&slug) {
5601                assert!(
5602                    existing.has_same_composition_domain_shape(&binding.rust),
5603                    "composition named-type `{slug}` binding must agree across machine schemas"
5604                );
5605            } else {
5606                merged.insert(slug, binding.rust.clone());
5607            }
5608        }
5609    }
5610    merged
5611}
5612
5613#[cfg(test)]
5614mod tests {
5615    use super::*;
5616
5617    /// A populated witness map literal renders as a TLC function in both the
5618    /// witness-literal path and the expression path, never as the `None`
5619    /// fallback (#1811).
5620    #[test]
5621    fn a_witness_map_literal_renders_as_a_tlc_function() {
5622        let machines = meerkat_machine_schema::canonical_machine_schemas();
5623        let compositions = meerkat_machine_schema::canonical_composition_schemas();
5624        let composition = compositions
5625            .iter()
5626            .find(|candidate| candidate.name.as_str() == "job_runtime_delivery")
5627            .expect("job_runtime_delivery composition");
5628        let compiler =
5629            CompositionTlaCompiler::new(composition, &machines).expect("composition compiler");
5630        let literal = Expr::MapLiteral(vec![
5631            (
5632                Expr::String("alpha".into()),
5633                Expr::String("member-a".into()),
5634            ),
5635            (Expr::String("beta".into()), Expr::U64(2)),
5636        ]);
5637        assert_eq!(
5638            compiler.render_literal_expr(&literal),
5639            "(\"alpha\" :> \"member-a\" @@ \"beta\" :> 2)"
5640        );
5641        assert_eq!(
5642            crate::render::render_expr_for_tests(&literal),
5643            "(\"alpha\" :> \"member-a\" @@ \"beta\" :> 2)"
5644        );
5645    }
5646
5647    /// Every quantified Next disjunct leads with its transition's source-phase
5648    /// guard, so TLC rejects the whole disjunct in other phases instead of
5649    /// enumerating each parameter tuple per state (#1499 measured 464 s
5650    /// unhoisted against 158 s hoisted on work_graph_lifecycle ci, identical
5651    /// state counts).
5652    #[test]
5653    fn quantified_next_disjuncts_lead_with_the_source_phase_guard() {
5654        let model =
5655            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
5656        let next = model
5657            .split_once("\nNext ==\n")
5658            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5659            .expect("Next block");
5660        let quantified = next
5661            .lines()
5662            .filter(|line| line.contains("\\E "))
5663            .collect::<Vec<_>>();
5664        assert!(
5665            !quantified.is_empty(),
5666            "MeerkatMachine has quantified transitions"
5667        );
5668        for line in &quantified {
5669            assert!(
5670                line.starts_with("    \\/ (phase = "),
5671                "quantified Next disjunct without a leading phase guard: {line}"
5672            );
5673        }
5674        assert!(
5675            next.contains("    \\/ (phase = \"Running\") /\\ \\E run_id \\in RunIdValues : RequestCancelAfterBoundary(run_id)"),
5676            "the guard is the transition's own source phase"
5677        );
5678    }
5679
5680    fn next_disjunct_for<'a>(model: &'a str, action: &str) -> &'a str {
5681        let next = model
5682            .split_once("\nNext ==\n")
5683            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5684            .expect("Next block");
5685        next.lines()
5686            .find(|line| line.contains(&format!(" {action}(")))
5687            .expect("Next disjunct for the action")
5688    }
5689
5690    /// A declared domain, not a binding name, decides an input field's TLC
5691    /// domain: additional values extend the default unsigned range, a state
5692    /// binding explores exactly the state field, and an undeclared
5693    /// `expected_revision` gets the plain default (the old name match is gone).
5694    #[test]
5695    fn declared_input_field_domains_decide_the_rendered_domain() {
5696        use meerkat_machine_schema::catalog::dsl::dsl_workgraph_lifecycle_machine;
5697        use meerkat_machine_schema::identity::{FieldId, InputVariantId};
5698        use meerkat_machine_schema::{InputFieldDomain, InputFieldDomainKind};
5699
5700        let shipped = dsl_workgraph_lifecycle_machine();
5701        let model = render_machine_semantic_model(&shipped).expect("render workgraph model");
5702        assert!(
5703            next_disjunct_for(&model, "UpdateOpen")
5704                .contains("\\E expected_revision \\in {revision} : "),
5705            "a state-bound declaration explores exactly the state field"
5706        );
5707
5708        let mut sampled = shipped.clone();
5709        sampled.input_field_domains.push(InputFieldDomain {
5710            input: InputVariantId::parse("CreateOpen").expect("input slug"),
5711            field: FieldId::parse("unresolved_blocker_count").expect("field slug"),
5712            domain: InputFieldDomainKind::AdditionalValues([3, 8].into_iter().collect()),
5713        });
5714        let model = render_machine_semantic_model(&sampled).expect("render sampled model");
5715        assert!(
5716            next_disjunct_for(&model, "CreateOpen")
5717                .contains("\\E arg_unresolved_blocker_count \\in (0..2 \\cup {3, 8}) : "),
5718            "additional values extend the default unsigned domain"
5719        );
5720
5721        let mut undeclared = shipped;
5722        undeclared.input_field_domains.clear();
5723        let model = render_machine_semantic_model(&undeclared).expect("render undeclared model");
5724        assert!(
5725            next_disjunct_for(&model, "UpdateOpen").contains("\\E expected_revision \\in 0..2 : "),
5726            "without a declaration the binding name no longer selects a domain"
5727        );
5728    }
5729
5730    /// A `CiValues` declaration ranges the field over a model constant: the
5731    /// CI config assigns it exactly the declared values, the Deep config those
5732    /// and the default unsigned domain.
5733    #[test]
5734    fn ci_values_narrow_the_ci_profile_alone() {
5735        use meerkat_machine_schema::catalog::dsl::dsl_workgraph_lifecycle_machine;
5736        use meerkat_machine_schema::identity::{FieldId, InputVariantId};
5737        use meerkat_machine_schema::{InputFieldDomain, InputFieldDomainKind};
5738
5739        let mut sampled = dsl_workgraph_lifecycle_machine();
5740        sampled.input_field_domains.push(InputFieldDomain {
5741            input: InputVariantId::parse("CreateOpen").expect("input slug"),
5742            field: FieldId::parse("unresolved_blocker_count").expect("field slug"),
5743            domain: InputFieldDomainKind::CiValues([0, 5].into_iter().collect()),
5744        });
5745        let constant = "InputSamples_CreateOpen_unresolved_blocker_count";
5746        let model = render_machine_semantic_model(&sampled).expect("render sampled model");
5747        assert!(
5748            next_disjunct_for(&model, "CreateOpen").contains(&format!(
5749                "\\E arg_unresolved_blocker_count \\in {constant} : "
5750            )),
5751            "the field ranges over its samples constant"
5752        );
5753        let constants_line = model
5754            .lines()
5755            .find(|line| line.starts_with("CONSTANTS "))
5756            .expect("model constants");
5757        assert!(
5758            constants_line.contains(constant),
5759            "the model declares the samples constant: {constants_line}"
5760        );
5761        assert!(
5762            next_disjunct_for(&model, "UpdateOpen")
5763                .contains("\\E expected_revision \\in {revision} : "),
5764            "the machine's other declarations are unchanged"
5765        );
5766
5767        let ci = render_machine_ci_cfg(&sampled, false).expect("valid CI CFG");
5768        assert!(
5769            ci.contains(&format!("\n  {constant} = {{0, 5}}\n")),
5770            "the CI config assigns exactly the declared values:\n{ci}"
5771        );
5772        let deep = render_machine_ci_cfg(&sampled, true).expect("valid Deep CFG");
5773        assert!(
5774            deep.contains(&format!("\n  {constant} = {{0, 1, 2, 5}}\n")),
5775            "the Deep config keeps the default domain beside the declared values:\n{deep}"
5776        );
5777        assert_eq!(
5778            broad_input_samples(&[0, 5].into_iter().collect::<BTreeSet<u64>>()),
5779            [0, 1, 2, 5].into_iter().collect::<BTreeSet<u64>>(),
5780            "outside the CI profile the field keeps the default domain beside its values"
5781        );
5782    }
5783
5784    /// A `CiSamples` declaration ranges a field of any type over a model
5785    /// constant that each profile's config assigns through an operator of
5786    /// the model: the CI profile the declared values, the Deep profile the
5787    /// field type's whole domain. DurableDecisionMachine's carried
5788    /// presentation is the shipped case; Present declares nothing, so it
5789    /// keeps every link a presentation's link can serve.
5790    #[test]
5791    fn ci_samples_narrow_the_ci_profile_alone_for_a_field_of_any_type() {
5792        let schema = meerkat_machine_schema::catalog::dsl::dsl_durable_decision_machine();
5793        let model = render_machine_semantic_model(&schema).expect("render DurableDecisionMachine");
5794        let ci = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
5795        let deep = render_machine_ci_cfg(&schema, true).expect("valid Deep CFG");
5796        let next = model
5797            .split_once("\nNext ==\n")
5798            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5799            .expect("Next block");
5800        let constants_line = model
5801            .lines()
5802            .find(|line| line.starts_with("CONSTANTS "))
5803            .expect("model constants");
5804        let decide = next
5805            .lines()
5806            .filter(|line| line.contains(": Decide"))
5807            .collect::<Vec<_>>();
5808        assert!(!decide.is_empty(), "Decide has Next disjuncts");
5809        for (field, ci_values, deep_domain) in [
5810            (
5811                "carried_audience",
5812                "{Some(\"alpha\")}",
5813                "OptionDecisionPartyValues",
5814            ),
5815            (
5816                "carried_digest",
5817                "{Some(\"alpha\")}",
5818                "OptionDecisionDigestValues",
5819            ),
5820            ("carried_complete", "{FALSE}", "BOOLEAN"),
5821            (
5822                "carried_link_served_digest",
5823                "{Some(\"alpha\")}",
5824                "OptionDecisionDigestValues",
5825            ),
5826        ] {
5827            let constant = format!("InputSamples_Decide_{field}");
5828            for line in &decide {
5829                assert!(
5830                    line.contains(&format!("\\E {field} \\in {constant} : ")),
5831                    "Decide.{field} ranges over {constant}: {line}"
5832                );
5833            }
5834            assert!(
5835                constants_line.contains(&constant),
5836                "the model declares {constant}: {constants_line}"
5837            );
5838            assert!(
5839                model.contains(&format!("\n{constant}Ci == {ci_values}\n")),
5840                "the model defines the CI samples of Decide.{field}"
5841            );
5842            assert!(
5843                model.contains(&format!("\n{constant}Deep == {deep_domain}\n")),
5844                "the model defines the Deep domain of Decide.{field}"
5845            );
5846            assert!(
5847                ci.contains(&format!("\n  {constant} <- {constant}Ci\n")),
5848                "the CI config samples Decide.{field}:\n{ci}"
5849            );
5850            assert!(
5851                deep.contains(&format!("\n  {constant} <- {constant}Deep\n")),
5852                "the Deep config keeps the whole domain of Decide.{field}:\n{deep}"
5853            );
5854        }
5855        let present = next
5856            .lines()
5857            .filter(|line| line.contains(": Present"))
5858            .collect::<Vec<_>>();
5859        assert!(!present.is_empty(), "Present has Next disjuncts");
5860        for line in present {
5861            assert!(
5862                line.contains("\\E link_served_digest \\in OptionDecisionDigestValues : "),
5863                "Present keeps every served link: {line}"
5864            );
5865        }
5866    }
5867
5868    /// SessionDocumentMachine's CI bound: under a step bound of 5 the CI
5869    /// profile explores the samples it declares, in every Next disjunct of
5870    /// the input's transitions; the Deep profile keeps `0..2` for each of
5871    /// them and its step bound of 8.
5872    #[test]
5873    fn session_document_narrows_its_ci_samples_only() {
5874        let schema = meerkat_machine_schema::catalog::dsl::dsl_session_document_machine();
5875        let model = render_machine_semantic_model(&schema).expect("render SessionDocumentMachine");
5876        let ci = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
5877        let deep = render_machine_ci_cfg(&schema, true).expect("valid Deep CFG");
5878        let next = model
5879            .split_once("\nNext ==\n")
5880            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5881            .expect("Next block");
5882        for (input, field, ci_values) in [
5883            ("ClassifyDurableTail", "dangling_tool_use_count", "{0}"),
5884            ("ClassifyDurableTail", "orphan_tool_result_count", "{0}"),
5885            ("RecoverSessionInstructionState", "target_generation", "{2}"),
5886            ("RecoverSessionInstructionState", "entry_sequence", "{0}"),
5887            ("RecoverSessionInstructionEffective", "generation", "{0}"),
5888            (
5889                "RecoverSessionInstructionEffective",
5890                "last_entry_sequence",
5891                "{0, 1}",
5892            ),
5893            ("SetSessionInstruction", "body_bytes", "{1}"),
5894        ] {
5895            let constant = format!("InputSamples_{input}_{field}");
5896            let disjuncts = next
5897                .lines()
5898                .filter(|line| line.contains(&format!(": {input}")))
5899                .collect::<Vec<_>>();
5900            assert!(!disjuncts.is_empty(), "{input} has Next disjuncts");
5901            for line in disjuncts {
5902                assert!(
5903                    line.contains(&format!("\\E {field} \\in {constant} : ")),
5904                    "{input}.{field} ranges over {constant}: {line}"
5905                );
5906            }
5907            assert!(
5908                ci.contains(&format!("\n  {constant} = {ci_values}\n")),
5909                "the CI config samples {input}.{field} as {ci_values}:\n{ci}"
5910            );
5911            assert!(
5912                deep.contains(&format!("\n  {constant} = {{0, 1, 2}}\n")),
5913                "the Deep config keeps 0..2 for {input}.{field}:\n{deep}"
5914            );
5915        }
5916        assert!(
5917            model.contains("\nCiStateConstraint == /\\ model_step_count <= 5 "),
5918            "the CI step bound is 5"
5919        );
5920        assert!(
5921            model.contains("\nDeepStateConstraint == /\\ model_step_count <= 8 "),
5922            "the Deep step bound stays 8"
5923        );
5924    }
5925
5926    #[test]
5927    fn substituted_compound_values_are_delimited_and_atoms_are_not() {
5928        for atom in [
5929            "x",
5930            "packet.payload.run_id",
5931            "Some(run_id)",
5932            "MapSet(m, k, v)",
5933            "m[k]",
5934            "f(a)[b](c)",
5935            "(a + 1)",
5936            "\"a(b\"",
5937            "42",
5938        ] {
5939            assert_eq!(tla_delimited(atom), atom, "{atom} is already an operand");
5940        }
5941        for compound in [
5942            "IF c THEN a ELSE b",
5943            "x + 1",
5944            "s \\cup {x}",
5945            "(a) + (b)",
5946            "f(a) = b",
5947            "~x",
5948        ] {
5949            assert_eq!(
5950                tla_delimited(compound),
5951                format!("({compound})"),
5952                "{compound} must be delimited before splicing"
5953            );
5954        }
5955    }
5956
5957    /// A field assigned by a conditional update earlier in the same block is
5958    /// read through its pending value, a bare `IF c THEN a ELSE b`. Spliced
5959    /// unparenthesized into a later expression, TLA+ precedence captured the
5960    /// surrounding operator. Shipped instance: the meerkat_mob_seam
5961    /// `TurnRunFailed` payload unwraps the conditionally updated
5962    /// `terminal_cause_kind` as `IF "value" \in DOMAIN v THEN v["value"] ELSE
5963    /// None`; with `v` bare, `["value"]` applied to v's ELSE branch only, so
5964    /// the THEN branch emitted the Option record instead of its value.
5965    #[test]
5966    fn a_conditionally_updated_field_read_later_in_the_block_splices_as_one_operand() {
5967        let model = render_composition_semantic_model(&meerkat_mob_seam_composition())
5968            .expect("render meerkat_mob_seam model");
5969        assert!(
5970            model.contains(
5971                "terminal_cause_kind |-> (IF \"value\" \\in DOMAIN (IF (IF (meerkat_terminal_cause_kind = None)"
5972            ),
5973            "the TurnRunFailed unwrap must test the whole conditional value"
5974        );
5975        assert!(
5976            !model.contains("ELSE meerkat_terminal_cause_kind[\"value\"]"),
5977            "no index may bind to one branch of a spliced conditional"
5978        );
5979    }
5980
5981    /// A set insert or remove of a field that a conditional update already
5982    /// changed earlier in the same block takes the field's pending value, a
5983    /// bare `IF c THEN a ELSE b`, as its left operand. Spliced unparenthesized,
5984    /// the ELSE branch captured the set operator, so the THEN branch lost the
5985    /// second update. Shipped instance: MobMachine's topology convergence
5986    /// removes both absent identities from `pending_respawn_topology`; the
5987    /// model removed only `a_identity` when both were absent.
5988    #[test]
5989    fn a_set_update_after_a_conditional_update_takes_the_whole_conditional() {
5990        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
5991        assert!(
5992            model.contains(
5993                "((IF ((a_identity \\in DOMAIN identity_to_runtime) = FALSE) THEN (pending_respawn_topology \\ {a_identity}) ELSE pending_respawn_topology) \\ {b_identity})"
5994            ),
5995            "the second removal must apply to the whole conditional value"
5996        );
5997        assert!(
5998            !model.contains("ELSE pending_respawn_topology \\ {b_identity}"),
5999            "no set operator may bind to one branch of a spliced conditional"
6000        );
6001    }
6002
6003    /// Every update kind that reads a field's pending value must splice it so
6004    /// no operator after it can bind into one branch of a pending conditional
6005    /// (`IF c THEN a ELSE b`, left by an earlier conditional update in the
6006    /// same block): each occurrence must close an operand, followed only by
6007    /// `)`, `,` or the end of the value. The match is exhaustive, so a new
6008    /// `Update` kind must be classified here.
6009    #[test]
6010    fn every_update_kind_splices_a_pending_conditional_as_one_operand() {
6011        use meerkat_machine_schema::identity::FieldId;
6012        const PENDING: &str = "IF c THEN a ELSE b";
6013        let field = || FieldId::parse("f").expect("field slug");
6014        let x = || Expr::Binding("x".to_owned());
6015        let samples = vec![
6016            Update::Increment {
6017                field: field(),
6018                amount: 1,
6019            },
6020            Update::Decrement {
6021                field: field(),
6022                amount: 1,
6023            },
6024            Update::MapInsert {
6025                field: field(),
6026                key: x(),
6027                value: x(),
6028            },
6029            Update::MapIncrement {
6030                field: field(),
6031                key: x(),
6032                amount: 1,
6033            },
6034            Update::MapDecrement {
6035                field: field(),
6036                key: x(),
6037                amount: 1,
6038            },
6039            Update::MapRemove {
6040                field: field(),
6041                key: x(),
6042            },
6043            Update::SetInsert {
6044                field: field(),
6045                value: x(),
6046            },
6047            Update::SetRemove {
6048                field: field(),
6049                value: x(),
6050            },
6051            Update::SeqAppend {
6052                field: field(),
6053                value: x(),
6054            },
6055            Update::SeqPrepend {
6056                field: field(),
6057                values: x(),
6058            },
6059            Update::SeqPopFront { field: field() },
6060            Update::SeqRemoveValue {
6061                field: field(),
6062                value: x(),
6063            },
6064            Update::SeqRemoveAll {
6065                field: field(),
6066                values: x(),
6067            },
6068            Update::Conditional {
6069                condition: Expr::Binding("d".to_owned()),
6070                then_updates: vec![Update::SetInsert {
6071                    field: field(),
6072                    value: x(),
6073                }],
6074                else_updates: vec![Update::SetRemove {
6075                    field: field(),
6076                    value: x(),
6077                }],
6078            },
6079            Update::ForEach {
6080                binding: "y".to_owned(),
6081                over: x(),
6082                updates: vec![Update::SetInsert {
6083                    field: field(),
6084                    value: Expr::Binding("y".to_owned()),
6085                }],
6086            },
6087        ];
6088        let schema = mob_machine();
6089        for update in &samples {
6090            // Exhaustive: classify every kind. `Assign` does not read the
6091            // field's pending value, so it cannot splice it.
6092            match update {
6093                Update::Assign { .. } => continue,
6094                Update::Increment { .. }
6095                | Update::Decrement { .. }
6096                | Update::MapInsert { .. }
6097                | Update::MapIncrement { .. }
6098                | Update::MapDecrement { .. }
6099                | Update::MapRemove { .. }
6100                | Update::SetInsert { .. }
6101                | Update::SetRemove { .. }
6102                | Update::SeqAppend { .. }
6103                | Update::SeqPrepend { .. }
6104                | Update::SeqPopFront { .. }
6105                | Update::SeqRemoveValue { .. }
6106                | Update::SeqRemoveAll { .. }
6107                | Update::Conditional { .. }
6108                | Update::ForEach { .. } => {}
6109            }
6110            let mut compiler = MachineTlaCompiler::new(&schema);
6111            let mut env = BTreeMap::from([("f".to_owned(), PENDING.to_owned())]);
6112            let binding_types =
6113                BTreeMap::from([("x".to_owned(), TypeRef::Set(Box::new(TypeRef::U64)))]);
6114            compiler.apply_update("Probe", &mut env, &BTreeMap::new(), &binding_types, update);
6115            let rendered = env.get("f").expect("the update writes f");
6116            assert!(
6117                rendered.contains(PENDING),
6118                "{update:?} must read the pending value: {rendered}"
6119            );
6120            for (at, _) in rendered.match_indices(PENDING) {
6121                let after = rendered[at + PENDING.len()..].chars().next();
6122                assert!(
6123                    matches!(after, None | Some(')' | ',')),
6124                    "{update:?} lets {after:?} bind into the pending conditional: {rendered}"
6125                );
6126            }
6127        }
6128    }
6129
6130    /// A `for` loop lowers to one fold per touched field, and each fold must
6131    /// read the other fields as they were BEFORE the loop, as the sequential
6132    /// kernel does within an iteration. Writing each fold back into the env
6133    /// while lowering handed later folds an earlier field's post-loop value:
6134    /// the causal-tail batch then looked up already-removed cursors and left
6135    /// orphaned queued rows, which the generated outbox invariant caught. So
6136    /// no fold of a loop may take another fold of the same loop as an
6137    /// argument.
6138    #[test]
6139    fn a_for_each_fold_reads_the_other_fields_before_the_loop() {
6140        let model =
6141            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
6142        let mut checked = 0;
6143        for line in model.lines() {
6144            let Some(eq) = line.find("' = ") else {
6145                continue;
6146            };
6147            let rhs = &line[eq + 4..];
6148            let Some(open) = rhs.find('(') else {
6149                continue;
6150            };
6151            let head = &rhs[..open];
6152            let Some(pos) = head.find("_ForEach") else {
6153                continue;
6154            };
6155            let digits: String = head[pos + "_ForEach".len()..]
6156                .chars()
6157                .take_while(char::is_ascii_digit)
6158                .collect();
6159            let same_loop = format!("{}_ForEach{digits}_", &head[..pos]);
6160            assert!(
6161                !rhs[open..].contains(&same_loop),
6162                "a for-loop fold takes another fold of the same loop as an argument: {line}"
6163            );
6164            checked += 1;
6165        }
6166        assert!(
6167            checked > 0,
6168            "the MeerkatMachine model has for-loop folds to check"
6169        );
6170    }
6171    use meerkat_machine_schema::RustTypeAtom;
6172    use meerkat_machine_schema::catalog::dsl::{
6173        dsl_meerkat_machine as meerkat_machine, dsl_mob_machine as mob_machine,
6174    };
6175    use meerkat_machine_schema::catalog::meerkat_mob_seam_composition;
6176    use meerkat_machine_schema::identity::{
6177        EffectVariantId, MachineId, MachineInstanceId, TransitionId,
6178    };
6179
6180    fn string_domain_values(assignment: &str) -> BTreeSet<String> {
6181        assignment
6182            .trim_start_matches('{')
6183            .trim_end_matches('}')
6184            .split(", ")
6185            .filter(|value| !value.is_empty())
6186            .map(|value| value.trim_matches('"').to_owned())
6187            .collect()
6188    }
6189
6190    fn cfg_string_domain_values(cfg: &str, domain: &str) -> BTreeSet<String> {
6191        let prefix = format!("  {domain} = ");
6192        cfg.lines()
6193            .find_map(|line| line.strip_prefix(&prefix))
6194            .map(string_domain_values)
6195            .unwrap_or_default()
6196    }
6197
6198    fn default_string_domain_values(sample_cardinality: usize) -> BTreeSet<String> {
6199        string_domain_values(&render_default_domain_assignment(
6200            &TypeRef::String,
6201            sample_cardinality,
6202            &BTreeMap::new(),
6203            &BTreeMap::new(),
6204            false,
6205        ))
6206    }
6207
6208    fn assert_session_id_string_overlap(cfg: &str, profile: &str) {
6209        let session_ids = cfg_string_domain_values(cfg, "SessionIdValues");
6210        let strings = cfg_string_domain_values(cfg, "StringValues");
6211        assert!(
6212            !session_ids.is_empty() && !strings.is_empty(),
6213            "{profile} must sample both bridged domains"
6214        );
6215        assert!(
6216            !session_ids.is_disjoint(&strings),
6217            "{profile} must make the SessionId/string equality branch satisfiable"
6218        );
6219        assert!(
6220            strings
6221                .iter()
6222                .any(|candidate| !session_ids.contains(candidate)),
6223            "{profile} must retain a non-matching string candidate for the rejection branch"
6224        );
6225    }
6226
6227    #[test]
6228    fn conjunctive_bool_specialization_is_literal_only_and_conservative() {
6229        let expr = Expr::And(vec![
6230            Expr::Binding("required_true".to_owned()),
6231            Expr::Not(Box::new(Expr::Binding("required_false".to_owned()))),
6232            Expr::Eq(
6233                Box::new(Expr::Binding("equal_true".to_owned())),
6234                Box::new(Expr::Bool(true)),
6235            ),
6236            Expr::Neq(
6237                Box::new(Expr::Bool(true)),
6238                Box::new(Expr::Binding("not_equal_true".to_owned())),
6239            ),
6240            Expr::Or(vec![
6241                Expr::Binding("under_disjunction".to_owned()),
6242                Expr::Binding("alternative".to_owned()),
6243            ]),
6244            Expr::Binding("conflicting".to_owned()),
6245            Expr::Not(Box::new(Expr::Binding("conflicting".to_owned()))),
6246        ]);
6247        let mut requirements = BTreeMap::new();
6248
6249        collect_conjunctive_bool_requirements(&expr, &mut requirements);
6250
6251        assert_eq!(requirements.get("required_true"), Some(&Some(true)));
6252        assert_eq!(requirements.get("required_false"), Some(&Some(false)));
6253        assert_eq!(requirements.get("equal_true"), Some(&Some(true)));
6254        assert_eq!(requirements.get("not_equal_true"), Some(&Some(false)));
6255        assert!(!requirements.contains_key("under_disjunction"));
6256        assert!(!requirements.contains_key("alternative"));
6257        assert_eq!(requirements.get("conflicting"), Some(&None));
6258    }
6259
6260    #[test]
6261    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6262    fn composition_semantic_model_fails_closed_on_undeclared_route_source_machine() {
6263        let mut schema = meerkat_mob_seam_composition();
6264        let route = schema
6265            .routes
6266            .first_mut()
6267            .expect("seam composition has at least one route");
6268        // Repoint the route source at an instance id that is not declared in
6269        // the composition. The CASE builder used to map this to an
6270        // `"unknown_machine"` sentinel; generation must now fail closed.
6271        route.from_machine =
6272            MachineInstanceId::parse("undeclared_source_instance").expect("valid slug");
6273
6274        let result = render_composition_semantic_model(&schema);
6275        assert!(
6276            matches!(
6277                result,
6278                Err(CompositionTlaError::UnknownRouteSourceMachine { .. })
6279            ),
6280            "expected UnknownRouteSourceMachine, got {result:?}"
6281        );
6282    }
6283
6284    #[test]
6285    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6286    fn composition_semantic_model_fails_closed_on_undeclared_route_effect() {
6287        let mut schema = meerkat_mob_seam_composition();
6288        let route = schema
6289            .routes
6290            .first_mut()
6291            .expect("seam composition has at least one route");
6292        // Keep the (declared) source machine but reference an effect variant
6293        // that the source machine does not declare.
6294        route.effect_variant =
6295            EffectVariantId::parse("UndeclaredEffectVariant").expect("valid slug");
6296
6297        let result = render_composition_semantic_model(&schema);
6298        assert!(
6299            matches!(result, Err(CompositionTlaError::UnknownRouteEffect { .. })),
6300            "expected UnknownRouteEffect, got {result:?}"
6301        );
6302    }
6303
6304    #[test]
6305    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6306    fn composition_semantic_model_fails_closed_on_undeclared_witness_transition() {
6307        let mut schema = meerkat_mob_seam_composition();
6308        schema
6309            .witnesses
6310            .first_mut()
6311            .expect("seam composition has at least one witness")
6312            .expected_transitions
6313            .first_mut()
6314            .expect("seam witness has at least one expected transition")
6315            .transition = TransitionId::parse("UndeclaredWitnessTransition").expect("valid slug");
6316
6317        let result = render_composition_semantic_model(&schema);
6318        assert!(
6319            matches!(
6320                result,
6321                Err(CompositionTlaError::UnknownWitnessTransition { .. })
6322            ),
6323            "expected UnknownWitnessTransition, got {result:?}"
6324        );
6325    }
6326
6327    #[test]
6328    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6329    fn composition_semantic_model_renders_for_valid_schema() {
6330        // Sanity: the fail-closed gate does not reject a currently-valid
6331        // composition. (Byte-identity of the output is enforced separately by
6332        // `make machine-check-drift`.)
6333        let schema = meerkat_mob_seam_composition();
6334        let result = render_composition_semantic_model(&schema);
6335        assert!(
6336            result.is_ok(),
6337            "valid composition should render: {result:?}"
6338        );
6339    }
6340
6341    #[test]
6342    #[should_panic(
6343        expected = "composition named-type `AgentRuntimeId` binding must agree across machine schemas"
6344    )]
6345    fn composition_named_binding_merge_rejects_divergent_domain_shapes() {
6346        let mut meerkat = meerkat_machine();
6347        meerkat.machine = MachineId::parse("CompositionMergeLeft").expect("test machine id");
6348        let mut mob = mob_machine();
6349        mob.machine = MachineId::parse("CompositionMergeRight").expect("test machine id");
6350        let binding = mob
6351            .named_types
6352            .iter_mut()
6353            .find(|binding| binding.name.as_str() == "AgentRuntimeId")
6354            .expect("MobMachine AgentRuntimeId binding");
6355        binding.rust = RustTypeAtom::U64;
6356
6357        let _ = collect_composition_named_bindings([&meerkat, &mob]);
6358    }
6359
6360    #[test]
6361    fn composition_named_binding_merge_allows_machine_local_type_path_twins() {
6362        let meerkat = meerkat_machine();
6363        let mob = mob_machine();
6364
6365        let bindings = collect_composition_named_bindings([&meerkat, &mob]);
6366
6367        assert!(
6368            matches!(
6369                bindings.get("PeerAddress"),
6370                Some(RustTypeAtom::TypePath(path))
6371                    if path == "crate::catalog::dsl::meerkat_machine::PeerAddress"
6372            ),
6373            "path-only TypePath twins should not block composition-domain binding merge"
6374        );
6375    }
6376
6377    #[test]
6378    fn mob_generation_native_helper_declares_and_assigns_u64_boundary() {
6379        let schema = mob_machine();
6380        assert!(machine_uses_u64_max(&schema));
6381
6382        let model = render_machine_semantic_model(&schema).expect("render MobMachine model");
6383        let constants_line = model
6384            .lines()
6385            .find(|line| line.starts_with("CONSTANTS "))
6386            .expect("MobMachine model constants");
6387        assert!(constants_line.contains(TLA_RUST_U64_MAX_CONSTANT));
6388
6389        for deep in [false, true] {
6390            let cfg = render_machine_ci_cfg(&schema, deep).expect("valid machine CFG");
6391            assert!(
6392                cfg.contains(&format!(
6393                    "  {TLA_RUST_U64_MAX_CONSTANT} = {TLC_SAFE_RUST_U64_MAX_VALUE}"
6394                )),
6395                "{} config must assign the boundary",
6396                if deep { "deep" } else { "ci" }
6397            );
6398        }
6399    }
6400
6401    #[test]
6402    fn meerkat_deep_cfg_samples_the_native_session_id_string_bridge() {
6403        let schema = meerkat_machine();
6404        assert!(machine_uses_session_id_string_bridge(&schema));
6405
6406        let deep_cfg = render_machine_ci_cfg(&schema, true).expect("valid deep CFG");
6407        assert_session_id_string_overlap(&deep_cfg, "MeerkatMachine Deep config");
6408        assert_eq!(
6409            cfg_string_domain_values(&deep_cfg, "StringValues").len(),
6410            default_string_domain_values(default_sample_cardinality(true)).len(),
6411            "bridge reachability must substitute a Deep string sample, not add one"
6412        );
6413
6414        let ci_cfg = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
6415        assert!(
6416            cfg_string_domain_values(&ci_cfg, "SessionIdValues").is_empty()
6417                && cfg_string_domain_values(&ci_cfg, "StringValues").is_empty(),
6418            "the step-limit-one CI profile must remain uninflated"
6419        );
6420    }
6421
6422    #[test]
6423    fn mob_deep_cfg_does_not_inflate_unrelated_string_domains() {
6424        let schema = mob_machine();
6425        assert!(!machine_uses_session_id_string_bridge(&schema));
6426
6427        let deep_cfg = render_machine_ci_cfg(&schema, true).expect("valid deep CFG");
6428        let session_ids = cfg_string_domain_values(&deep_cfg, "SessionIdValues");
6429        let strings = cfg_string_domain_values(&deep_cfg, "StringValues");
6430        assert!(
6431            session_ids.is_disjoint(&strings),
6432            "a machine without the native bridge must retain independent domains"
6433        );
6434    }
6435
6436    #[test]
6437    fn mob_identity_classifier_uses_a_typed_tlc_lifecycle_representative() {
6438        let schema = mob_machine();
6439        assert_eq!(
6440            schema
6441                .tlc_representative_inputs
6442                .iter()
6443                .map(|input| input.as_str())
6444                .collect::<Vec<_>>(),
6445            vec!["ClassifyIdentityReconciliation"],
6446            "the schema must explicitly own the TLC-only classifier abstraction"
6447        );
6448
6449        let model = render_machine_semantic_model(&schema).expect("render MobMachine model");
6450        assert!(
6451            model.contains(
6452                "TlcRepresentativeDomain(values) == IF values = {} THEN {} ELSE {CHOOSE value \\in values : TRUE}"
6453            ),
6454            "the representative domain must remain typed and nonempty-aware"
6455        );
6456        assert!(
6457            model.contains(
6458                "\\E intent \\in TlcRepresentativeDomain(IdentityAuthorityConditionValues) : \\E lease \\in TlcRepresentativeDomain(IdentityLeaseConditionValues)"
6459            ),
6460            "MobMachine lifecycle Next must sample one typed identity-classifier tuple"
6461        );
6462        assert!(
6463            !model.contains(
6464                "\\E intent \\in IdentityAuthorityConditionValues : \\E lease \\in IdentityLeaseConditionValues : \\E external_binding_required \\in BOOLEAN"
6465            ),
6466            "MobMachine lifecycle Next must not reintroduce the exhaustive classifier cartesian product"
6467        );
6468
6469        let composition = render_composition_semantic_model(&meerkat_mob_seam_composition())
6470            .expect("render Meerkat/Mob composition");
6471        assert!(
6472            composition.contains(
6473                "\\E arg_intent \\in TlcRepresentativeDomain(IdentityAuthorityConditionValues) : \\E arg_lease \\in TlcRepresentativeDomain(IdentityLeaseConditionValues)"
6474            ),
6475            "composition lifecycle exploration must honor the same schema-owned abstraction"
6476        );
6477    }
6478
6479    #[test]
6480    fn meerkat_mob_composition_deep_cfg_samples_the_included_native_bridge() {
6481        let schema = meerkat_mob_seam_composition();
6482        let deep_cfg = render_composition_ci_cfg(&schema, true);
6483
6484        assert_session_id_string_overlap(&deep_cfg, "Meerkat/Mob composition Deep config");
6485        let string_cardinality = schema
6486            .deep_domain_overrides
6487            .get("StringValues")
6488            .copied()
6489            .unwrap_or(schema.deep_domain_cardinality);
6490        assert_eq!(
6491            cfg_string_domain_values(&deep_cfg, "StringValues").len(),
6492            default_string_domain_values(string_cardinality).len(),
6493            "composition bridge reachability must substitute a string sample, not add one"
6494        );
6495
6496        let ci_cfg = render_composition_ci_cfg(&schema, false);
6497        assert!(
6498            cfg_string_domain_values(&ci_cfg, "SessionIdValues")
6499                .is_disjoint(&cfg_string_domain_values(&ci_cfg, "StringValues")),
6500            "the composition CI profile must remain unchanged"
6501        );
6502    }
6503
6504    #[test]
6505    fn runtime_delivery_recipient_insert_has_identical_local_map_semantics_in_tla() {
6506        let schema = meerkat_machine_schema::catalog::dsl::dsl_runtime_delivery_machine();
6507        let model = render_machine_semantic_model(&schema).expect("render recipient model");
6508        let definition = "runtime_delivery_recipient_outcomes_after_set(current, recipient, outcome) ==\n    MapSet(current, recipient, outcome)\n";
6509        assert!(model.contains(definition));
6510        assert!(
6511            model
6512                .matches("runtime_delivery_recipient_outcomes_after_set(")
6513                .count()
6514                > 1,
6515            "the generated settlement must call the formally defined insert"
6516        );
6517        let composition = render_composition_semantic_model(
6518            &meerkat_machine_schema::catalog::job_runtime_delivery_composition(),
6519        )
6520        .expect("render embedded recipient model");
6521        assert!(
6522            composition.contains(&format!("runtime_delivery__{definition}")),
6523            "embedded delivery machines require their scoped helper definition too"
6524        );
6525    }
6526
6527    #[test]
6528    fn session_document_instruction_natives_have_the_rust_semantics_in_tla() {
6529        // The DSL authority, the kernel oracle and the Core mirror give these
6530        // natives one meaning, pinned here as the generated TLA renders it:
6531        // a slot map with one slot set (insert or replace), the body bytes of
6532        // a slot set's Active slots (a slot the bytes map does not name
6533        // counts nothing), and the entries of a slot map whose slot is
6534        // Active.
6535        let schema = meerkat_machine_schema::catalog::dsl::dsl_session_document_machine();
6536        let model = render_machine_semantic_model(&schema).expect("render model");
6537        let slot_after_set = r"session_document_instruction_slot_after_set(current, slot, value) ==
6538    MapSet(current, slot, value)
6539";
6540        let active_bytes = r#"session_document_instruction_active_bytes(slot_effect, slot_bytes) ==
6541    LET RECURSIVE SessionDocumentInstructionActiveBytesOver(_)
6542        SessionDocumentInstructionActiveBytesOver(instruction_slots) ==
6543            IF instruction_slots = {} THEN 0
6544            ELSE LET instruction_slot == CHOOSE candidate_slot \in instruction_slots : TRUE
6545                 IN (IF slot_effect[instruction_slot] = "Active" /\ instruction_slot \in DOMAIN slot_bytes
6546                     THEN slot_bytes[instruction_slot] ELSE 0)
6547                    + SessionDocumentInstructionActiveBytesOver(instruction_slots \ {instruction_slot})
6548    IN SessionDocumentInstructionActiveBytesOver(DOMAIN slot_effect)
6549"#;
6550        let active_slots = r#"session_document_instruction_active_slots(slot_effect, slot_values) ==
6551    [instruction_slot \in {candidate_slot \in DOMAIN slot_values :
6552            candidate_slot \in DOMAIN slot_effect /\ slot_effect[candidate_slot] = "Active"}
6553        |-> slot_values[instruction_slot]]
6554"#;
6555        let retired_after = r"session_document_activation_retired_after(activation_rows, activation_retired) ==
6556    [activation_key \in DOMAIN activation_rows |->
6557        LET retired_count == IF activation_key \in DOMAIN activation_retired THEN activation_retired[activation_key] ELSE 0
6558            superseded_count == IF activation_rows[activation_key] > 0 THEN activation_rows[activation_key] - 1 ELSE 0
6559        IN IF retired_count >= superseded_count THEN retired_count ELSE superseded_count]
6560";
6561        for (native, definition) in [
6562            (
6563                "session_document_instruction_slot_after_set",
6564                slot_after_set,
6565            ),
6566            ("session_document_instruction_active_bytes", active_bytes),
6567            ("session_document_instruction_active_slots", active_slots),
6568            ("session_document_activation_retired_after", retired_after),
6569        ] {
6570            assert!(
6571                model.contains(definition),
6572                "the generated model must define {native} with its Rust semantics"
6573            );
6574            assert!(
6575                model.matches(&format!("{native}(")).count() > 1,
6576                "the generated arms must call the formally defined {native}"
6577            );
6578        }
6579    }
6580
6581    #[test]
6582    fn mob_machine_instruction_snapshot_natives_have_the_rust_semantics_in_tla() {
6583        // The DSL authority, the kernel oracle and the generated TLA give
6584        // the operator-instruction natives one meaning: the widest member
6585        // snapshot the records allow, the shared records (every slot that
6586        // is not member-targeted) plus the most one name holds of its own,
6587        // alone or with what another name's records pass to its forks, in
6588        // records and in Active body bytes; and, with a write applied, the
6589        // widest snapshot of the maps the write leaves.
6590        let schema = meerkat_machine_schema::catalog::dsl::dsl_mob_machine();
6591        let model = render_machine_semantic_model(&schema).expect("render model");
6592        let widest_slots = r#"mob_machine_instruction_widest_snapshot_slots(target_kind, target_member) ==
6593    LET member_slots == {candidate_slot \in DOMAIN target_kind : target_kind[candidate_slot] \in {"Member", "MemberAndForks"} /\ candidate_slot \in DOMAIN target_member}
6594        instruction_fork_slots == {candidate_slot \in member_slots : target_kind[candidate_slot] = "MemberAndForks"}
6595        instruction_member_names == {target_member[named_slot] : named_slot \in member_slots}
6596        InstructionOwnOf(named_member) == Cardinality({own_slot \in member_slots : target_member[own_slot] = named_member})
6597        InstructionForForksOf(named_member) == Cardinality({own_slot \in instruction_fork_slots : target_member[own_slot] = named_member})
6598        instruction_snapshots == {InstructionOwnOf(named_member) : named_member \in instruction_member_names} \cup {InstructionOwnOf(name_pair[1]) + InstructionForForksOf(name_pair[2]) : name_pair \in {candidate_pair \in instruction_member_names \X instruction_member_names : candidate_pair[1] # candidate_pair[2]}}
6599        widest_own == IF instruction_snapshots = {} THEN 0 ELSE CHOOSE snapshot_size \in instruction_snapshots : \A other_size \in instruction_snapshots : snapshot_size >= other_size
6600    IN Cardinality(DOMAIN target_kind \ member_slots) + widest_own
6601"#;
6602        let widest_bytes = r#"mob_machine_instruction_widest_snapshot_active_bytes(slot_effect, slot_bytes, target_kind, target_member) ==
6603    LET member_slots == {candidate_slot \in DOMAIN slot_effect : candidate_slot \in DOMAIN target_kind /\ target_kind[candidate_slot] \in {"Member", "MemberAndForks"} /\ candidate_slot \in DOMAIN target_member}
6604        instruction_fork_slots == {candidate_slot \in member_slots : target_kind[candidate_slot] = "MemberAndForks"}
6605        instruction_member_names == {target_member[named_slot] : named_slot \in member_slots}
6606        ActiveBytesOf(instruction_slots) == session_document_instruction_active_bytes([instruction_slot \in instruction_slots |-> slot_effect[instruction_slot]], slot_bytes)
6607        InstructionOwnOf(named_member) == ActiveBytesOf({own_slot \in member_slots : target_member[own_slot] = named_member})
6608        InstructionForForksOf(named_member) == ActiveBytesOf({own_slot \in instruction_fork_slots : target_member[own_slot] = named_member})
6609        instruction_snapshots == {InstructionOwnOf(named_member) : named_member \in instruction_member_names} \cup {InstructionOwnOf(name_pair[1]) + InstructionForForksOf(name_pair[2]) : name_pair \in {candidate_pair \in instruction_member_names \X instruction_member_names : candidate_pair[1] # candidate_pair[2]}}
6610        widest_own == IF instruction_snapshots = {} THEN 0 ELSE CHOOSE snapshot_size \in instruction_snapshots : \A other_size \in instruction_snapshots : snapshot_size >= other_size
6611    IN ActiveBytesOf(DOMAIN slot_effect \ member_slots) + widest_own
6612"#;
6613        let write_slots = r"mob_machine_instruction_write_snapshot_slots(target_kind, target_member, slot, kind, member) ==
6614    LET kind_after == MapSet(target_kind, slot, kind)
6615        member_after == IF member = None THEN [other_slot \in DOMAIN target_member \ {slot} |-> target_member[other_slot]] ELSE MapSet(target_member, slot, member.value)
6616    IN mob_machine_instruction_widest_snapshot_slots(kind_after, member_after)
6617";
6618        let write_bytes = r#"mob_machine_instruction_write_snapshot_active_bytes(slot_effect, slot_bytes, target_kind, target_member, slot, body_bytes, kind, member) ==
6619    LET effect_after == MapSet(slot_effect, slot, "Active")
6620        bytes_after == MapSet(slot_bytes, slot, body_bytes)
6621        kind_after == MapSet(target_kind, slot, kind)
6622        member_after == IF member = None THEN [other_slot \in DOMAIN target_member \ {slot} |-> target_member[other_slot]] ELSE MapSet(target_member, slot, member.value)
6623    IN mob_machine_instruction_widest_snapshot_active_bytes(effect_after, bytes_after, kind_after, member_after)
6624"#;
6625
6626        for (native, definition) in [
6627            (
6628                "mob_machine_instruction_widest_snapshot_slots",
6629                widest_slots,
6630            ),
6631            (
6632                "mob_machine_instruction_widest_snapshot_active_bytes",
6633                widest_bytes,
6634            ),
6635            ("mob_machine_instruction_write_snapshot_slots", write_slots),
6636            (
6637                "mob_machine_instruction_write_snapshot_active_bytes",
6638                write_bytes,
6639            ),
6640        ] {
6641            assert!(
6642                model.contains(definition),
6643                "the generated model must define {native} with its Rust semantics"
6644            );
6645            assert!(
6646                model.matches(&format!("{native}(")).count() > 1,
6647                "the generated arms must call the formally defined {native}"
6648            );
6649        }
6650    }
6651
6652    #[test]
6653    fn meerkat_session_id_native_helper_matches_typed_option_contract() {
6654        let model =
6655            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
6656        let expected = r"meerkat_machine_session_id_matches_string(current, candidate) ==
6657    current # None /\ current.value = candidate
6658";
6659
6660        assert!(
6661            model.contains(expected),
6662            "MeerkatMachine TLA session identity operator must preserve the Rust typed-option/string comparison contract"
6663        );
6664    }
6665
6666    #[test]
6667    fn mob_placed_native_helpers_are_defined_in_the_tla_model() {
6668        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6669
6670        for operator in [
6671            "mob_machine_finalized_placed_kickoff_recovery_well_formed(",
6672            "mob_machine_placed_completion_obligation_well_formed(",
6673            "mob_machine_placed_completion_custody_admits(",
6674            "mob_machine_adaptive_lifecycle_drained(",
6675            "mob_machine_adaptive_run_custody_drained(",
6676            "mob_machine_placed_kickoff_obligation_well_formed(",
6677            "mob_machine_placed_kickoff_correlation_available(",
6678            "mob_machine_placed_kickoff_custody_absent_for_identity(",
6679            "mob_machine_placed_kickoff_custody_absent_for_host(",
6680            "mob_machine_remote_turn_input_id_available_to_kickoff(",
6681            "mob_machine_placed_carrier_binding_active(",
6682            "mob_machine_placed_carrier_binding_confirmed_revoked(",
6683            "mob_machine_host_binding_generation_tombstone(",
6684        ] {
6685            assert!(
6686                model
6687                    .lines()
6688                    .any(|line| line.starts_with(operator) && line.ends_with(" ==")),
6689                "MobMachine TLA model must define native operator {operator}"
6690            );
6691        }
6692    }
6693
6694    #[test]
6695    fn mob_placed_kickoff_correlation_tla_helper_covers_every_shared_input_namespace() {
6696        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6697        let expected = r"mob_machine_placed_kickoff_correlation_available(pending_kickoffs, resolved_kickoffs, retained_kickoffs, pending_turns, committed_turns, resolved_turns, pending_completions, resolved_completions, candidate) ==
6698    /\ \A row \in pending_kickoffs \cup resolved_kickoffs : /\ row.agent_identity # candidate.agent_identity /\ \lnot (/\ row.host_id = candidate.host_id /\ row.generation = candidate.generation /\ row.fence_token = candidate.fence_token /\ row.input_id = candidate.input_id)
6699    /\ \A identity \in DOMAIN retained_kickoffs : retained_kickoffs[identity].agent_identity # candidate.agent_identity
6700    /\ \A row \in pending_turns \cup committed_turns \cup resolved_turns : \lnot (/\ row.agent_identity = candidate.agent_identity /\ row.host_id = candidate.host_id /\ row.generation = candidate.generation /\ row.fence_token = candidate.fence_token /\ row.input_id = candidate.input_id)
6701    /\ \A row \in pending_completions \cup resolved_completions : \lnot (/\ row.agent_identity = candidate.agent_identity /\ row.host_id = candidate.host_id /\ row.generation = candidate.generation /\ row.fence_token = candidate.fence_token /\ row.input_id = candidate.input_id)
6702";
6703
6704        assert!(
6705            model.contains(expected),
6706            "MobMachine TLA kickoff-correlation helper must reject collisions across kickoff, remote-turn, and placed-completion custody"
6707        );
6708    }
6709
6710    #[test]
6711    fn mob_placed_kickoff_recovery_tla_helper_does_not_shadow_machine_phase() {
6712        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6713        assert!(
6714            model.contains(
6715                r#"Cardinality({ kickoff_phase \in {"Started", "CallbackPending", "Failed", "Cancelled"} :"#
6716            ),
6717            "kickoff recovery helper must bind a helper-local identifier"
6718        );
6719        assert!(
6720            !model.contains(
6721                r#"Cardinality({ phase \in {"Started", "CallbackPending", "Failed", "Cancelled"} :"#
6722            ),
6723            "TLA forbids the helper-local binder from shadowing the machine's phase variable"
6724        );
6725    }
6726
6727    #[test]
6728    fn mob_adaptive_run_custody_native_helper_matches_rust_contract() {
6729        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6730        let expected = r#"mob_machine_adaptive_run_custody_drained(adaptive_run_id, active_layer, active_members, layer_run, layer_phases, layer_dispositions) ==
6731    /\ adaptive_run_id \notin DOMAIN active_layer
6732    /\ (IF adaptive_run_id \in DOMAIN active_members THEN active_members[adaptive_run_id] ELSE 0) = 0
6733    /\ \A layer_id \in DOMAIN layer_run :
6734           \/ layer_run[layer_id] # adaptive_run_id
6735           \/ /\ layer_id \in DOMAIN layer_dispositions
6736              /\ layer_id \in DOMAIN layer_phases
6737              /\ layer_phases[layer_id] \in {"Completed", "SetupFailed", "RunFailed", "ResultInvalid", "Canceled"}
6738"#;
6739
6740        assert!(
6741            model.contains(expected),
6742            "MobMachine TLA adaptive-run custody operator must preserve the Rust absence, zero-active-member, and terminal-layer contract"
6743        );
6744    }
6745
6746    /// Every conjunct of the option-order ASSUME table states what Rust's
6747    /// `Option` order computes, so a TLC run that accepts the ASSUMEs proves
6748    /// `OptionLt` / `OptionLe` right. The table covers both operators over
6749    /// None/None, None/Some, Some/None and Some/Some below, equal and above.
6750    #[test]
6751    #[allow(clippy::panic)]
6752    fn the_option_order_assume_table_is_rusts_option_order() {
6753        use std::cmp::Ordering;
6754
6755        fn operand(text: &str) -> Option<u64> {
6756            if text == "None" {
6757                return None;
6758            }
6759            let value = text
6760                .strip_prefix("Some(")
6761                .and_then(|rest| rest.strip_suffix(')'))
6762                .unwrap_or_else(|| panic!("unexpected operand {text}"));
6763            Some(
6764                value
6765                    .parse()
6766                    .unwrap_or_else(|_| panic!("unexpected operand {text}")),
6767            )
6768        }
6769
6770        // TLC evaluates every disjunct of an action-level `\/`, so a `\/` in
6771        // either definition would read a `None` record's `value` inside a
6772        // guard; the ASSUMEs alone cannot see that.
6773        for line in TLA_OPTION_ORDER_DEFINITIONS
6774            .lines()
6775            .filter(|line| line.starts_with("OptionL"))
6776        {
6777            assert!(!line.contains("\\/"), "{line} branches with a disjunction");
6778        }
6779
6780        let mut covered = BTreeSet::new();
6781        for line in TLA_OPTION_ORDER_DEFINITIONS.lines() {
6782            let Some(table) = line.strip_prefix("ASSUME ") else {
6783                continue;
6784            };
6785            for conjunct in table.split(" /\\ ") {
6786                let (expected, call) = match conjunct.strip_prefix('~') {
6787                    Some(call) => (false, call),
6788                    None => (true, conjunct),
6789                };
6790                let (operator, operands) = call.split_once('(').expect("an operator call");
6791                let (left, right) = operands
6792                    .strip_suffix(')')
6793                    .and_then(|operands| operands.split_once(", "))
6794                    .expect("two operands");
6795                let (left, right) = (operand(left), operand(right));
6796                let rust = match operator {
6797                    "OptionLt" => left < right,
6798                    "OptionLe" => left <= right,
6799                    other => panic!("unexpected operator {other}"),
6800                };
6801                assert_eq!(
6802                    expected, rust,
6803                    "{conjunct} disagrees with Rust's Option order"
6804                );
6805                covered.insert((operator, left.is_some(), right.is_some(), left.cmp(&right)));
6806            }
6807        }
6808        for operator in ["OptionLt", "OptionLe"] {
6809            for case in [
6810                (false, false, Ordering::Equal),
6811                (false, true, Ordering::Less),
6812                (true, false, Ordering::Greater),
6813                (true, true, Ordering::Less),
6814                (true, true, Ordering::Equal),
6815                (true, true, Ordering::Greater),
6816            ] {
6817                assert!(
6818                    covered.contains(&(operator, case.0, case.1, case.2)),
6819                    "the ASSUME table misses {operator} over {case:?}"
6820                );
6821            }
6822        }
6823    }
6824
6825    /// An ordering comparison with an option operand renders through
6826    /// `OptionLt` / `OptionLe` (`>` and `>=` with the operands swapped) for
6827    /// every way an operand is an option, on either side; a plain ordering
6828    /// keeps its TLA+ operator and leaves the module without the definitions.
6829    #[test]
6830    fn an_ordering_with_an_option_operand_renders_in_rusts_option_order() {
6831        let mut schema = mob_machine();
6832        schema.helpers.push(HelperSchema {
6833            name: "maybe_epoch".into(),
6834            params: Vec::new(),
6835            returns: TypeRef::Option(Box::new(TypeRef::U64)),
6836            body: Expr::None,
6837        });
6838        let field = |name: &str| {
6839            Box::new(Expr::Field(
6840                meerkat_machine_schema::identity::FieldId::parse(name).expect("field id"),
6841            ))
6842        };
6843        let binding = |name: &str| Box::new(Expr::Binding(name.to_owned()));
6844        let binding_types = BTreeMap::from([
6845            ("agent_identity".to_owned(), TypeRef::String),
6846            ("maybe".to_owned(), TypeRef::Option(Box::new(TypeRef::U64))),
6847            ("n".to_owned(), TypeRef::U64),
6848            ("run_id".to_owned(), TypeRef::String),
6849        ]);
6850        let options = [
6851            ("a None literal", Expr::None),
6852            ("a Some literal", Expr::Some(Box::new(Expr::U64(3)))),
6853            ("an option binding", Expr::Binding("maybe".to_owned())),
6854            ("an option field", *field("supervisor_authority_epoch")),
6855            (
6856                "the get_copied lowering",
6857                Expr::IfElse {
6858                    condition: Box::new(Expr::MapContainsKey {
6859                        map: field("member_last_observed_at_ms"),
6860                        key: binding("agent_identity"),
6861                    }),
6862                    then_expr: Box::new(Expr::Some(Box::new(Expr::MapGet {
6863                        map: field("member_last_observed_at_ms"),
6864                        key: binding("agent_identity"),
6865                    }))),
6866                    else_expr: Box::new(Expr::None),
6867                },
6868            ),
6869            (
6870                "a read of a map with option values",
6871                Expr::MapGet {
6872                    map: field("run_last_granted_frame"),
6873                    key: binding("run_id"),
6874                },
6875            ),
6876            (
6877                "a helper returning an option",
6878                Expr::Call {
6879                    helper: "maybe_epoch".to_owned(),
6880                    args: Vec::new(),
6881                },
6882            ),
6883        ];
6884        let other = Expr::Some(binding("n"));
6885        for (shape, option) in &options {
6886            let compiler = MachineTlaCompiler::new(&schema);
6887            let render = |expr: &Expr| {
6888                compiler.render_expr_with_types(
6889                    expr,
6890                    &BTreeMap::new(),
6891                    &BTreeMap::new(),
6892                    &binding_types,
6893                )
6894            };
6895            let (a, b) = (render(option), render(&other));
6896            let pair = || (Box::new(option.clone()), Box::new(other.clone()));
6897            let swapped = || (Box::new(other.clone()), Box::new(option.clone()));
6898            for (expr, expected) in [
6899                (Expr::Lt(pair().0, pair().1), format!("OptionLt({a}, {b})")),
6900                (Expr::Lte(pair().0, pair().1), format!("OptionLe({a}, {b})")),
6901                (Expr::Gt(pair().0, pair().1), format!("OptionLt({b}, {a})")),
6902                (Expr::Gte(pair().0, pair().1), format!("OptionLe({b}, {a})")),
6903                (
6904                    Expr::Lt(swapped().0, swapped().1),
6905                    format!("OptionLt({b}, {a})"),
6906                ),
6907                (
6908                    Expr::Gte(swapped().0, swapped().1),
6909                    format!("OptionLe({a}, {b})"),
6910                ),
6911            ] {
6912                assert_eq!(render(&expr), expected, "{shape}: {expr:?}");
6913            }
6914            assert!(compiler.option_order_used.get(), "{shape} marks the module");
6915        }
6916
6917        let compiler = MachineTlaCompiler::new(&schema);
6918        let render = |expr: Expr| {
6919            compiler.render_expr_with_types(
6920                &expr,
6921                &BTreeMap::new(),
6922                &BTreeMap::new(),
6923                &binding_types,
6924            )
6925        };
6926        let one = || Box::new(Expr::U64(1));
6927        assert_eq!(render(Expr::Lt(binding("n"), one())), "(n < 1)");
6928        assert_eq!(render(Expr::Lte(binding("n"), one())), "(n <= 1)");
6929        assert_eq!(render(Expr::Gt(binding("n"), one())), "(n > 1)");
6930        assert_eq!(render(Expr::Gte(binding("n"), one())), "(n >= 1)");
6931        assert!(
6932            !compiler.option_order_used.get(),
6933            "a plain ordering needs no option-order definitions"
6934        );
6935    }
6936
6937    /// A machine or composition module defines `OptionLt` / `OptionLe` if
6938    /// and only if it calls them, so the definitions land only beside an
6939    /// option ordering.
6940    #[test]
6941    fn a_module_defines_the_option_order_operators_iff_it_calls_them() {
6942        let calls_operators = |module: &str, model: &str| {
6943            let defined = model.matches(TLA_OPTION_ORDER_DEFINITIONS).count();
6944            assert!(
6945                defined <= 1,
6946                "{module} defines the operators {defined} times"
6947            );
6948            let body = model.replacen(TLA_OPTION_ORDER_DEFINITIONS, "", 1);
6949            let called = body.contains("OptionLt(") || body.contains("OptionLe(");
6950            assert_eq!(
6951                defined == 1,
6952                called,
6953                "{module}: defined {defined} time(s), called: {called}"
6954            );
6955            called
6956        };
6957        let mut callers = Vec::new();
6958        for machine in canonical_machine_schemas() {
6959            let model = render_machine_semantic_model(&machine).expect("render machine model");
6960            if calls_operators(machine.machine.as_str(), &model) {
6961                callers.push(machine.machine.as_str().to_owned());
6962            }
6963        }
6964        for composition in meerkat_machine_schema::canonical_composition_schemas() {
6965            // meerkat_mob_seam takes about 45 s to render. Its MobMachine part
6966            // goes through the same per-instance compilers as
6967            // adaptive_mob_bundle's two MobMachine instances below, and
6968            // machine-check-drift holds its regenerated model.
6969            if composition.name.as_str() == "meerkat_mob_seam" {
6970                continue;
6971            }
6972            let model =
6973                render_composition_semantic_model(&composition).expect("render composition model");
6974            if calls_operators(composition.name.as_str(), &model) {
6975                callers.push(composition.name.as_str().to_owned());
6976            }
6977        }
6978        for caller in ["MobMachine", "adaptive_mob_bundle"] {
6979            assert!(
6980                callers.iter().any(|candidate| candidate == caller),
6981                "{caller} orders options (MobMachine's member progress guards): {callers:?}"
6982            );
6983        }
6984    }
6985
6986    /// The option-ordering contract: every ordering comparison in a
6987    /// canonical machine whose operand is option-shaped renders through
6988    /// `OptionLt` / `OptionLe`, never as a plain comparison TLC cannot
6989    /// evaluate. The walk decides "option-shaped" from the schema's declared
6990    /// types (state fields, trigger bindings, helper parameters and returns,
6991    /// map value types, `Some` / `None` literals), independently of the
6992    /// renderer's own inference, so a new guard cannot bring the class back
6993    /// through a shape the renderer misses.
6994    #[test]
6995    fn every_canonical_option_ordering_renders_in_rusts_option_order() {
6996        struct Walk<'a> {
6997            schema: &'a MachineSchema,
6998            compiler: MachineTlaCompiler<'a>,
6999            checked: usize,
7000            plain: Vec<String>,
7001        }
7002
7003        impl Walk<'_> {
7004            fn declared<'t>(
7005                &'t self,
7006                expr: &Expr,
7007                bindings: &'t BTreeMap<String, TypeRef>,
7008            ) -> Option<&'t TypeRef> {
7009                match expr {
7010                    Expr::Field(field) => self
7011                        .schema
7012                        .state
7013                        .fields
7014                        .iter()
7015                        .find(|candidate| candidate.name == *field)
7016                        .map(|candidate| &candidate.ty),
7017                    Expr::Binding(name) => bindings.get(name),
7018                    Expr::Call { helper, .. } => self
7019                        .schema
7020                        .helpers
7021                        .iter()
7022                        .chain(self.schema.derived.iter())
7023                        .find(|candidate| candidate.name == *helper)
7024                        .map(|candidate| &candidate.returns),
7025                    Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
7026                        match self.declared(map, bindings)? {
7027                            TypeRef::Map(_, value) => Some(value.as_ref()),
7028                            _ => None,
7029                        }
7030                    }
7031                    _ => None,
7032                }
7033            }
7034
7035            fn option_shaped(&self, expr: &Expr, bindings: &BTreeMap<String, TypeRef>) -> bool {
7036                match expr {
7037                    Expr::Some(_) | Expr::None => true,
7038                    Expr::IfElse {
7039                        then_expr,
7040                        else_expr,
7041                        ..
7042                    } => {
7043                        self.option_shaped(then_expr, bindings)
7044                            || self.option_shaped(else_expr, bindings)
7045                    }
7046                    other => matches!(self.declared(other, bindings), Some(TypeRef::Option(_))),
7047                }
7048            }
7049
7050            fn walk(&mut self, site: &str, expr: &Expr, bindings: &BTreeMap<String, TypeRef>) {
7051                match expr {
7052                    Expr::Lt(left, right)
7053                    | Expr::Lte(left, right)
7054                    | Expr::Gt(left, right)
7055                    | Expr::Gte(left, right) => {
7056                        if self.option_shaped(left, bindings) || self.option_shaped(right, bindings)
7057                        {
7058                            self.checked += 1;
7059                            let rendered = self.compiler.render_expr_with_types(
7060                                expr,
7061                                &BTreeMap::new(),
7062                                &BTreeMap::new(),
7063                                bindings,
7064                            );
7065                            if !rendered.starts_with("OptionLt(")
7066                                && !rendered.starts_with("OptionLe(")
7067                            {
7068                                self.plain
7069                                    .push(format!("{} {site}: {rendered}", self.schema.machine));
7070                            }
7071                        }
7072                        self.walk(site, left, bindings);
7073                        self.walk(site, right, bindings);
7074                    }
7075                    Expr::Bool(_)
7076                    | Expr::U64(_)
7077                    | Expr::U64Max
7078                    | Expr::String(_)
7079                    | Expr::NamedVariant { .. }
7080                    | Expr::EmptySet
7081                    | Expr::EmptyMap
7082                    | Expr::CurrentPhase
7083                    | Expr::Phase(_)
7084                    | Expr::Field(_)
7085                    | Expr::Binding(_)
7086                    | Expr::Variant(_)
7087                    | Expr::None => {}
7088                    Expr::FieldAccess { base, .. } => self.walk(site, base, bindings),
7089                    Expr::EnumVariantIs { value, .. }
7090                    | Expr::EnumStringSetPayload { value, .. } => self.walk(site, value, bindings),
7091                    Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
7092                        for item in items {
7093                            self.walk(site, item, bindings);
7094                        }
7095                    }
7096                    Expr::IfElse {
7097                        condition,
7098                        then_expr,
7099                        else_expr,
7100                    } => {
7101                        self.walk(site, condition, bindings);
7102                        self.walk(site, then_expr, bindings);
7103                        self.walk(site, else_expr, bindings);
7104                    }
7105                    Expr::Not(inner)
7106                    | Expr::SeqElements(inner)
7107                    | Expr::Len(inner)
7108                    | Expr::Head(inner)
7109                    | Expr::MapKeys(inner)
7110                    | Expr::Some(inner) => self.walk(site, inner, bindings),
7111                    Expr::Eq(left, right)
7112                    | Expr::Neq(left, right)
7113                    | Expr::Add(left, right)
7114                    | Expr::Sub(left, right) => {
7115                        self.walk(site, left, bindings);
7116                        self.walk(site, right, bindings);
7117                    }
7118                    Expr::Contains { collection, value } | Expr::Count { collection, value } => {
7119                        self.walk(site, collection, bindings);
7120                        self.walk(site, value, bindings);
7121                    }
7122                    Expr::MapContainsKey { map, key }
7123                    | Expr::MapGet { map, key }
7124                    | Expr::MapValue { map, key } => {
7125                        self.walk(site, map, bindings);
7126                        self.walk(site, key, bindings);
7127                    }
7128                    Expr::SeqStartsWith { seq, prefix } => {
7129                        self.walk(site, seq, bindings);
7130                        self.walk(site, prefix, bindings);
7131                    }
7132                    Expr::MapLiteral(entries) => {
7133                        for (key, value) in entries {
7134                            self.walk(site, key, bindings);
7135                            self.walk(site, value, bindings);
7136                        }
7137                    }
7138                    Expr::Call { args, .. } => {
7139                        for arg in args {
7140                            self.walk(site, arg, bindings);
7141                        }
7142                    }
7143                    Expr::Quantified { over, body, .. } => {
7144                        self.walk(site, over, bindings);
7145                        self.walk(site, body, bindings);
7146                    }
7147                }
7148            }
7149
7150            fn walk_updates(
7151                &mut self,
7152                site: &str,
7153                updates: &[Update],
7154                bindings: &BTreeMap<String, TypeRef>,
7155            ) {
7156                for update in updates {
7157                    match update {
7158                        Update::Assign { expr, .. } => self.walk(site, expr, bindings),
7159                        Update::Increment { .. }
7160                        | Update::Decrement { .. }
7161                        | Update::SeqPopFront { .. } => {}
7162                        Update::MapInsert { key, value, .. } => {
7163                            self.walk(site, key, bindings);
7164                            self.walk(site, value, bindings);
7165                        }
7166                        Update::MapIncrement { key, .. }
7167                        | Update::MapDecrement { key, .. }
7168                        | Update::MapRemove { key, .. } => self.walk(site, key, bindings),
7169                        Update::SetInsert { value, .. }
7170                        | Update::SetRemove { value, .. }
7171                        | Update::SeqAppend { value, .. }
7172                        | Update::SeqRemoveValue { value, .. } => self.walk(site, value, bindings),
7173                        Update::SeqPrepend { values, .. } | Update::SeqRemoveAll { values, .. } => {
7174                            self.walk(site, values, bindings)
7175                        }
7176                        Update::Conditional {
7177                            condition,
7178                            then_updates,
7179                            else_updates,
7180                        } => {
7181                            self.walk(site, condition, bindings);
7182                            self.walk_updates(site, then_updates, bindings);
7183                            self.walk_updates(site, else_updates, bindings);
7184                        }
7185                        Update::ForEach { over, updates, .. } => {
7186                            self.walk(site, over, bindings);
7187                            self.walk_updates(site, updates, bindings);
7188                        }
7189                    }
7190                }
7191            }
7192        }
7193
7194        let mut checked = 0;
7195        let mut plain = Vec::new();
7196        for schema in canonical_machine_schemas() {
7197            let mut walk = Walk {
7198                schema: &schema,
7199                compiler: MachineTlaCompiler::new(&schema),
7200                checked: 0,
7201                plain: Vec::new(),
7202            };
7203            let none = BTreeMap::new();
7204            for transition in &schema.transitions {
7205                let bindings = walk.compiler.binding_type_map(transition);
7206                let site = transition.name.as_str();
7207                for guard in &transition.guards {
7208                    walk.walk(site, &guard.expr, &bindings);
7209                }
7210                walk.walk_updates(site, &transition.updates, &bindings);
7211                for emit in &transition.emit {
7212                    for expr in emit.fields.values() {
7213                        walk.walk(site, expr, &bindings);
7214                    }
7215                }
7216            }
7217            for invariant in &schema.invariants {
7218                walk.walk(&invariant.name, &invariant.expr, &none);
7219            }
7220            for helper in schema.helpers.iter().chain(schema.derived.iter()) {
7221                let params = helper
7222                    .params
7223                    .iter()
7224                    .map(|param| (param.name.as_str().to_owned(), param.ty.clone()))
7225                    .collect::<BTreeMap<_, _>>();
7226                walk.walk(&helper.name, &helper.body, &params);
7227            }
7228            checked += walk.checked;
7229            plain.extend(walk.plain);
7230        }
7231        assert!(
7232            plain.is_empty(),
7233            "option orderings rendered as plain comparisons (TLC cannot order option records):\n{}",
7234            plain.join("\n")
7235        );
7236        // MobMachine's seven member-progress guards order options: the walk
7237        // must find them, or the contract passes vacuously.
7238        assert!(checked >= 7, "the walk found {checked} option orderings");
7239    }
7240}
7241
7242fn render_sequence_domain_definition(inner: &TypeRef) -> String {
7243    let inner_domain = render_type_domain_expr(inner);
7244    format!(
7245        "{{<<>>}} \\cup {{<<x>> : x \\in {inner_domain}}} \\cup {{<<x, y>> : x \\in {inner_domain}, y \\in {inner_domain}}}"
7246    )
7247}
7248
7249fn render_option_domain_definition(inner: &TypeRef) -> String {
7250    let inner_domain = render_type_domain_expr(inner);
7251    format!("{{None}} \\cup {{Some(x) : x \\in {inner_domain}}}")
7252}
7253
7254fn render_map_domain_definition(key: &TypeRef, value: &TypeRef) -> String {
7255    let key_domain = render_type_domain_expr(key);
7256    let value_domain = render_type_domain_expr(value);
7257    let empty_map = "[x \\in {} |-> None]";
7258    format!(
7259        "{{{empty_map}}} \\cup {{ [x \\in {{k}} |-> v] : k \\in {key_domain}, v \\in {value_domain} }}"
7260    )
7261}
7262
7263fn ordered_composite_domain_definitions(
7264    constants: &BTreeMap<String, TypeRef>,
7265) -> Vec<(&String, &TypeRef)> {
7266    let mut domains = constants
7267        .iter()
7268        .filter(|(_, ty)| {
7269            matches!(
7270                ty,
7271                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7272            )
7273        })
7274        .collect::<Vec<_>>();
7275    domains.sort_by_key(|(name, ty)| (domain_dependency_depth(ty), (*name).clone()));
7276    domains
7277}
7278
7279fn domain_dependency_depth(ty: &TypeRef) -> usize {
7280    match ty {
7281        TypeRef::Option(inner) | TypeRef::Seq(inner) | TypeRef::Set(inner) => {
7282            1 + domain_dependency_depth(inner)
7283        }
7284        TypeRef::Map(key, value) => {
7285            1 + domain_dependency_depth(key).max(domain_dependency_depth(value))
7286        }
7287        TypeRef::Bool
7288        | TypeRef::U32
7289        | TypeRef::U64
7290        | TypeRef::String
7291        | TypeRef::Named(_)
7292        | TypeRef::Enum(_) => 0,
7293    }
7294}
7295
7296/// The rendered payload of one owner feedback input.
7297struct FeedbackPayload {
7298    payload_expr: String,
7299    quantifiers: Vec<String>,
7300    /// `(obligation field, bound member variable)` per `ObligationMember`.
7301    members: Vec<(String, String)>,
7302}
7303
7304/// Whether `NoOpenObligationsOnTerminal_<protocol>` applies: the producer has
7305/// terminal phases and the protocol is `AckRequired`, so only owner feedback
7306/// closes its obligations. Under `AckOrAbort` and `TerminalClosure` the
7307/// terminal phase is itself the closure, and a `PublicationOnly` protocol has
7308/// no feedback (the publication closes it), so for those the invariant would be
7309/// unsatisfiable once the producer reaches a terminal phase.
7310fn terminal_closure_required(
7311    protocol: &meerkat_machine_schema::EffectHandoffProtocol,
7312    producer: &MachineSchema,
7313) -> bool {
7314    !producer.state.terminal_phases.is_empty()
7315        && matches!(
7316            protocol.closure_policy,
7317            meerkat_machine_schema::ClosurePolicy::AckRequired
7318        )
7319}
7320
7321fn render_type_domain_expr(ty: &TypeRef) -> String {
7322    match ty {
7323        TypeRef::Bool => "BOOLEAN".into(),
7324        // dogma #172 (codegen half): U32 and U64 are distinct bounded domains,
7325        // not one collapsed `NatValues`. The domains-map machinery auto-declares
7326        // the `U32Values` CONSTANT and emits its .cfg sample assignment, so a
7327        // u32 field references its own domain (matching the kernel's u32 width
7328        // check) rather than aliasing the unbounded u64 domain.
7329        TypeRef::U32 => "U32Values".into(),
7330        TypeRef::U64 => "NatValues".into(),
7331        TypeRef::String => "StringValues".into(),
7332        TypeRef::Named(_)
7333        | TypeRef::Enum(_)
7334        | TypeRef::Set(_)
7335        | TypeRef::Seq(_)
7336        | TypeRef::Option(_)
7337        | TypeRef::Map(_, _) => domain_constant_name(ty),
7338    }
7339}
7340
7341fn domain_constant_name(ty: &TypeRef) -> String {
7342    match ty {
7343        TypeRef::Named(name) => format!("{}Values", tla_ident(name)),
7344        TypeRef::Enum(name) => format!("{}Values", tla_ident(name)),
7345        TypeRef::Seq(inner) => format!("SeqOf{}Values", tla_ident(type_ref_name(inner))),
7346        TypeRef::Set(inner) => format!("SetOf{}Values", tla_ident(type_ref_name(inner))),
7347        TypeRef::String => "StringValues".into(),
7348        TypeRef::Bool => "BooleanValues".into(),
7349        TypeRef::U32 => "U32Values".into(),
7350        TypeRef::U64 => "NatValues".into(),
7351        TypeRef::Option(inner) => format!("Option{}Values", tla_ident(type_ref_name(inner))),
7352        TypeRef::Map(key, value) => {
7353            format!(
7354                "Map{}{}Values",
7355                tla_ident(type_ref_name(key)),
7356                tla_ident(type_ref_name(value))
7357            )
7358        }
7359    }
7360}
7361
7362fn type_ref_name(ty: &TypeRef) -> String {
7363    match ty {
7364        TypeRef::Bool => "Bool".into(),
7365        TypeRef::U32 => "U32".into(),
7366        TypeRef::U64 => "U64".into(),
7367        TypeRef::String => "String".into(),
7368        TypeRef::Named(name) => name.as_str().to_owned(),
7369        TypeRef::Enum(name) => name.as_str().to_owned(),
7370        TypeRef::Option(inner) => format!("Option{}", type_ref_name(inner)),
7371        TypeRef::Set(inner) => format!("Set{}", type_ref_name(inner)),
7372        TypeRef::Seq(inner) => format!("Seq{}", type_ref_name(inner)),
7373        TypeRef::Map(key, value) => format!("Map{}{}", type_ref_name(key), type_ref_name(value)),
7374    }
7375}
7376
7377struct CompositionTlaCompiler<'a> {
7378    schema: &'a CompositionSchema,
7379    machine_by_instance: BTreeMap<&'a str, &'a MachineSchema>,
7380    named_bindings: BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
7381    fallback_machine: &'a MachineSchema,
7382    unchanged_frames: RefCell<UnchangedFrameInterner>,
7383    /// Shared with every machine compiler that renders into this module (see
7384    /// `MachineTlaCompiler::option_order_used`).
7385    option_order_used: Rc<Cell<bool>>,
7386}
7387
7388const COMPOSITION_UNCHANGED_CHUNK_SIZE: usize = 64;
7389const COMPOSITION_UNCHANGED_SPLIT_THRESHOLD: usize = 96;
7390
7391/// Prefix for the generated named UNCHANGED frame operators.
7392///
7393/// Deliberately upper-camel: the machine-poster TLA reader treats a
7394/// `^[a-z_][A-Za-z0-9_]* == ...` line before `THEOREM` as a machine invariant,
7395/// and a line ending in bare `==` as the head of a multi-line definition. An
7396/// upper-case name on a single line is invisible to both.
7397const UNCHANGED_FRAME_PREFIX: &str = "UnchangedFrame_";
7398
7399/// Stable 64-bit FNV-1a.
7400///
7401/// Frame operator names are derived from frame content so that adding or
7402/// removing a transition perturbs exactly the frames it touches instead of
7403/// renumbering every later one. That only holds if the hash itself is stable:
7404/// `std::collections::hash_map::DefaultHasher` is explicitly documented as not
7405/// stable across Rust releases, so a toolchain bump would rename every frame
7406/// and turn `machine-check-drift` red with no source change. FNV-1a is pinned
7407/// here for that reason.
7408fn fnv1a64(bytes: &[u8]) -> u64 {
7409    const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
7410    const PRIME: u64 = 0x0000_0100_0000_01b3;
7411    let mut hash = OFFSET_BASIS;
7412    for byte in bytes {
7413        hash ^= u64::from(*byte);
7414        hash = hash.wrapping_mul(PRIME);
7415    }
7416    hash
7417}
7418
7419/// Renders one UNCHANGED frame as a single TLA line.
7420///
7421/// `chunking` carries the composition-only `(split_threshold, chunk_size)`
7422/// policy: TLC's semantic pass can overflow on very large tuple frames, so a
7423/// composition frame past the threshold is expressed as a conjunction of
7424/// smaller tuples. `/\` is an ordinary infix operator, so the conjunction is
7425/// the same formula as the previously emitted bulleted list. Machines pass
7426/// `None` and keep their single-tuple frame verbatim.
7427fn unchanged_frame_body(vars: &[String], chunking: Option<(usize, usize)>) -> String {
7428    if let Some((split_threshold, chunk_size)) = chunking
7429        && vars.len() > split_threshold
7430    {
7431        return vars
7432            .chunks(chunk_size)
7433            .map(|chunk| format!("UNCHANGED << {} >>", chunk.join(", ")))
7434            .collect::<Vec<_>>()
7435            .join(" /\\ ");
7436    }
7437    format!("UNCHANGED << {} >>", vars.join(", "))
7438}
7439
7440/// Interns the distinct UNCHANGED frames of one generated TLA module.
7441///
7442/// The renderer used to expand a full frame tuple inline at every action. On
7443/// the largest composition that was 32,850 expansions of 650 distinct frames,
7444/// which is where ~85% of the emitted bytes went. Each distinct frame is now
7445/// emitted once as a named operator and referenced by name.
7446#[derive(Default)]
7447struct UnchangedFrameInterner {
7448    /// Frame operator name -> single-line frame body. Names are derived from
7449    /// the body, so a name already bound to a *different* body is a hash
7450    /// collision, never a rename.
7451    frames: BTreeMap<String, String>,
7452    /// First observed collision, if any. Recorded rather than resolved: a
7453    /// counter suffix would be order-dependent across schema edits and, worse,
7454    /// would silently hand one action a different frame condition than it had.
7455    /// The owning `render` turns this into a typed error and emits nothing.
7456    collision: Option<UnchangedFrameCollision>,
7457}
7458
7459/// Two distinct frames that derive the same operator name.
7460#[derive(Debug, Clone, PartialEq, Eq)]
7461pub struct UnchangedFrameCollision {
7462    pub name: String,
7463    pub first: String,
7464    pub second: String,
7465}
7466
7467impl std::fmt::Display for UnchangedFrameCollision {
7468    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7469        write!(
7470            f,
7471            "frame operator `{}` derives from two different frames:\n  {}\n  {}",
7472            self.name, self.first, self.second
7473        )
7474    }
7475}
7476
7477impl UnchangedFrameInterner {
7478    /// Returns the operator name for `body`, registering the definition on
7479    /// first sight.
7480    fn intern(&mut self, body: String) -> String {
7481        let name = format!("{UNCHANGED_FRAME_PREFIX}{:016x}", fnv1a64(body.as_bytes()));
7482        match self.frames.get(&name) {
7483            Some(existing) if *existing == body => {}
7484            Some(existing) => {
7485                if self.collision.is_none() {
7486                    self.collision = Some(UnchangedFrameCollision {
7487                        name: name.clone(),
7488                        first: existing.clone(),
7489                        second: body,
7490                    });
7491                }
7492            }
7493            None => {
7494                self.frames.insert(name.clone(), body);
7495            }
7496        }
7497        name
7498    }
7499
7500    fn collision(&self) -> Option<&UnchangedFrameCollision> {
7501        self.collision.as_ref()
7502    }
7503
7504    /// Renders the definition block, sorted by operator name.
7505    ///
7506    /// Sorted rather than first-use order so that a later schema edit inserts
7507    /// or drops a single definition line instead of shifting every definition
7508    /// after it. Returns `String::new()` when the module has no frames.
7509    fn definitions_block(&self) -> String {
7510        if self.frames.is_empty() {
7511            return String::new();
7512        }
7513        let mut out = String::new();
7514        pushln!(
7515            &mut out,
7516            "\\* Named UNCHANGED frames. One definition per distinct frame; every action"
7517        );
7518        pushln!(
7519            &mut out,
7520            "\\* that leaves those variables unchanged references the definition by name."
7521        );
7522        for (name, body) in &self.frames {
7523            pushln!(&mut out, "{name} == {body}");
7524        }
7525        pushln!(&mut out);
7526        out
7527    }
7528}
7529
7530impl<'a> CompositionTlaCompiler<'a> {
7531    fn new(
7532        schema: &'a CompositionSchema,
7533        machine_catalog: &'a [MachineSchema],
7534    ) -> Result<Self, String> {
7535        let machine_catalog_by_name = machine_catalog
7536            .iter()
7537            .map(|machine| (machine.machine.as_str(), machine))
7538            .collect::<BTreeMap<_, _>>();
7539
7540        let mut machine_by_instance = BTreeMap::new();
7541        for instance in &schema.machines {
7542            let machine = machine_catalog_by_name
7543                .get(instance.machine_name.as_str())
7544                .copied()
7545                .ok_or_else(|| {
7546                    format!(
7547                        "unknown machine schema `{}` for composition `{}`",
7548                        instance.machine_name, schema.name
7549                    )
7550                })?;
7551            machine_by_instance.insert(instance.instance_id.as_str(), machine);
7552        }
7553        let named_bindings =
7554            collect_composition_named_bindings(machine_by_instance.values().copied());
7555
7556        Ok(Self {
7557            schema,
7558            machine_by_instance,
7559            named_bindings,
7560            fallback_machine: machine_catalog.first().ok_or_else(|| {
7561                format!(
7562                    "no machine catalog available for composition `{}`",
7563                    schema.name
7564                )
7565            })?,
7566            unchanged_frames: RefCell::new(UnchangedFrameInterner::default()),
7567            option_order_used: Rc::default(),
7568        })
7569    }
7570
7571    /// The machine compiler for one instance's part of this module. Every
7572    /// compiler that renders into the module shares its option-order flag, so
7573    /// an `OptionLt` / `OptionLe` call never reaches the module without the
7574    /// definitions.
7575    fn instance_compiler(
7576        &self,
7577        instance_id: &str,
7578        helper_prefix: String,
7579    ) -> MachineTlaCompiler<'_> {
7580        MachineTlaCompiler::new_with_helper_prefix(self.machine(instance_id), helper_prefix)
7581            .with_phase_symbol(self.phase_var(instance_id))
7582            .with_field_env_override(self.machine_field_env(instance_id))
7583            .with_option_order_flag(Rc::clone(&self.option_order_used))
7584    }
7585
7586    fn render_unchanged_vars(&self, out: &mut String, prefix: &str, vars: &[String]) {
7587        if vars.is_empty() {
7588            return;
7589        }
7590        // The frame is interned on its variable list alone and referenced at
7591        // the caller's own `prefix`, so the conjunct keeps its original column.
7592        // Indentation is semantically load-bearing in TLA bulleted lists.
7593        let body = unchanged_frame_body(
7594            vars,
7595            Some((
7596                COMPOSITION_UNCHANGED_SPLIT_THRESHOLD,
7597                COMPOSITION_UNCHANGED_CHUNK_SIZE,
7598            )),
7599        );
7600        let name = self.unchanged_frames.borrow_mut().intern(body);
7601        writeln!(out, "{prefix}{name}").expect("write to string");
7602    }
7603
7604    fn render(&self) -> std::result::Result<String, CompositionTlaError> {
7605        // Fail-closed gate: every route component must resolve against the
7606        // composition schema before any CASE expression is emitted. This makes
7607        // the defensive `OTHER -> "unknown_*"` branches in the generated TLA
7608        // provably unreachable rather than silent catch-alls.
7609        self.validate_routes()?;
7610
7611        let mut out = String::new();
7612        let constants = self.collect_binding_domains();
7613        let named_samples =
7614            collect_composition_named_type_samples(self.schema, &self.machine_by_instance);
7615        let machine_vars = self.machine_vars();
7616        let obligation_vars = self.obligation_vars();
7617        let mut machine_invariant_names = Vec::new();
7618
7619        pushln!(&mut out, "---- MODULE model ----");
7620        pushln!(&mut out, "EXTENDS TLC, Naturals, Sequences, FiniteSets");
7621        pushln!(&mut out);
7622        writeln!(
7623            &mut out,
7624            "\\* Generated composition model for {}.",
7625            self.schema.name
7626        )
7627        .expect("write to string");
7628        pushln!(&mut out);
7629
7630        let mut model_constants = constants
7631            .iter()
7632            .filter(|(_, ty)| {
7633                !matches!(
7634                    ty,
7635                    TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7636                )
7637            })
7638            .map(|(name, _)| name)
7639            .cloned()
7640            .collect::<Vec<_>>();
7641        if composition_uses_u64_max(self.schema, &self.machine_by_instance) {
7642            model_constants.push(TLA_RUST_U64_MAX_CONSTANT.to_owned());
7643        }
7644        if !model_constants.is_empty() {
7645            if model_constants
7646                .iter()
7647                .any(|constant| constant == TLA_RUST_U64_MAX_CONSTANT)
7648            {
7649                pushln!(
7650                    &mut out,
7651                    "\\* RustU64Max is the TLA boundary for Expr::U64Max; production generated Rust renders u64::MAX."
7652                );
7653            }
7654            writeln!(&mut out, "CONSTANTS {}", model_constants.join(", "))
7655                .expect("write to string");
7656            pushln!(&mut out);
7657        }
7658
7659        writeln!(&mut out, "None == [tag |-> \"none\", value |-> \"none\"]")
7660            .expect("write to string");
7661        writeln!(&mut out, "Some(v) == [tag |-> \"some\", value |-> v]");
7662        pushln!(&mut out);
7663        let option_order_anchor = out.len();
7664
7665        push_cfg_assignment_operator_definitions(
7666            &mut out,
7667            &constants,
7668            &self.named_bindings,
7669            &CfgAssignmentOperatorProfile {
7670                suffix: "Ci".to_owned(),
7671                explicit_values: None,
7672                sample_cardinality: default_sample_cardinality(false),
7673                domain_overrides: None,
7674                named_samples: &named_samples,
7675                include_string_samples: false,
7676            },
7677        );
7678        push_cfg_assignment_operator_definitions(
7679            &mut out,
7680            &constants,
7681            &self.named_bindings,
7682            &CfgAssignmentOperatorProfile {
7683                suffix: "Deep".to_owned(),
7684                explicit_values: None,
7685                sample_cardinality: self.schema.deep_domain_cardinality,
7686                domain_overrides: Some(&self.schema.deep_domain_overrides),
7687                named_samples: &named_samples,
7688                include_string_samples: false,
7689            },
7690        );
7691        for witness in &self.schema.witnesses {
7692            let witness_samples = collect_composition_witness_named_type_samples(
7693                self.schema,
7694                witness,
7695                &self.machine_by_instance,
7696            );
7697            push_cfg_assignment_operator_definitions(
7698                &mut out,
7699                &constants,
7700                &self.named_bindings,
7701                &CfgAssignmentOperatorProfile {
7702                    suffix: witness_cfg_operator_suffix(witness),
7703                    explicit_values: None,
7704                    sample_cardinality: self
7705                        .schema
7706                        .witness_domain_cardinality
7707                        .max(max_named_sample_cardinality(&witness_samples)),
7708                    domain_overrides: None,
7709                    named_samples: &witness_samples,
7710                    include_string_samples: true,
7711                },
7712            );
7713        }
7714        for (name, ty) in ordered_composite_domain_definitions(&constants) {
7715            let definition = match ty {
7716                TypeRef::Seq(inner) => render_sequence_domain_definition(inner),
7717                TypeRef::Option(inner) => render_option_domain_definition(inner),
7718                TypeRef::Map(key, value) => render_map_domain_definition(key, value),
7719                _ => continue,
7720            };
7721            writeln!(&mut out, "{} == {}", name, definition).expect("write to string");
7722        }
7723        if constants.values().any(|ty| {
7724            matches!(
7725                ty,
7726                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7727            )
7728        }) {
7729            pushln!(&mut out);
7730        }
7731        writeln!(
7732            &mut out,
7733            "MapLookup(map, key) == IF key \\in DOMAIN map THEN map[key] ELSE None"
7734        )
7735        .expect("write to string");
7736        writeln!(
7737            &mut out,
7738            "MapSet(map, key, value) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN value ELSE map[x]]"
7739        )
7740        .expect("write to string");
7741        writeln!(
7742            &mut out,
7743            "MapIncrement(map, key, amount) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN (IF key \\in DOMAIN map THEN map[key] ELSE 0) + amount ELSE map[x]]"
7744        )
7745        .expect("write to string");
7746        writeln!(
7747            &mut out,
7748            "MapDecrement(map, key, amount) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN (IF key \\in DOMAIN map THEN map[key] ELSE 0) - amount ELSE map[x]]"
7749        )
7750        .expect("write to string");
7751        writeln!(
7752            &mut out,
7753            "MapRemove(map, key) == [x \\in DOMAIN map \\ {{key}} |-> map[x]]"
7754        )
7755        .expect("write to string");
7756        writeln!(
7757            &mut out,
7758            "StartsWith(seq, prefix) == /\\ Len(prefix) <= Len(seq) /\\ SubSeq(seq, 1, Len(prefix)) = prefix"
7759        )
7760        .expect("write to string");
7761        writeln!(
7762            &mut out,
7763            "SeqElements(seq) == {{seq[i] : i \\in 1..Len(seq)}}"
7764        )
7765        .expect("write to string");
7766        writeln!(
7767            &mut out,
7768            "Count(seq, value) == Cardinality({{i \\in DOMAIN seq : seq[i] = value}})"
7769        )
7770        .expect("write to string");
7771        if self.schema.machines.iter().any(|instance| {
7772            !self
7773                .machine(instance.instance_id.as_str())
7774                .tlc_representative_inputs
7775                .is_empty()
7776        }) {
7777            writeln!(
7778                &mut out,
7779                "{TLC_REPRESENTATIVE_DOMAIN_HELPER}(values) == IF values = {{}} THEN {{}} ELSE {{CHOOSE value \\in values : TRUE}}"
7780            )
7781            .expect("write to string");
7782        }
7783        writeln!(
7784            &mut out,
7785            "RECURSIVE SeqRemove(_, _)\nSeqRemove(seq, value) == IF Len(seq) = 0 THEN <<>> ELSE IF Head(seq) = value THEN Tail(seq) ELSE <<Head(seq)>> \\o SeqRemove(Tail(seq), value)"
7786        )
7787        .expect("write to string");
7788        writeln!(
7789            &mut out,
7790            "RECURSIVE SeqRemoveAll(_, _)\nSeqRemoveAll(seq, values) == IF Len(values) = 0 THEN seq ELSE SeqRemoveAll(SeqRemove(seq, Head(values)), Tail(values))"
7791        )
7792        .expect("write to string");
7793        writeln!(
7794            &mut out,
7795            "AppendIfMissing(seq, value) == IF value \\in SeqElements(seq) THEN seq ELSE Append(seq, value)"
7796        )
7797        .expect("write to string");
7798        self.render_static_sets(&mut out)?;
7799
7800        let all_vars = {
7801            let mut v = machine_vars;
7802            v.extend(obligation_vars.clone());
7803            v.push("model_step_count".into());
7804            v.push("pending_inputs".into());
7805            v.push("observed_inputs".into());
7806            v.push("pending_routes".into());
7807            v.push("delivered_routes".into());
7808            v.push("emitted_effects".into());
7809            v.push("observed_transitions".into());
7810            v.push("witness_current_script_input".into());
7811            v.push("witness_remaining_script_inputs".into());
7812            v
7813        };
7814        writeln!(&mut out, "VARIABLES {}", all_vars.join(", ")).expect("write to string");
7815        writeln!(&mut out, "vars == << {} >>", all_vars.join(", ")).expect("write to string");
7816        pushln!(&mut out);
7817
7818        // Named UNCHANGED frames are spliced back in here once the whole module
7819        // body is rendered: the frames are discovered while rendering actions,
7820        // but TLA requires an operator to be defined before it is referenced.
7821        // This is the first point where every frame variable is in scope.
7822        let unchanged_frame_anchor = out.len();
7823
7824        writeln!(
7825            &mut out,
7826            "RoutePackets == SeqElements(pending_routes) \\cup delivered_routes"
7827        )
7828        .expect("write to string");
7829        writeln!(
7830            &mut out,
7831            "PendingActors == {{ActorOfMachine(packet.machine) : packet \\in SeqElements(pending_inputs)}}"
7832        )
7833        .expect("write to string");
7834        writeln!(
7835            &mut out,
7836            "HigherPriorityReady(actor) == \\E priority \\in ActorPriorities : /\\ priority[2] = actor /\\ priority[1] \\in PendingActors"
7837        )
7838        .expect("write to string");
7839        pushln!(&mut out);
7840
7841        pushln!(&mut out, "BaseInit ==");
7842        for instance in &self.schema.machines {
7843            let machine = self.machine(instance.instance_id.as_str());
7844            writeln!(
7845                &mut out,
7846                "    /\\ {} = {}",
7847                self.phase_var(instance.instance_id.as_str()),
7848                tla_string(&machine.state.init.phase)
7849            )
7850            .expect("write to string");
7851            for field in &machine.state.fields {
7852                let init_expr = machine
7853                    .state
7854                    .init
7855                    .fields
7856                    .iter()
7857                    .find(|item| item.field == field.name)
7858                    .map(|item| {
7859                        let compiler = self.instance_compiler(
7860                            instance.instance_id.as_str(),
7861                            format!("{}__", tla_ident(&instance.instance_id)),
7862                        );
7863                        compiler.render_expr(&item.expr, &BTreeMap::new(), &BTreeMap::new())
7864                    })
7865                    .unwrap_or_else(|| default_state_init_expr(&field.ty));
7866                writeln!(
7867                    &mut out,
7868                    "    /\\ {} = {}",
7869                    self.field_var(instance.instance_id.as_str(), field.name.as_str()),
7870                    init_expr
7871                )
7872                .expect("write to string");
7873            }
7874        }
7875        for var in &obligation_vars {
7876            pushln!(&mut out, "    /\\ {} = {{}}", var);
7877        }
7878        pushln!(&mut out, "    /\\ model_step_count = 0");
7879        pushln!(&mut out, "    /\\ pending_routes = <<>>");
7880        pushln!(&mut out, "    /\\ delivered_routes = {{}}");
7881        pushln!(&mut out, "    /\\ emitted_effects = {{}}");
7882        pushln!(&mut out, "    /\\ observed_transitions = {{}}");
7883        pushln!(&mut out);
7884
7885        pushln!(&mut out, "Init ==");
7886        pushln!(&mut out, "    /\\ BaseInit");
7887        pushln!(&mut out, "    /\\ pending_inputs = <<>>");
7888        pushln!(&mut out, "    /\\ observed_inputs = {{}}");
7889        pushln!(&mut out, "    /\\ witness_current_script_input = None");
7890        pushln!(&mut out, "    /\\ witness_remaining_script_inputs = <<>>");
7891        pushln!(&mut out);
7892
7893        for witness in &self.schema.witnesses {
7894            writeln!(
7895                &mut out,
7896                "{} ==",
7897                composition_witness_init_name(&witness.name)
7898            )
7899            .expect("write to string");
7900            writeln!(&mut out, "    /\\ BaseInit");
7901            writeln!(
7902                &mut out,
7903                "    /\\ pending_inputs = {}",
7904                self.witness_initial_pending_inputs_expr(witness)
7905            )
7906            .expect("write to string");
7907            writeln!(
7908                &mut out,
7909                "    /\\ observed_inputs = {}",
7910                self.witness_initial_observed_inputs_expr(witness)
7911            )
7912            .expect("write to string");
7913            writeln!(
7914                &mut out,
7915                "    /\\ witness_current_script_input = {}",
7916                self.witness_current_script_input_expr(witness)
7917            )
7918            .expect("write to string");
7919            writeln!(
7920                &mut out,
7921                "    /\\ witness_remaining_script_inputs = {}",
7922                self.witness_remaining_script_inputs_expr(witness)
7923            )
7924            .expect("write to string");
7925            pushln!(&mut out);
7926        }
7927
7928        for instance in &self.schema.machines {
7929            let machine = self.machine(instance.instance_id.as_str());
7930            let helper_prefix = format!("{}__", tla_ident(&instance.instance_id));
7931            let mut compiler = self.instance_compiler(instance.instance_id.as_str(), helper_prefix);
7932            for derived in helper_dependency_order(machine)? {
7933                compiler.render_helper(&mut out, derived);
7934                pushln!(&mut out);
7935            }
7936            if machine.machine.as_str() == "MobMachine" {
7937                compiler.render_mob_machine_native_helpers(&mut out);
7938                pushln!(&mut out);
7939            }
7940            if machine.machine.as_str() == "MeerkatMachine" {
7941                compiler.render_meerkat_machine_native_helpers(&mut out);
7942                pushln!(&mut out);
7943            }
7944            if machine.machine.as_str() == "RuntimeDeliveryMachine" {
7945                compiler.render_runtime_delivery_native_helpers(&mut out);
7946                pushln!(&mut out);
7947            }
7948            if machine.machine.as_str() == "SessionDocumentMachine" {
7949                compiler.render_session_document_native_helpers(&mut out);
7950                pushln!(&mut out);
7951            }
7952
7953            let mut rendered_actions = Vec::new();
7954            for transition in &machine.transitions {
7955                let mut action = String::new();
7956                self.render_machine_transition_action(
7957                    &mut compiler,
7958                    instance.instance_id.as_str(),
7959                    transition,
7960                    &mut action,
7961                )?;
7962                rendered_actions.push(action);
7963            }
7964
7965            for helper in &compiler.helper_defs {
7966                pushln!(&mut out, "{helper}");
7967                pushln!(&mut out);
7968            }
7969
7970            for action in &rendered_actions {
7971                pushln!(&mut out, "{action}");
7972                pushln!(&mut out);
7973            }
7974
7975            let invariant_field_env = self.machine_field_env(instance.instance_id.as_str());
7976            let invariant_binding_env = BTreeMap::new();
7977            let invariant_types = BTreeMap::new();
7978            for invariant in &machine.invariants {
7979                let invariant_name =
7980                    self.machine_invariant_name(instance.instance_id.as_str(), &invariant.name);
7981                machine_invariant_names.push(invariant_name.clone());
7982                writeln!(
7983                    &mut out,
7984                    "{} == {}",
7985                    invariant_name,
7986                    compiler.render_expr_with_types(
7987                        &invariant.expr,
7988                        &invariant_field_env,
7989                        &invariant_binding_env,
7990                        &invariant_types
7991                    )
7992                )
7993                .expect("write to string");
7994            }
7995            if !machine.invariants.is_empty() {
7996                pushln!(&mut out);
7997            }
7998        }
7999
8000        self.render_entry_packet_admissibility_helpers(&mut out)?;
8001        self.render_entry_input_actions(&mut out);
8002        self.render_deliver_queued_route_action(&mut out);
8003        self.render_reject_pending_entry_input_action(&mut out);
8004        self.render_quiescent_stutter(&mut out);
8005        self.render_witness_inject_actions(&mut out);
8006        self.render_witness_completion_operators(&mut out);
8007        self.render_witness_action_constraint_operators(&mut out);
8008        self.render_witness_satisfied_stutter_actions(&mut out);
8009        // TLA+ does not permit action references before their definitions.
8010        // Owner-feedback actions participate in CoreNext and witness Next, so
8011        // render them before either dispatcher is declared.
8012        self.render_owner_actor_processes(&mut out)?;
8013
8014        let core_next_branches = self.core_next_branches();
8015
8016        pushln!(&mut out, "CoreNext ==");
8017        for branch in &core_next_branches {
8018            pushln!(&mut out, "    \\/ {branch}");
8019        }
8020        pushln!(&mut out);
8021
8022        let inject_branches = self
8023            .schema
8024            .entry_inputs
8025            .iter()
8026            .map(|entry_input| self.render_entry_input_call(entry_input))
8027            .collect::<Vec<_>>();
8028
8029        pushln!(&mut out, "InjectNext ==");
8030        if inject_branches.is_empty() {
8031            pushln!(&mut out, "    FALSE");
8032        } else {
8033            for branch in &inject_branches {
8034                pushln!(&mut out, "    \\/ {branch}");
8035            }
8036        }
8037        pushln!(&mut out);
8038
8039        pushln!(&mut out, "Next ==");
8040        pushln!(&mut out, "    \\/ CoreNext");
8041        if !inject_branches.is_empty() {
8042            pushln!(&mut out, "    \\/ InjectNext");
8043        }
8044        pushln!(&mut out);
8045
8046        for witness in &self.schema.witnesses {
8047            let witness_branches = self.witness_next_branches(witness)?;
8048            writeln!(
8049                &mut out,
8050                "{} ==",
8051                composition_witness_next_name(&witness.name)
8052            )
8053            .expect("write to string");
8054            for branch in &witness_branches {
8055                pushln!(&mut out, "    \\/ {branch}");
8056            }
8057            writeln!(
8058                &mut out,
8059                "    \\/ {}",
8060                self.render_witness_inject_next_call(witness)
8061            )
8062            .expect("write to string");
8063            pushln!(&mut out);
8064        }
8065        pushln!(&mut out);
8066
8067        for invariant in &self.schema.invariants {
8068            writeln!(
8069                &mut out,
8070                "{} == {}",
8071                invariant.name,
8072                render_composition_invariant_formula(self.schema, &invariant.kind)
8073            )
8074            .expect("write to string");
8075        }
8076        if !self.schema.invariants.is_empty() {
8077            pushln!(&mut out);
8078        }
8079
8080        self.render_obligation_invariants(&mut out, &mut machine_invariant_names)?;
8081
8082        self.render_coverage_instrumentation(&mut out);
8083
8084        writeln!(
8085            &mut out,
8086            "CiStateConstraint == {}",
8087            render_composition_state_constraint(
8088                self.schema,
8089                self.schema
8090                    .ci_limits
8091                    .as_ref()
8092                    .unwrap_or(&CompositionStateLimits::ci_defaults()),
8093                self
8094            )
8095        )
8096        .expect("write to string");
8097        writeln!(
8098            &mut out,
8099            "DeepStateConstraint == {}",
8100            render_composition_state_constraint(
8101                self.schema,
8102                &composition_deep_state_limits(self.schema),
8103                self
8104            )
8105        )
8106        .expect("write to string");
8107        for witness in &self.schema.witnesses {
8108            writeln!(
8109                &mut out,
8110                "{} == {}",
8111                composition_witness_state_constraint_name(&witness.name),
8112                render_composition_state_constraint(
8113                    self.schema,
8114                    &effective_composition_state_limits(&witness.state_limits, Some(witness)),
8115                    self
8116                )
8117            )
8118            .expect("write to string");
8119        }
8120        pushln!(&mut out);
8121
8122        pushln!(&mut out, "Spec ==");
8123        pushln!(&mut out, "    /\\ Init");
8124        pushln!(&mut out, "    /\\ [][Next]_vars");
8125        pushln!(&mut out);
8126
8127        for witness in &self.schema.witnesses {
8128            let fairness_clauses = self.witness_fairness_clauses(witness)?;
8129            let fairness_chunk_names = fairness_clauses
8130                .chunks(24)
8131                .enumerate()
8132                .map(|(index, chunk)| {
8133                    let chunk_name = composition_witness_fairness_name(&witness.name, index);
8134                    writeln!(&mut out, "{chunk_name} ==").expect("write to string");
8135                    for clause in chunk {
8136                        writeln!(&mut out, "    /\\ WF_vars({clause})").expect("write to string");
8137                    }
8138                    pushln!(&mut out);
8139                    chunk_name
8140                })
8141                .collect::<Vec<_>>();
8142
8143            writeln!(
8144                &mut out,
8145                "{} ==",
8146                composition_witness_spec_name(&witness.name),
8147            )
8148            .expect("write to string");
8149            writeln!(
8150                &mut out,
8151                "    /\\ {}",
8152                composition_witness_init_name(&witness.name),
8153            )
8154            .expect("write to string");
8155            writeln!(
8156                &mut out,
8157                "    /\\ [] [{}]_vars",
8158                composition_witness_next_name(&witness.name)
8159            )
8160            .expect("write to string");
8161            for chunk_name in fairness_chunk_names {
8162                writeln!(&mut out, "    /\\ {chunk_name}").expect("write to string");
8163            }
8164            pushln!(&mut out);
8165        }
8166        for witness in &self.schema.witnesses {
8167            for route in &witness.expected_routes {
8168                let formula = composition_route_observed_operator_name(route);
8169                writeln!(
8170                    &mut out,
8171                    "{} == {}",
8172                    composition_witness_route_property_name(&witness.name, route),
8173                    self.render_witness_obligation_formula(witness, formula)
8174                )
8175                .expect("write to string");
8176            }
8177            for rule in &witness.expected_scheduler_rules {
8178                let formula = composition_scheduler_triggered_operator_name(rule);
8179                writeln!(
8180                    &mut out,
8181                    "{} == {}",
8182                    composition_witness_scheduler_property_name(&witness.name, rule),
8183                    self.render_witness_obligation_formula(witness, formula)
8184                )
8185                .expect("write to string");
8186            }
8187            for (idx, state) in witness.expected_states.iter().enumerate() {
8188                let formula = self.render_witness_state_formula(state);
8189                writeln!(
8190                    &mut out,
8191                    "{} == {}",
8192                    composition_witness_state_property_name(&witness.name, idx),
8193                    self.render_witness_obligation_formula(witness, formula)
8194                )
8195                .expect("write to string");
8196            }
8197            for transition in &witness.expected_transitions {
8198                let formula = self.render_witness_transition_formula(transition);
8199                writeln!(
8200                    &mut out,
8201                    "{} == {}",
8202                    composition_witness_transition_property_name(
8203                        &witness.name,
8204                        &transition.machine,
8205                        &transition.transition,
8206                    ),
8207                    self.render_witness_obligation_formula(witness, formula)
8208                )
8209                .expect("write to string");
8210            }
8211            for (idx, ordering) in witness.expected_transition_order.iter().enumerate() {
8212                let formula = self.render_witness_transition_order_formula(ordering);
8213                writeln!(
8214                    &mut out,
8215                    "{} == {}",
8216                    composition_witness_transition_order_property_name(&witness.name, idx),
8217                    self.render_witness_obligation_formula(witness, formula)
8218                )
8219                .expect("write to string");
8220            }
8221        }
8222        if !self.schema.witnesses.is_empty() {
8223            pushln!(&mut out);
8224        }
8225        for invariant in &self.schema.invariants {
8226            pushln!(&mut out, "THEOREM Spec => []{}", invariant.name);
8227        }
8228        for invariant_name in &machine_invariant_names {
8229            pushln!(&mut out, "THEOREM Spec => []{}", invariant_name);
8230        }
8231        pushln!(&mut out);
8232        writeln!(
8233            &mut out,
8234            "============================================================================="
8235        )
8236        .expect("write to string");
8237
8238        // Fail closed on a frame-name collision: the rendered body already
8239        // references one name for two different frames, so returning it would
8240        // silently give an action the wrong frame condition.
8241        let frames = self.unchanged_frames.borrow();
8242        if let Some(collision) = frames.collision() {
8243            return Err(CompositionTlaError::UnchangedFrameCollision {
8244                composition: self.schema.name.as_str().to_owned(),
8245                collision: collision.clone(),
8246            });
8247        }
8248        out.insert_str(unchanged_frame_anchor, &frames.definitions_block());
8249        // Before the frame anchor, so inserting it last leaves that one valid.
8250        if self.option_order_used.get() {
8251            out.insert_str(option_order_anchor, TLA_OPTION_ORDER_DEFINITIONS);
8252        }
8253
8254        Ok(out)
8255    }
8256
8257    fn collect_binding_domains(&self) -> BTreeMap<String, TypeRef> {
8258        collect_composition_binding_domains(self.schema, &self.machine_by_instance)
8259    }
8260
8261    fn machine(&self, instance_id: impl AsRef<str>) -> &MachineSchema {
8262        self.machine_by_instance
8263            .get(instance_id.as_ref())
8264            .copied()
8265            .unwrap_or(self.fallback_machine)
8266    }
8267
8268    fn actor(&self, instance_id: impl AsRef<str>) -> &str {
8269        let instance_id = instance_id.as_ref();
8270        self.schema
8271            .machines
8272            .iter()
8273            .find(|machine| machine.instance_id.as_str() == instance_id)
8274            .map(|machine| machine.actor.as_str())
8275            .unwrap_or("")
8276    }
8277
8278    fn phase_var(&self, instance_id: impl AsRef<str>) -> String {
8279        format!("{}_phase", tla_ident(instance_id))
8280    }
8281
8282    fn field_var(&self, instance_id: impl AsRef<str>, field: impl AsRef<str>) -> String {
8283        format!("{}_{}", tla_ident(instance_id), tla_ident(field))
8284    }
8285
8286    fn machine_invariant_name(
8287        &self,
8288        instance_id: impl AsRef<str>,
8289        invariant: impl AsRef<str>,
8290    ) -> String {
8291        format!("{}_{}", tla_ident(instance_id), tla_ident(invariant))
8292    }
8293
8294    fn machine_transition_name(
8295        &self,
8296        instance_id: impl AsRef<str>,
8297        transition: &TransitionSchema,
8298    ) -> String {
8299        format!("{}_{}", tla_ident(instance_id), tla_ident(&transition.name))
8300    }
8301
8302    fn machine_transition_call(&self, instance_id: &str, transition: &TransitionSchema) -> String {
8303        if transition.on.bindings().is_empty() {
8304            self.machine_transition_name(instance_id, transition)
8305        } else {
8306            let binding_types = transition_trigger_variant(self.machine(instance_id), transition)
8307                .map(|variant| {
8308                    variant
8309                        .fields
8310                        .iter()
8311                        .filter(|field| {
8312                            transition
8313                                .on
8314                                .bindings()
8315                                .iter()
8316                                .any(|binding| binding == &field.name)
8317                        })
8318                        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
8319                        .collect::<BTreeMap<_, _>>()
8320                })
8321                .unwrap_or_default();
8322            let forced_bool_literals = transition_forced_bool_literals(transition, &binding_types);
8323            let mut prefix = String::new();
8324            for binding in transition.on.bindings() {
8325                if forced_bool_literals.contains_key(binding.as_str()) {
8326                    continue;
8327                }
8328                let local = format!("arg_{}", tla_ident(binding.as_str()));
8329                let Some(ty) = binding_types.get(binding.as_str()) else {
8330                    return self.machine_transition_name(instance_id, transition);
8331                };
8332                let domain = self.binding_domain_for_binding(
8333                    instance_id,
8334                    trigger_input_variant(transition),
8335                    binding.as_str(),
8336                    ty,
8337                );
8338                let domain = if transition_uses_tlc_representative_payload(
8339                    self.machine(instance_id),
8340                    transition,
8341                ) {
8342                    tlc_representative_domain(domain)
8343                } else {
8344                    domain
8345                };
8346                push_fmt(&mut prefix, format_args!("\\E {local} \\in {domain} : "));
8347            }
8348            let args = transition
8349                .on
8350                .bindings()
8351                .iter()
8352                .map(|binding| {
8353                    forced_bool_literals
8354                        .get(binding.as_str())
8355                        .map(|value| tla_bool_literal(*value).to_owned())
8356                        .unwrap_or_else(|| format!("arg_{}", tla_ident(binding.as_str())))
8357                })
8358                .collect::<Vec<_>>()
8359                .join(", ");
8360            format!(
8361                "{prefix}{}({args})",
8362                self.machine_transition_name(instance_id, transition)
8363            )
8364        }
8365    }
8366
8367    fn binding_domain_for_type(&self, ty: &TypeRef) -> String {
8368        match ty {
8369            TypeRef::Bool => "BOOLEAN".into(),
8370            TypeRef::U32 | TypeRef::U64 => "0..2".into(),
8371            TypeRef::String => "StringValues".into(),
8372            TypeRef::Named(_)
8373            | TypeRef::Enum(_)
8374            | TypeRef::Seq(_)
8375            | TypeRef::Set(_)
8376            | TypeRef::Option(_)
8377            | TypeRef::Map(_, _) => domain_constant_name(ty),
8378        }
8379    }
8380
8381    /// Payload domain for one bound field of `input` on `instance_id`: the
8382    /// machine's declared input field domain if it has one, otherwise the
8383    /// type's default domain.
8384    fn binding_domain_for_binding(
8385        &self,
8386        instance_id: &str,
8387        input: Option<&str>,
8388        binding: &str,
8389        ty: &TypeRef,
8390    ) -> String {
8391        let declared =
8392            input.and_then(|input| self.machine(instance_id).input_field_domain(input, binding));
8393        match declared {
8394            Some(meerkat_machine_schema::InputFieldDomainKind::StateField(state_field)) => {
8395                format!("{{{}}}", self.field_var(instance_id, state_field.as_str()))
8396            }
8397            Some(meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(values)) => {
8398                additional_values_domain(&self.binding_domain_for_type(ty), values)
8399            }
8400            // A composition has no machine CI profile: it explores the
8401            // field's Deep samples, the declared values and `0..2`.
8402            Some(meerkat_machine_schema::InputFieldDomainKind::CiValues(values)) => {
8403                render_u64_set(&broad_input_samples(values))
8404            }
8405            // ... and the whole type domain of a `CiSamples` field.
8406            Some(meerkat_machine_schema::InputFieldDomainKind::CiSamples(_)) | None => {
8407                self.binding_domain_for_type(ty)
8408            }
8409        }
8410    }
8411
8412    fn machine_vars(&self) -> Vec<String> {
8413        let mut vars = Vec::new();
8414        for instance in &self.schema.machines {
8415            vars.push(self.phase_var(instance.instance_id.as_str()));
8416            let machine = self.machine(instance.instance_id.as_str());
8417            for field in &machine.state.fields {
8418                vars.push(self.field_var(instance.instance_id.as_str(), field.name.as_str()));
8419            }
8420        }
8421        vars
8422    }
8423
8424    fn machine_field_env(&self, instance_id: &str) -> BTreeMap<String, String> {
8425        let machine = self.machine(instance_id);
8426        machine
8427            .state
8428            .fields
8429            .iter()
8430            .map(|field| {
8431                (
8432                    field.name.as_str().to_owned(),
8433                    self.field_var(instance_id, field.name.as_str()),
8434                )
8435            })
8436            .collect()
8437    }
8438
8439    fn obligation_symbol_suffix(
8440        &self,
8441        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
8442    ) -> String {
8443        format!(
8444            "{}_{}",
8445            tla_ident(&protocol.producer_instance),
8446            tla_ident(&protocol.name)
8447        )
8448    }
8449
8450    fn obligation_var(&self, protocol: &meerkat_machine_schema::EffectHandoffProtocol) -> String {
8451        format!("obligation_{}", self.obligation_symbol_suffix(protocol))
8452    }
8453
8454    /// Returns TLA+ variable names for obligation tracking — one per
8455    /// concrete producer/protocol pair.
8456    fn obligation_vars(&self) -> Vec<String> {
8457        self.schema
8458            .handoff_protocols
8459            .iter()
8460            .map(|protocol| self.obligation_var(protocol))
8461            .collect()
8462    }
8463
8464    fn feedback_variant(
8465        &self,
8466        feedback: &FeedbackInputRef,
8467    ) -> std::result::Result<&VariantSchema, String> {
8468        self.machine(&feedback.machine_instance)
8469            .inputs
8470            .variant_named(&feedback.input_variant)
8471            .map_err(|_| {
8472                format!(
8473                    "feedback variant `{}` not found for machine `{}`",
8474                    feedback.input_variant, feedback.machine_instance
8475                )
8476            })
8477    }
8478
8479    /// The feedback input's payload record, the quantifiers over the values it
8480    /// leaves open, and the obligation members it names. An `ObligationMember`
8481    /// value ranges over that set field of the obligation token, so the owner
8482    /// can only name a member the obligation actually carries.
8483    fn feedback_payload_expr(
8484        &self,
8485        feedback: &FeedbackInputRef,
8486        token_var: &str,
8487    ) -> std::result::Result<FeedbackPayload, String> {
8488        let variant = self.feedback_variant(feedback)?;
8489        let mut owner_context_quantifiers = Vec::new();
8490        let mut payload_fields = Vec::new();
8491        let mut members = Vec::new();
8492
8493        for field in &variant.fields {
8494            let binding = feedback
8495                .field_bindings
8496                .iter()
8497                .find(|binding| binding.input_field == field.name)
8498                .ok_or_else(|| format!("feedback binding for field `{}` not found", field.name))?;
8499            let expr = match &binding.source {
8500                FeedbackFieldSource::ObligationField(source_field) => {
8501                    format!("{token_var}.{}", tla_ident(source_field))
8502                }
8503                FeedbackFieldSource::ObligationMember(source_field) => {
8504                    let var_name = format!("member_{}", tla_ident(source_field));
8505                    owner_context_quantifiers.push(format!(
8506                        "{var_name} \\in {token_var}.{}",
8507                        tla_ident(source_field)
8508                    ));
8509                    members.push((tla_ident(source_field), var_name.clone()));
8510                    var_name
8511                }
8512                FeedbackFieldSource::OwnerContext(name) => {
8513                    let var_name = format!("owner_ctx_{}", tla_ident(name));
8514                    let domain = render_type_domain_expr(&field.ty);
8515                    owner_context_quantifiers.push(format!("{var_name} \\in {domain}"));
8516                    var_name
8517                }
8518            };
8519            payload_fields.push(format!("{} |-> {}", tla_ident(&field.name), expr));
8520        }
8521
8522        let payload_expr = if payload_fields.is_empty() {
8523            "[tag |-> \"unit\"]".to_string()
8524        } else {
8525            format!("[{}]", payload_fields.join(", "))
8526        };
8527
8528        Ok(FeedbackPayload {
8529            payload_expr,
8530            quantifiers: owner_context_quantifiers,
8531            members,
8532        })
8533    }
8534
8535    /// Obligation fields some feedback input of `protocol` names members of.
8536    /// The obligation token stays open while any of them is non-empty.
8537    fn protocol_member_fields(
8538        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
8539    ) -> BTreeSet<String> {
8540        protocol
8541            .allowed_feedback_inputs
8542            .iter()
8543            .flat_map(|feedback| feedback.field_bindings.iter())
8544            .filter_map(|binding| match &binding.source {
8545                FeedbackFieldSource::ObligationMember(field) => Some(tla_ident(field)),
8546                _ => None,
8547            })
8548            .collect()
8549    }
8550
8551    /// Renders obligation closure invariants into the TLA+ output.
8552    ///
8553    /// For each handoff protocol, generates:
8554    /// - `NoOpenObligationsOnTerminal_<protocol>`: when the producer machine is
8555    ///   in a terminal phase, the obligation set must be empty.
8556    /// - `NoFeedbackWithoutObligation_<protocol>`: a feedback input can only be
8557    ///   observed if there's a corresponding outstanding obligation.
8558    fn render_obligation_invariants(
8559        &self,
8560        out: &mut String,
8561        invariant_names: &mut Vec<String>,
8562    ) -> std::result::Result<(), String> {
8563        for protocol in &self.schema.handoff_protocols {
8564            let suffix = self.obligation_symbol_suffix(protocol);
8565            let var = self.obligation_var(protocol);
8566            let phase_var = self.phase_var(&protocol.producer_instance);
8567
8568            // Find terminal phases for the producer machine.
8569            let machine = self.machine(&protocol.producer_instance);
8570            let terminal_phases: Vec<&str> = machine
8571                .state
8572                .terminal_phases
8573                .iter()
8574                .map(meerkat_machine_schema::identity::PhaseId::as_str)
8575                .collect();
8576
8577            // NoOpenObligationsOnTerminal: terminal phase => obligation set is
8578            // empty. Only an AckRequired protocol needs owner feedback to close
8579            // its obligations; under AckOrAbort and TerminalClosure the terminal
8580            // phase is itself the closure, and a PublicationOnly protocol has no
8581            // feedback (the publication closes it), so for those the invariant
8582            // would be unsatisfiable once the producer reaches a terminal phase.
8583            if terminal_closure_required(protocol, machine) {
8584                let inv_name = format!("NoOpenObligationsOnTerminal_{}", suffix);
8585                let terminal_disjuncts: Vec<String> = terminal_phases
8586                    .iter()
8587                    .map(|phase| format!("{} = {}", phase_var, tla_string(phase)))
8588                    .collect();
8589                writeln!(
8590                    out,
8591                    "{} == ({}) => {} = {{}}",
8592                    inv_name,
8593                    terminal_disjuncts.join(" \\/ "),
8594                    var
8595                )
8596                .expect("write to string");
8597                invariant_names.push(inv_name);
8598            }
8599        }
8600
8601        let owner_feedback_sources = self
8602            .schema
8603            .handoff_protocols
8604            .iter()
8605            .flat_map(|protocol| {
8606                protocol.allowed_feedback_inputs.iter().map(move |feedback| {
8607                    format!(
8608                        "(/\\ input_packet.machine = {} /\\ input_packet.variant = {} /\\ input_packet.source_machine = {} /\\ input_packet.source_effect = {} /\\ \\E effect_packet \\in emitted_effects : /\\ effect_packet.machine = {} /\\ effect_packet.variant = {} /\\ effect_packet.effect_id = input_packet.effect_id)",
8609                        tla_string(&feedback.machine_instance),
8610                        tla_string(&feedback.input_variant),
8611                        tla_string(&protocol.producer_instance),
8612                        tla_string(&protocol.effect_variant),
8613                        tla_string(&protocol.producer_instance),
8614                        tla_string(&protocol.effect_variant),
8615                    )
8616                })
8617            })
8618            .collect::<Vec<_>>();
8619        if !owner_feedback_sources.is_empty() {
8620            pushln!(out, "OwnerFeedbackHasProtocolProvenance ==");
8621            pushln!(out, "    \\A input_packet \\in observed_inputs :");
8622            pushln!(out, "        input_packet.source_kind /= \"owner\"");
8623            writeln!(
8624                out,
8625                "        \\/ ({})",
8626                owner_feedback_sources.join(" \\/ ")
8627            )
8628            .expect("write to string");
8629            invariant_names.push("OwnerFeedbackHasProtocolProvenance".to_string());
8630        }
8631
8632        if !self.schema.handoff_protocols.is_empty() {
8633            pushln!(out);
8634        }
8635        Ok(())
8636    }
8637
8638    /// Renders owner-actor process definitions: nondeterministic actions that
8639    /// model the owner choosing to submit protocol-allowed feedback when an
8640    /// obligation is outstanding.
8641    ///
8642    /// Each allowed feedback input generates an
8643    /// `OwnerFeedback_<protocol>_<input>` action that:
8644    /// - Is enabled when the obligation set is non-empty
8645    /// - Nondeterministically picks one of the allowed feedback inputs
8646    /// - Removes one obligation token from the set
8647    /// - Injects the feedback as a pending input
8648    ///
8649    /// If any protocols have `liveness_annotation`, fairness comments are added.
8650    fn render_owner_actor_processes(&self, out: &mut String) -> std::result::Result<(), String> {
8651        for protocol in &self.schema.handoff_protocols {
8652            let var = self.obligation_var(protocol);
8653
8654            if protocol.allowed_feedback_inputs.is_empty() {
8655                continue;
8656            }
8657
8658            if let Some(liveness) = &protocol.liveness_annotation {
8659                writeln!(out, "\\* Liveness: {liveness}").expect("write to string");
8660            }
8661
8662            for feedback in &protocol.allowed_feedback_inputs {
8663                let action_name = self.owner_feedback_action_name(protocol, feedback);
8664                let FeedbackPayload {
8665                    payload_expr,
8666                    quantifiers: owner_context_quantifiers,
8667                    members,
8668                } = self.feedback_payload_expr(feedback, "token")?;
8669                let input_expr = format!(
8670                    "[machine |-> {}, variant |-> {}, source_kind |-> \"owner\", source_machine |-> {}, source_effect |-> {}, source_route |-> \"none\", effect_id |-> token.effect_id, payload |-> {}]",
8671                    tla_string(&feedback.machine_instance),
8672                    tla_string(&feedback.input_variant),
8673                    tla_string(&protocol.producer_instance),
8674                    tla_string(&protocol.effect_variant),
8675                    payload_expr,
8676                );
8677
8678                writeln!(out, "{action_name} ==").expect("write to string");
8679                writeln!(out, "    /\\ {} /= {{}}", var).expect("write to string");
8680                writeln!(out, "    /\\ \\E token \\in {} :", var).expect("write to string");
8681                let quantifier_prefix = if owner_context_quantifiers.is_empty() {
8682                    String::new()
8683                } else {
8684                    format!("\\E {} : ", owner_context_quantifiers.join(", "))
8685                };
8686                // Feedback naming obligation members discharges only those
8687                // members; the token closes once every member-bearing field of
8688                // the protocol is empty. Other feedback closes the token.
8689                let obligation_update = if members.is_empty() {
8690                    format!("{var}' = {var} \\ {{token}}")
8691                } else {
8692                    let residual = format!(
8693                        "[token EXCEPT {}]",
8694                        members
8695                            .iter()
8696                            .map(|(field, member)| format!("!.{field} = @ \\ {{{member}}}"))
8697                            .collect::<Vec<_>>()
8698                            .join(", ")
8699                    );
8700                    let drained = Self::protocol_member_fields(protocol)
8701                        .iter()
8702                        .map(|field| format!("{residual}.{field} = {{}}"))
8703                        .collect::<Vec<_>>()
8704                        .join(" /\\ ");
8705                    // Parenthesised: an unbracketed ELSE would swallow the
8706                    // conjuncts that follow it in the action.
8707                    format!(
8708                        "{var}' = (IF {drained} THEN {var} \\ {{token}} ELSE ({var} \\ {{token}}) \\cup {{{residual}}})"
8709                    )
8710                };
8711                writeln!(
8712                    out,
8713                    "        /\\ {quantifier_prefix}(/\\ pending_inputs' = Append(pending_inputs, {input_expr}) /\\ observed_inputs' = observed_inputs \\cup {{{input_expr}}} /\\ {obligation_update} /\\ model_step_count' = model_step_count + 1)"
8714                )
8715                .expect("write to string");
8716
8717                let unchanged_vars: Vec<String> = self
8718                    .machine_vars()
8719                    .into_iter()
8720                    .chain(self.obligation_vars().into_iter().filter(|v| *v != var))
8721                    .chain(
8722                        [
8723                            "pending_routes",
8724                            "delivered_routes",
8725                            "emitted_effects",
8726                            "observed_transitions",
8727                            "witness_current_script_input",
8728                            "witness_remaining_script_inputs",
8729                        ]
8730                        .iter()
8731                        .map(std::string::ToString::to_string),
8732                    )
8733                    .collect();
8734                self.render_unchanged_vars(out, "    /\\ ", &unchanged_vars);
8735                pushln!(out);
8736            }
8737        }
8738        Ok(())
8739    }
8740
8741    fn render_coverage_instrumentation(&self, out: &mut String) {
8742        let route_ops = self
8743            .schema
8744            .routes
8745            .iter()
8746            .map(|route| composition_route_coverage_operator_name(&route.name))
8747            .collect::<Vec<_>>();
8748        let scheduler_ops = self
8749            .schema
8750            .scheduler_rules
8751            .iter()
8752            .map(composition_scheduler_coverage_operator_name)
8753            .collect::<Vec<_>>();
8754
8755        for route in &self.schema.routes {
8756            writeln!(
8757                out,
8758                "{} == \\E packet \\in delivered_routes : packet.route = {}",
8759                composition_route_observed_operator_name(&route.name),
8760                tla_string(&route.name)
8761            )
8762            .expect("write to string");
8763            writeln!(
8764                out,
8765                "{} == ({} \\/ ~{})",
8766                composition_route_coverage_operator_name(&route.name),
8767                composition_route_observed_operator_name(&route.name),
8768                composition_route_observed_operator_name(&route.name)
8769            )
8770            .expect("write to string");
8771        }
8772        for rule in &self.schema.scheduler_rules {
8773            writeln!(
8774                out,
8775                "{} == {}",
8776                composition_scheduler_triggered_operator_name(rule),
8777                render_scheduler_trigger_formula(rule)
8778            )
8779            .expect("write to string");
8780            writeln!(
8781                out,
8782                "{} == ({} \\/ ~{})",
8783                composition_scheduler_coverage_operator_name(rule),
8784                composition_scheduler_triggered_operator_name(rule),
8785                composition_scheduler_triggered_operator_name(rule)
8786            )
8787            .expect("write to string");
8788        }
8789
8790        let mut instrumentation_terms = Vec::new();
8791        instrumentation_terms.extend(route_ops.into_iter());
8792        instrumentation_terms.extend(scheduler_ops.into_iter());
8793
8794        let instrumentation = if instrumentation_terms.is_empty() {
8795            "TRUE".to_string()
8796        } else {
8797            instrumentation_terms.join(" /\\ ")
8798        };
8799
8800        pushln!(out, "CoverageInstrumentation == {instrumentation}");
8801        pushln!(out);
8802    }
8803
8804    /// Fail-closed resolution check for every route in the composition.
8805    ///
8806    /// Confirms that each route's `from_machine` and `to.machine` is a declared
8807    /// machine instance, that `effect_variant` is a declared effect on the
8808    /// source machine, and that `to.input_variant` is a declared input/signal
8809    /// (per `to.kind`) on the target machine. The composition CASE builders
8810    /// (`ActorOfMachine`, `RouteSource`, `RouteEffect`, `RouteTargetMachine`,
8811    /// `RouteTargetInput`) used to map an unresolved component to a sentinel
8812    /// (`"unknown_*"`) default; with this gate run first, those sentinels are
8813    /// unreachable-by-construction for valid input, and malformed input fails
8814    /// closed instead of silently emitting a broken model.
8815    fn validate_routes(&self) -> std::result::Result<(), CompositionTlaError> {
8816        let composition = self.schema.name.as_str();
8817        for route in &self.schema.routes {
8818            let route_name = route.name.as_str();
8819
8820            // Source machine instance must be declared.
8821            let source = self
8822                .machine_by_instance
8823                .get(route.from_machine.as_str())
8824                .copied()
8825                .ok_or_else(|| CompositionTlaError::UnknownRouteSourceMachine {
8826                    composition: composition.to_owned(),
8827                    route: route_name.to_owned(),
8828                    machine: route.from_machine.as_str().to_owned(),
8829                })?;
8830
8831            // Effect variant must be declared on the source machine.
8832            if source
8833                .effects
8834                .variant_named(route.effect_variant.as_str())
8835                .is_err()
8836            {
8837                return Err(CompositionTlaError::UnknownRouteEffect {
8838                    composition: composition.to_owned(),
8839                    route: route_name.to_owned(),
8840                    machine: route.from_machine.as_str().to_owned(),
8841                    effect: route.effect_variant.as_str().to_owned(),
8842                });
8843            }
8844
8845            // Target machine instance must be declared.
8846            let target = self
8847                .machine_by_instance
8848                .get(route.to.machine.as_str())
8849                .copied()
8850                .ok_or_else(|| CompositionTlaError::UnknownRouteTargetMachine {
8851                    composition: composition.to_owned(),
8852                    route: route_name.to_owned(),
8853                    machine: route.to.machine.as_str().to_owned(),
8854                })?;
8855
8856            // Target input/signal variant must be declared on the target
8857            // machine, dispatching on the route's structural kind.
8858            match route.to.kind {
8859                RouteTargetKind::Input => {
8860                    if target
8861                        .inputs
8862                        .variant_named(route.to.input_variant.as_str())
8863                        .is_err()
8864                    {
8865                        return Err(CompositionTlaError::UnknownRouteTargetInput {
8866                            composition: composition.to_owned(),
8867                            route: route_name.to_owned(),
8868                            machine: route.to.machine.as_str().to_owned(),
8869                            input: route.to.input_variant.as_str().to_owned(),
8870                        });
8871                    }
8872                }
8873                RouteTargetKind::Signal => {
8874                    if target
8875                        .signals
8876                        .variant_named(route.to.input_variant.as_str())
8877                        .is_err()
8878                    {
8879                        return Err(CompositionTlaError::UnknownRouteTargetSignal {
8880                            composition: composition.to_owned(),
8881                            route: route_name.to_owned(),
8882                            machine: route.to.machine.as_str().to_owned(),
8883                            signal: route.to.input_variant.as_str().to_owned(),
8884                        });
8885                    }
8886                }
8887            }
8888        }
8889        Ok(())
8890    }
8891
8892    fn render_static_sets(&self, out: &mut String) -> std::result::Result<(), CompositionTlaError> {
8893        pushln!(out, "Machines == {{");
8894        for (idx, machine) in self.schema.machines.iter().enumerate() {
8895            let suffix = if idx + 1 == self.schema.machines.len() {
8896                ""
8897            } else {
8898                ","
8899            };
8900            writeln!(
8901                out,
8902                "    <<{}, {}, {}>>{}",
8903                tla_string(&machine.instance_id),
8904                tla_string(&machine.machine_name),
8905                tla_string(&machine.actor),
8906                suffix
8907            )
8908            .expect("write to string");
8909        }
8910        pushln!(out, "}}");
8911        pushln!(out);
8912
8913        pushln!(out, "RouteNames == {{");
8914        for (idx, route) in self.schema.routes.iter().enumerate() {
8915            let suffix = if idx + 1 == self.schema.routes.len() {
8916                ""
8917            } else {
8918                ","
8919            };
8920            pushln!(out, "    {}{}", tla_string(&route.name), suffix);
8921        }
8922        pushln!(out, "}}");
8923        pushln!(out);
8924
8925        pushln!(out, "Actors == {{");
8926        for (idx, machine) in self.schema.machines.iter().enumerate() {
8927            let suffix = if idx + 1 == self.schema.machines.len() {
8928                ""
8929            } else {
8930                ","
8931            };
8932            pushln!(out, "    {}{}", tla_string(&machine.actor), suffix);
8933        }
8934        pushln!(out, "}}");
8935        pushln!(out);
8936
8937        pushln!(out, "ActorPriorities == {{");
8938        for (idx, priority) in self.schema.actor_priorities.iter().enumerate() {
8939            let suffix = if idx + 1 == self.schema.actor_priorities.len() {
8940                ""
8941            } else {
8942                ","
8943            };
8944            writeln!(
8945                out,
8946                "    <<{}, {}>>{}",
8947                tla_string(&priority.higher),
8948                tla_string(&priority.lower),
8949                suffix
8950            )
8951            .expect("write to string");
8952        }
8953        pushln!(out, "}}");
8954        pushln!(out);
8955
8956        pushln!(out, "SchedulerRules == {{");
8957        for (idx, rule) in self.schema.scheduler_rules.iter().enumerate() {
8958            let suffix = if idx + 1 == self.schema.scheduler_rules.len() {
8959                ""
8960            } else {
8961                ","
8962            };
8963            pushln!(out, "    {}{}", render_scheduler_rule_tuple(rule), suffix);
8964        }
8965        writeln!(out, "}}");
8966        pushln!(out);
8967
8968        let composition_name = self.schema.name.as_str();
8969        render_composition_case_fn(
8970            out,
8971            composition_name,
8972            "ActorOfMachine",
8973            "machine_id",
8974            self.schema
8975                .machines
8976                .iter()
8977                .map(|machine| (machine.instance_id.as_str(), tla_string(&machine.actor)))
8978                .collect(),
8979            CaseDefault::FailClosed {
8980                component: "actor",
8981                require_mapping: true,
8982            },
8983        )?;
8984        render_composition_case_fn(
8985            out,
8986            composition_name,
8987            "RouteSource",
8988            "route_name",
8989            self.schema
8990                .routes
8991                .iter()
8992                .map(|route| (route.name.as_str(), tla_string(&route.from_machine)))
8993                .collect(),
8994            CaseDefault::FailClosed {
8995                component: "route_source_machine",
8996                require_mapping: false,
8997            },
8998        )?;
8999        render_composition_case_fn(
9000            out,
9001            composition_name,
9002            "RouteEffect",
9003            "route_name",
9004            self.schema
9005                .routes
9006                .iter()
9007                .map(|route| (route.name.as_str(), tla_string(&route.effect_variant)))
9008                .collect(),
9009            CaseDefault::FailClosed {
9010                component: "route_effect",
9011                require_mapping: false,
9012            },
9013        )?;
9014        render_composition_case_fn(
9015            out,
9016            composition_name,
9017            "RouteTargetMachine",
9018            "route_name",
9019            self.schema
9020                .routes
9021                .iter()
9022                .map(|route| (route.name.as_str(), tla_string(&route.to.machine)))
9023                .collect(),
9024            CaseDefault::FailClosed {
9025                component: "route_target_machine",
9026                require_mapping: false,
9027            },
9028        )?;
9029        render_composition_case_fn(
9030            out,
9031            composition_name,
9032            "RouteTargetInput",
9033            "route_name",
9034            self.schema
9035                .routes
9036                .iter()
9037                .map(|route| (route.name.as_str(), tla_string(&route.to.input_variant)))
9038                .collect(),
9039            CaseDefault::FailClosed {
9040                component: "route_target_input",
9041                require_mapping: false,
9042            },
9043        )?;
9044        render_composition_case_fn(
9045            out,
9046            composition_name,
9047            "RouteTargetKind",
9048            "route_name",
9049            self.schema
9050                .routes
9051                .iter()
9052                .map(|route| {
9053                    (
9054                        route.name.as_str(),
9055                        tla_string(match route.to.kind {
9056                            RouteTargetKind::Input => "Input",
9057                            RouteTargetKind::Signal => "Signal",
9058                        }),
9059                    )
9060                })
9061                .collect(),
9062            CaseDefault::ClosedEnum(tla_string("Unknown")),
9063        )?;
9064        render_composition_case_fn(
9065            out,
9066            composition_name,
9067            "RouteDeliveryKind",
9068            "route_name",
9069            self.schema
9070                .routes
9071                .iter()
9072                .map(|route| {
9073                    (
9074                        route.name.as_str(),
9075                        tla_string(match route.delivery {
9076                            RouteDelivery::Immediate => "Immediate",
9077                            RouteDelivery::Enqueue => "Enqueue",
9078                        }),
9079                    )
9080                })
9081                .collect(),
9082            CaseDefault::ClosedEnum(tla_string("Unknown")),
9083        )?;
9084        writeln!(
9085            out,
9086            "RouteTargetActor(route_name) == ActorOfMachine(RouteTargetMachine(route_name))"
9087        );
9088        pushln!(out);
9089        Ok(())
9090    }
9091
9092    fn render_entry_input_actions(&self, out: &mut String) {
9093        for entry_input in &self.schema.entry_inputs {
9094            let machine = self.machine(entry_input.machine.as_str());
9095            let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
9096                continue;
9097            };
9098            let action_name = self.entry_input_action_name(entry_input);
9099            let params = variant
9100                .fields
9101                .iter()
9102                .map(|field| format!("arg_{}", tla_ident(&field.name)))
9103                .collect::<Vec<_>>();
9104            let packet_expr = self.input_packet_expr(
9105                entry_input.machine.as_str(),
9106                &entry_input.input_variant,
9107                &variant
9108                    .fields
9109                    .iter()
9110                    .map(|field| {
9111                        (
9112                            field.name.as_str().to_owned(),
9113                            format!("arg_{}", tla_ident(&field.name)),
9114                        )
9115                    })
9116                    .collect::<BTreeMap<String, _>>(),
9117                "entry",
9118                &entry_input.name,
9119                "external_entry",
9120                &entry_input.input_variant,
9121                "0",
9122            );
9123
9124            if params.is_empty() {
9125                pushln!(out, "{} ==", action_name);
9126            } else {
9127                pushln!(out, "{}({}) ==", action_name, params.join(", "));
9128            }
9129            writeln!(
9130                out,
9131                "    /\\ ~({} \\in SeqElements(pending_inputs))",
9132                packet_expr
9133            )
9134            .expect("write to string");
9135            writeln!(out, "    /\\ EntryPacketAdmissible({packet_expr})").expect("write to string");
9136            writeln!(
9137                out,
9138                "    /\\ pending_inputs' = Append(pending_inputs, {})",
9139                packet_expr
9140            )
9141            .expect("write to string");
9142            writeln!(
9143                out,
9144                "    /\\ observed_inputs' = observed_inputs \\cup {{{}}}",
9145                packet_expr
9146            )
9147            .expect("write to string");
9148            writeln!(out, "    /\\ model_step_count' = model_step_count + 1")
9149                .expect("write to string");
9150            {
9151                let mut unchanged = self.machine_vars();
9152                unchanged.extend(self.obligation_vars());
9153                unchanged.extend([
9154                    "pending_routes".into(),
9155                    "delivered_routes".into(),
9156                    "emitted_effects".into(),
9157                    "observed_transitions".into(),
9158                    "witness_current_script_input".into(),
9159                    "witness_remaining_script_inputs".into(),
9160                ]);
9161                self.render_unchanged_vars(out, "    /\\ ", &unchanged);
9162            }
9163            pushln!(out);
9164        }
9165    }
9166
9167    fn render_entry_input_call(&self, entry_input: &EntryInput) -> String {
9168        let machine = self.machine(entry_input.machine.as_str());
9169        let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
9170            return self.entry_input_action_name(entry_input);
9171        };
9172        let action_name = self.entry_input_action_name(entry_input);
9173        if variant.fields.is_empty() {
9174            action_name
9175        } else {
9176            let prefix = variant
9177                .fields
9178                .iter()
9179                .map(|field| {
9180                    let local = format!("arg_{}", tla_ident(&field.name));
9181                    let domain = self.binding_domain_for_type(&field.ty);
9182                    format!("\\E {local} \\in {domain} : ")
9183                })
9184                .collect::<String>();
9185            let args = variant
9186                .fields
9187                .iter()
9188                .map(|field| format!("arg_{}", tla_ident(&field.name)))
9189                .collect::<Vec<_>>()
9190                .join(", ");
9191            format!("{prefix}{action_name}({args})")
9192        }
9193    }
9194
9195    fn render_deliver_queued_route_action(&self, out: &mut String) {
9196        writeln!(out, "DeliverQueuedRoute ==");
9197        pushln!(out, "    /\\ Len(pending_routes) > 0");
9198        pushln!(out, "    /\\ LET route == Head(pending_routes) IN");
9199        pushln!(out, "       /\\ pending_routes' = Tail(pending_routes)");
9200        writeln!(
9201            out,
9202            "       /\\ delivered_routes' = delivered_routes \\cup {{route}}"
9203        )
9204        .expect("write to string");
9205        writeln!(out, "       /\\ model_step_count' = model_step_count + 1")
9206            .expect("write to string");
9207        writeln!(
9208            out,
9209            "       /\\ pending_inputs' = AppendIfMissing(pending_inputs, [machine |-> route.target_machine, variant |-> route.target_input, payload |-> route.payload, source_kind |-> \"route\", source_route |-> route.route, source_machine |-> route.source_machine, source_effect |-> route.effect, effect_id |-> route.effect_id])"
9210        )
9211        .expect("write to string");
9212        writeln!(
9213            out,
9214            "       /\\ observed_inputs' = observed_inputs \\cup {{[machine |-> route.target_machine, variant |-> route.target_input, payload |-> route.payload, source_kind |-> \"route\", source_route |-> route.route, source_machine |-> route.source_machine, source_effect |-> route.effect, effect_id |-> route.effect_id]}}"
9215        )
9216        .expect("write to string");
9217        {
9218            let mut unchanged = self.machine_vars();
9219            unchanged.extend(self.obligation_vars());
9220            unchanged.extend([
9221                "emitted_effects".into(),
9222                "observed_transitions".into(),
9223                "witness_current_script_input".into(),
9224                "witness_remaining_script_inputs".into(),
9225            ]);
9226            self.render_unchanged_vars(out, "       /\\ ", &unchanged);
9227        }
9228        pushln!(out);
9229    }
9230
9231    fn entry_packet_admissibility_name(&self, instance_id: &str) -> String {
9232        format!("EntryPacketAdmissible_{}", tla_ident(instance_id))
9233    }
9234
9235    fn render_entry_packet_admissibility_helpers(
9236        &self,
9237        out: &mut String,
9238    ) -> std::result::Result<(), CompositionTlaError> {
9239        if self.schema.entry_inputs.is_empty()
9240            && !self
9241                .schema
9242                .witnesses
9243                .iter()
9244                .any(|witness| !witness.preload_inputs.is_empty())
9245        {
9246            return Ok(());
9247        }
9248
9249        for instance in &self.schema.machines {
9250            let machine = self.machine(instance.instance_id.as_str());
9251            let helper_prefix = format!("{}__entry_packet__", tla_ident(&instance.instance_id));
9252            let mut compiler = self.instance_compiler(instance.instance_id.as_str(), helper_prefix);
9253
9254            for derived in helper_dependency_order(machine)? {
9255                compiler.render_helper(out, derived);
9256                pushln!(out);
9257            }
9258            if machine.machine.as_str() == "MobMachine" {
9259                compiler.render_mob_machine_native_helpers(out);
9260                pushln!(out);
9261            }
9262            if machine.machine.as_str() == "MeerkatMachine" {
9263                compiler.render_meerkat_machine_native_helpers(out);
9264                pushln!(out);
9265            }
9266            if machine.machine.as_str() == "RuntimeDeliveryMachine" {
9267                compiler.render_runtime_delivery_native_helpers(out);
9268                pushln!(out);
9269            }
9270            if machine.machine.as_str() == "SessionDocumentMachine" {
9271                compiler.render_session_document_native_helpers(out);
9272                pushln!(out);
9273            }
9274
9275            let branches = machine
9276                .transitions
9277                .iter()
9278                .map(|transition| {
9279                    self.render_machine_packet_admissibility_branch(
9280                        &mut compiler,
9281                        instance.instance_id.as_str(),
9282                        transition,
9283                    )
9284                })
9285                .collect::<Vec<_>>();
9286
9287            for helper in &compiler.helper_defs {
9288                pushln!(out, "{helper}");
9289                pushln!(out);
9290            }
9291
9292            writeln!(
9293                out,
9294                "{}(packet) ==",
9295                self.entry_packet_admissibility_name(instance.instance_id.as_str())
9296            )
9297            .expect("write to string");
9298            if branches.is_empty() {
9299                pushln!(out, "    FALSE");
9300            } else {
9301                for branch in &branches {
9302                    pushln!(out, "    \\/ {branch}");
9303                }
9304            }
9305            pushln!(out);
9306        }
9307
9308        writeln!(out, "EntryPacketAdmissible(packet) ==").expect("write to string");
9309        pushln!(out, "    CASE");
9310        for (idx, instance) in self.schema.machines.iter().enumerate() {
9311            let prefix = if idx == 0 { "      " } else { "      [] " };
9312            writeln!(
9313                out,
9314                "{}packet.machine = {} -> {}(packet)",
9315                prefix,
9316                tla_string(&instance.instance_id),
9317                self.entry_packet_admissibility_name(instance.instance_id.as_str())
9318            )
9319            .expect("write to string");
9320        }
9321        pushln!(out, "      [] OTHER -> FALSE");
9322        pushln!(out);
9323        Ok(())
9324    }
9325
9326    fn render_machine_packet_admissibility_branch(
9327        &self,
9328        compiler: &mut MachineTlaCompiler<'_>,
9329        instance_id: &str,
9330        transition: &TransitionSchema,
9331    ) -> String {
9332        let phase_var = self.phase_var(instance_id);
9333        let from_guard = if transition.from.len() == 1 {
9334            format!("{phase_var} = {}", tla_string(&transition.from[0]))
9335        } else {
9336            transition
9337                .from
9338                .iter()
9339                .map(|phase| format!("{phase_var} = {}", tla_string(phase)))
9340                .collect::<Vec<_>>()
9341                .join(" \\/ ")
9342        };
9343
9344        let binding_types = compiler.binding_type_map(transition);
9345        let binding_env = transition
9346            .on
9347            .bindings()
9348            .iter()
9349            .map(|binding| {
9350                (
9351                    binding.as_str().to_owned(),
9352                    format!("packet.payload.{}", tla_ident(binding)),
9353                )
9354            })
9355            .collect::<BTreeMap<_, _>>();
9356        let field_env = self.machine_field_env(instance_id);
9357
9358        let mut clauses = vec![
9359            format!(
9360                "packet.variant = {}",
9361                tla_string(transition.on.variant_str())
9362            ),
9363            from_guard,
9364        ];
9365        clauses.extend(
9366            transition.guards.iter().map(|guard| {
9367                compiler.render_guard(guard, &field_env, &binding_env, &binding_types)
9368            }),
9369        );
9370
9371        format!(
9372            "/\\ {}",
9373            clauses
9374                .into_iter()
9375                .map(|clause| format!("({clause})"))
9376                .collect::<Vec<_>>()
9377                .join(" /\\ ")
9378        )
9379    }
9380
9381    fn render_reject_pending_entry_input_action(&self, out: &mut String) {
9382        if self.schema.entry_inputs.is_empty() {
9383            return;
9384        }
9385
9386        writeln!(out, "RejectPendingEntryInput ==").expect("write to string");
9387        pushln!(out, "    /\\ \\E packet \\in SeqElements(pending_inputs) :");
9388        pushln!(out, "       /\\ packet.source_kind = \"entry\"");
9389        pushln!(out, "       /\\ ~EntryPacketAdmissible(packet)");
9390        pushln!(
9391            out,
9392            "       /\\ pending_inputs' = SeqRemove(pending_inputs, packet)"
9393        );
9394        pushln!(out, "       /\\ observed_inputs' = observed_inputs");
9395        pushln!(out, "       /\\ pending_routes' = pending_routes");
9396        pushln!(out, "       /\\ delivered_routes' = delivered_routes");
9397        pushln!(out, "       /\\ emitted_effects' = emitted_effects");
9398        pushln!(
9399            out,
9400            "       /\\ observed_transitions' = observed_transitions"
9401        );
9402        writeln!(out, "       /\\ model_step_count' = model_step_count + 1")
9403            .expect("write to string");
9404        let mut unchanged = self.machine_vars();
9405        unchanged.extend(self.obligation_vars());
9406        unchanged.extend([
9407            "witness_current_script_input".into(),
9408            "witness_remaining_script_inputs".into(),
9409        ]);
9410        self.render_unchanged_vars(out, "       /\\ ", &unchanged);
9411        pushln!(out);
9412    }
9413
9414    fn render_quiescent_stutter(&self, out: &mut String) {
9415        writeln!(out, "QuiescentStutter ==");
9416        pushln!(out, "    /\\ Len(pending_routes) = 0");
9417        pushln!(out, "    /\\ Len(pending_inputs) = 0");
9418        pushln!(out, "    /\\ UNCHANGED vars");
9419        pushln!(out);
9420    }
9421
9422    fn render_witness_inject_next_call(&self, witness: &CompositionWitness) -> String {
9423        format!("WitnessInjectNext_{}", tla_ident(&witness.name))
9424    }
9425
9426    fn render_witness_satisfied_stutter_call(&self, witness: &CompositionWitness) -> String {
9427        format!("WitnessSatisfiedStutter_{}", tla_ident(&witness.name))
9428    }
9429
9430    fn core_next_branches(&self) -> Vec<String> {
9431        let mut branches = Vec::new();
9432        if !self.schema.routes.is_empty() {
9433            branches.push("DeliverQueuedRoute".into());
9434        }
9435        if !self.schema.entry_inputs.is_empty() {
9436            branches.push("RejectPendingEntryInput".into());
9437        }
9438        for instance in &self.schema.machines {
9439            let machine = self.machine(instance.instance_id.as_str());
9440            for transition in &machine.transitions {
9441                branches
9442                    .push(self.machine_transition_call(instance.instance_id.as_str(), transition));
9443            }
9444        }
9445        branches.extend(self.owner_feedback_branches());
9446        branches.push("QuiescentStutter".into());
9447        branches
9448    }
9449
9450    fn owner_feedback_branches(&self) -> Vec<String> {
9451        self.schema
9452            .handoff_protocols
9453            .iter()
9454            .flat_map(|protocol| {
9455                protocol
9456                    .allowed_feedback_inputs
9457                    .iter()
9458                    .map(move |feedback| self.owner_feedback_action_name(protocol, feedback))
9459            })
9460            .collect()
9461    }
9462
9463    fn owner_feedback_action_name(
9464        &self,
9465        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
9466        feedback: &FeedbackInputRef,
9467    ) -> String {
9468        format!(
9469            "OwnerFeedback_{}_{}",
9470            self.obligation_symbol_suffix(protocol),
9471            tla_ident(&feedback.input_variant)
9472        )
9473    }
9474
9475    fn witness_owner_feedback_branches(&self, witness: &CompositionWitness) -> Vec<String> {
9476        let expected_inputs = witness
9477            .expected_transitions
9478            .iter()
9479            .filter_map(|expected| {
9480                let machine = self.machine_by_instance.get(expected.machine.as_str())?;
9481                let transition = machine
9482                    .transitions
9483                    .iter()
9484                    .find(|transition| transition.name == expected.transition)?;
9485                match &transition.on {
9486                    TriggerMatch::Input { variant, .. } => {
9487                        Some((expected.machine.clone(), variant.clone()))
9488                    }
9489                    TriggerMatch::Signal { .. } => None,
9490                }
9491            })
9492            .collect::<BTreeSet<_>>();
9493
9494        let ordered_predecessor_effects = witness
9495            .expected_transition_order
9496            .iter()
9497            .filter_map(|order| {
9498                let predecessor_machine = self
9499                    .machine_by_instance
9500                    .get(order.earlier.machine.as_str())?;
9501                let predecessor = predecessor_machine
9502                    .transitions
9503                    .iter()
9504                    .find(|transition| transition.name == order.earlier.transition)?;
9505                Some((
9506                    (order.later.machine.clone(), order.later.transition.clone()),
9507                    predecessor
9508                        .emit
9509                        .iter()
9510                        .map(|effect| (order.earlier.machine.clone(), effect.variant.clone()))
9511                        .collect::<BTreeSet<_>>(),
9512                ))
9513            })
9514            .fold(
9515                BTreeMap::<_, BTreeSet<_>>::new(),
9516                |mut effects, (transition, predecessor_effects)| {
9517                    effects
9518                        .entry(transition)
9519                        .or_default()
9520                        .extend(predecessor_effects);
9521                    effects
9522                },
9523            );
9524
9525        self.schema
9526            .handoff_protocols
9527            .iter()
9528            .flat_map(|protocol| {
9529                protocol
9530                    .allowed_feedback_inputs
9531                    .iter()
9532                    .filter_map(|feedback| {
9533                        let input = (
9534                            feedback.machine_instance.clone(),
9535                            feedback.input_variant.clone(),
9536                        );
9537                        if !expected_inputs.contains(&input) {
9538                            return None;
9539                        }
9540                        let receiver_machine = self
9541                            .machine_by_instance
9542                            .get(feedback.machine_instance.as_str())?;
9543                        let receiver = receiver_machine.transitions.iter().find(|transition| {
9544                            matches!(
9545                                &transition.on,
9546                                TriggerMatch::Input { variant, .. }
9547                                    if variant == &feedback.input_variant
9548                            )
9549                        })?;
9550                        let receiver_key =
9551                            (feedback.machine_instance.clone(), receiver.name.clone());
9552                        if let Some(predecessor_effects) =
9553                            ordered_predecessor_effects.get(&receiver_key)
9554                        {
9555                            let producer = (
9556                                protocol.producer_instance.clone(),
9557                                protocol.effect_variant.clone(),
9558                            );
9559                            if !predecessor_effects.contains(&producer) {
9560                                return None;
9561                            }
9562                        }
9563                        Some(self.owner_feedback_action_name(protocol, feedback))
9564                    })
9565            })
9566            .collect::<BTreeSet<_>>()
9567            .into_iter()
9568            .collect()
9569    }
9570
9571    fn witness_next_branches(
9572        &self,
9573        witness: &CompositionWitness,
9574    ) -> Result<Vec<String>, CompositionTlaError> {
9575        if !Self::witness_has_explicit_progress(witness) {
9576            let mut branches = vec!["CoreNext".into()];
9577            branches.push(self.render_witness_satisfied_stutter_call(witness));
9578            return Ok(branches);
9579        }
9580        let mut branches = self.witness_progress_branches(witness)?;
9581        branches.push(self.render_witness_satisfied_stutter_call(witness));
9582        Ok(branches)
9583    }
9584
9585    fn witness_progress_branches(
9586        &self,
9587        witness: &CompositionWitness,
9588    ) -> Result<Vec<String>, CompositionTlaError> {
9589        let mut branches = Vec::new();
9590        if !witness.expected_routes.is_empty() {
9591            branches.push("DeliverQueuedRoute".into());
9592        }
9593        for expected in &witness.expected_transitions {
9594            branches.push(self.witness_transition_call(witness, expected)?);
9595        }
9596        branches.extend(self.witness_owner_feedback_branches(witness));
9597        Ok(branches)
9598    }
9599
9600    fn witness_transition_call(
9601        &self,
9602        witness: &CompositionWitness,
9603        expected: &meerkat_machine_schema::CompositionWitnessTransition,
9604    ) -> Result<String, CompositionTlaError> {
9605        let machine = self
9606            .machine_by_instance
9607            .get(expected.machine.as_str())
9608            .ok_or_else(|| CompositionTlaError::UnknownWitnessMachine {
9609                composition: self.schema.name.to_string(),
9610                witness: witness.name.to_string(),
9611                machine: expected.machine.to_string(),
9612            })?;
9613        let transition = machine
9614            .transitions
9615            .iter()
9616            .find(|transition| transition.name == expected.transition)
9617            .ok_or_else(|| CompositionTlaError::UnknownWitnessTransition {
9618                composition: self.schema.name.to_string(),
9619                witness: witness.name.to_string(),
9620                machine: expected.machine.to_string(),
9621                transition: expected.transition.to_string(),
9622            })?;
9623        if transition.on.bindings().is_empty() {
9624            return Ok(self.machine_transition_name(expected.machine.as_str(), transition));
9625        }
9626        // A scripted witness supplies exact typed packets. Sampling the ordinary
9627        // exploration domains again can make those packets impossible to consume
9628        // (for example, revisions 3 and 4 outside the bounded 0..2 sample).
9629        // Reuse the same guarded action with the queued payload, without changing
9630        // ordinary exploration bounds or bypassing action admission checks.
9631        let args = transition
9632            .on
9633            .bindings()
9634            .iter()
9635            .map(|binding| format!("witness_packet.payload.{}", tla_ident(binding)))
9636            .collect::<Vec<_>>()
9637            .join(", ");
9638        Ok(format!(
9639            "\\E witness_packet \\in SeqElements(pending_inputs) : /\\ witness_packet.machine = {} /\\ witness_packet.variant = {} /\\ {}({args})",
9640            tla_string(expected.machine.as_str()),
9641            tla_string(transition.on.variant_str()),
9642            self.machine_transition_name(expected.machine.as_str(), transition),
9643        ))
9644    }
9645
9646    fn witness_fairness_clauses(
9647        &self,
9648        witness: &CompositionWitness,
9649    ) -> Result<Vec<String>, CompositionTlaError> {
9650        if Self::witness_has_explicit_progress(witness) {
9651            return Ok(Vec::new());
9652        }
9653
9654        let mut clauses = self.core_fairness_clauses();
9655        if witness.preload_inputs.len() > 1 {
9656            clauses.push(self.render_witness_inject_next_call(witness));
9657        }
9658        Ok(clauses)
9659    }
9660
9661    fn core_fairness_clauses(&self) -> Vec<String> {
9662        let mut clauses = Vec::new();
9663        if !self.schema.routes.is_empty() {
9664            clauses.push("DeliverQueuedRoute".into());
9665        }
9666        if !self.schema.entry_inputs.is_empty() {
9667            clauses.push("RejectPendingEntryInput".into());
9668        }
9669        clauses.extend(self.schema.machines.iter().flat_map(|instance| {
9670            let machine = self.machine(instance.instance_id.as_str());
9671            machine
9672                .transitions
9673                .iter()
9674                .map(|transition| {
9675                    self.machine_transition_call(instance.instance_id.as_str(), transition)
9676                })
9677                .collect::<Vec<_>>()
9678        }));
9679        clauses
9680    }
9681
9682    fn witness_has_explicit_progress(witness: &CompositionWitness) -> bool {
9683        !witness.preload_inputs.is_empty() || !witness.expected_transitions.is_empty()
9684    }
9685
9686    fn entry_input_action_name(&self, entry_input: &EntryInput) -> String {
9687        format!("Inject_{}", tla_ident(&entry_input.name))
9688    }
9689
9690    fn input_packet_expr(
9691        &self,
9692        machine_id: impl AsRef<str>,
9693        input_variant: impl AsRef<str>,
9694        payload_fields: &BTreeMap<String, String>,
9695        source_kind: impl AsRef<str>,
9696        source_route: impl AsRef<str>,
9697        source_machine: impl AsRef<str>,
9698        source_effect: impl AsRef<str>,
9699        effect_id: impl AsRef<str>,
9700    ) -> String {
9701        format!(
9702            "[machine |-> {}, variant |-> {}, payload |-> {}, source_kind |-> {}, source_route |-> {}, source_machine |-> {}, source_effect |-> {}, effect_id |-> {}]",
9703            tla_string(machine_id),
9704            tla_string(input_variant),
9705            self.payload_record_expr(payload_fields),
9706            tla_string(source_kind),
9707            tla_string(source_route),
9708            tla_string(source_machine),
9709            tla_string(source_effect),
9710            effect_id.as_ref()
9711        )
9712    }
9713
9714    fn input_packet_expr_from_payload_expr(
9715        &self,
9716        machine_id: impl AsRef<str>,
9717        input_variant: impl AsRef<str>,
9718        payload_expr: &str,
9719        source_kind: impl AsRef<str>,
9720        source_route: impl AsRef<str>,
9721        source_machine: impl AsRef<str>,
9722        source_effect: impl AsRef<str>,
9723        effect_id: impl AsRef<str>,
9724    ) -> String {
9725        format!(
9726            "[machine |-> {}, variant |-> {}, payload |-> {}, source_kind |-> {}, source_route |-> {}, source_machine |-> {}, source_effect |-> {}, effect_id |-> {}]",
9727            tla_string(machine_id),
9728            tla_string(input_variant),
9729            payload_expr,
9730            tla_string(source_kind),
9731            tla_string(source_route),
9732            tla_string(source_machine),
9733            tla_string(source_effect),
9734            effect_id.as_ref()
9735        )
9736    }
9737
9738    fn payload_record_expr(&self, payload_fields: &BTreeMap<String, String>) -> String {
9739        if payload_fields.is_empty() {
9740            "[tag |-> \"unit\"]".into()
9741        } else {
9742            format!(
9743                "[{}]",
9744                payload_fields
9745                    .iter()
9746                    .map(|(field, expr)| format!("{field} |-> {expr}"))
9747                    .collect::<Vec<_>>()
9748                    .join(", ")
9749            )
9750        }
9751    }
9752
9753    fn witness_packet_exprs(&self, witness: &CompositionWitness) -> Vec<String> {
9754        witness
9755            .preload_inputs
9756            .iter()
9757            .enumerate()
9758            .map(|(idx, packet)| {
9759                let payload_fields = packet
9760                    .fields
9761                    .iter()
9762                    .map(|field| {
9763                        (
9764                            field.field.as_str().to_owned(),
9765                            self.render_literal_expr(&field.expr),
9766                        )
9767                    })
9768                    .collect::<BTreeMap<String, _>>();
9769                self.input_packet_expr(
9770                    packet.machine.as_str(),
9771                    packet.input_variant.as_str(),
9772                    &payload_fields,
9773                    "entry",
9774                    format!("witness:{}:{}", witness.name, idx + 1),
9775                    "external_entry",
9776                    &packet.input_variant,
9777                    "0",
9778                )
9779            })
9780            .collect()
9781    }
9782
9783    fn witness_initial_batch_size(&self, witness: &CompositionWitness) -> usize {
9784        if witness.expected_scheduler_rules.is_empty() {
9785            1
9786        } else {
9787            witness.preload_inputs.len().min(2).max(1)
9788        }
9789    }
9790
9791    fn witness_initial_observed_inputs_expr(&self, witness: &CompositionWitness) -> String {
9792        let packets = self.witness_packet_exprs(witness);
9793        let batch_size = self.witness_initial_batch_size(witness);
9794        if packets.is_empty() {
9795            "{}".into()
9796        } else {
9797            format!(
9798                "{{{}}}",
9799                packets
9800                    .into_iter()
9801                    .take(batch_size)
9802                    .collect::<Vec<_>>()
9803                    .join(", ")
9804            )
9805        }
9806    }
9807
9808    fn witness_initial_pending_inputs_expr(&self, witness: &CompositionWitness) -> String {
9809        let packets = self.witness_packet_exprs(witness);
9810        let batch_size = self.witness_initial_batch_size(witness);
9811        if packets.is_empty() {
9812            "<<>>".into()
9813        } else {
9814            format!(
9815                "<<{}>>",
9816                packets
9817                    .into_iter()
9818                    .take(batch_size)
9819                    .collect::<Vec<_>>()
9820                    .join(", ")
9821            )
9822        }
9823    }
9824
9825    fn witness_current_script_input_expr(&self, witness: &CompositionWitness) -> String {
9826        let packets = self.witness_packet_exprs(witness);
9827        let batch_size = self.witness_initial_batch_size(witness);
9828        packets
9829            .into_iter()
9830            .take(batch_size)
9831            .last()
9832            .unwrap_or_else(|| "None".into())
9833    }
9834
9835    fn witness_remaining_script_inputs_expr(&self, witness: &CompositionWitness) -> String {
9836        let packets = self.witness_packet_exprs(witness);
9837        let batch_size = self.witness_initial_batch_size(witness);
9838        if packets.len() <= batch_size {
9839            return "<<>>".into();
9840        }
9841
9842        format!(
9843            "<<{}>>",
9844            packets
9845                .into_iter()
9846                .skip(batch_size)
9847                .collect::<Vec<_>>()
9848                .join(", ")
9849        )
9850    }
9851
9852    fn render_witness_inject_actions(&self, out: &mut String) {
9853        for witness in &self.schema.witnesses {
9854            let action_name = self.render_witness_inject_next_call(witness);
9855            pushln!(out, "{action_name} ==");
9856            if witness.preload_inputs.len() <= 1 {
9857                pushln!(out, "    FALSE");
9858                pushln!(out);
9859                continue;
9860            }
9861
9862            pushln!(
9863                out,
9864                "    LET next_script_input == IF Len(witness_remaining_script_inputs) > 0 THEN Head(witness_remaining_script_inputs) ELSE witness_current_script_input"
9865            );
9866            pushln!(
9867                out,
9868                "        next_remaining_script_inputs == IF Len(witness_remaining_script_inputs) > 0 THEN Tail(witness_remaining_script_inputs) ELSE <<>>"
9869            );
9870            pushln!(out, "    IN");
9871            pushln!(out, "    /\\ witness_current_script_input # None");
9872            writeln!(
9873                out,
9874                "    /\\ ~(witness_current_script_input \\in SeqElements(pending_inputs))"
9875            )
9876            .expect("write to string");
9877            pushln!(out, "    /\\ EntryPacketAdmissible(next_script_input)");
9878            pushln!(out, "    /\\ Len(pending_inputs) = 0");
9879            pushln!(out, "    /\\ Len(pending_routes) = 0");
9880            pushln!(out, "    /\\ Len(witness_remaining_script_inputs) > 0");
9881            writeln!(
9882                out,
9883                "    /\\ pending_inputs' = Append(pending_inputs, next_script_input)"
9884            )
9885            .expect("write to string");
9886            writeln!(
9887                out,
9888                "    /\\ observed_inputs' = observed_inputs \\cup {{next_script_input}}"
9889            )
9890            .expect("write to string");
9891            writeln!(
9892                out,
9893                "    /\\ witness_current_script_input' = next_script_input"
9894            )
9895            .expect("write to string");
9896            writeln!(
9897                out,
9898                "    /\\ witness_remaining_script_inputs' = next_remaining_script_inputs"
9899            )
9900            .expect("write to string");
9901            writeln!(out, "    /\\ model_step_count' = model_step_count + 1")
9902                .expect("write to string");
9903            {
9904                let mut unchanged = self.machine_vars();
9905                unchanged.extend(self.obligation_vars());
9906                unchanged.extend([
9907                    "pending_routes".into(),
9908                    "delivered_routes".into(),
9909                    "emitted_effects".into(),
9910                    "observed_transitions".into(),
9911                ]);
9912                self.render_unchanged_vars(out, "    /\\ ", &unchanged);
9913            }
9914            pushln!(out);
9915        }
9916    }
9917
9918    fn render_witness_satisfied_stutter_actions(&self, out: &mut String) {
9919        for witness in &self.schema.witnesses {
9920            let action_name = self.render_witness_satisfied_stutter_call(witness);
9921            pushln!(out, "{action_name} ==");
9922            let mut conditions = self.witness_satisfaction_conditions(witness);
9923            if Self::witness_has_explicit_progress(witness) {
9924                conditions.insert(0, composition_witness_completion_name(&witness.name));
9925            }
9926            if conditions.is_empty() {
9927                pushln!(out, "    /\\ FALSE");
9928            } else {
9929                for condition in conditions {
9930                    pushln!(out, "    /\\ {condition}");
9931                }
9932                pushln!(out, "    /\\ UNCHANGED vars");
9933            }
9934            pushln!(out);
9935        }
9936    }
9937
9938    fn render_witness_completion_operators(&self, out: &mut String) {
9939        for witness in &self.schema.witnesses {
9940            if !Self::witness_has_explicit_progress(witness) {
9941                continue;
9942            }
9943            writeln!(
9944                out,
9945                "{} ==",
9946                composition_witness_completion_name(&witness.name)
9947            )
9948            .expect("write to string");
9949            pushln!(out, "    /\\ Len(witness_remaining_script_inputs) = 0");
9950            pushln!(
9951                out,
9952                "    /\\ ~(witness_current_script_input \\in SeqElements(pending_inputs))"
9953            );
9954            pushln!(out, "    /\\ Len(pending_routes) = 0");
9955            for condition in self.witness_satisfaction_conditions(witness) {
9956                pushln!(out, "    /\\ {condition}");
9957            }
9958            pushln!(out);
9959        }
9960    }
9961
9962    fn render_witness_action_constraint_operators(&self, out: &mut String) {
9963        for witness in &self.schema.witnesses {
9964            if !Self::witness_has_explicit_progress(witness) {
9965                continue;
9966            }
9967            writeln!(
9968                out,
9969                "{} ==",
9970                composition_witness_action_constraint_name(&witness.name)
9971            )
9972            .expect("write to string");
9973            writeln!(
9974                out,
9975                "    \\/ {}",
9976                composition_witness_completion_name(&witness.name)
9977            )
9978            .expect("write to string");
9979            pushln!(out, "    \\/ model_step_count' # model_step_count");
9980            pushln!(out);
9981        }
9982    }
9983
9984    fn witness_satisfaction_conditions(&self, witness: &CompositionWitness) -> Vec<String> {
9985        let mut conditions = Vec::new();
9986        conditions.extend(witness.expected_routes.iter().map(|route| {
9987            format!(
9988                "\\E packet \\in delivered_routes : packet.route = {}",
9989                tla_string(route)
9990            )
9991        }));
9992        conditions.extend(
9993            witness
9994                .expected_scheduler_rules
9995                .iter()
9996                .map(render_scheduler_trigger_formula),
9997        );
9998        conditions.extend(
9999            witness
10000                .expected_states
10001                .iter()
10002                .map(|state| format!("({})", self.render_witness_state_formula(state))),
10003        );
10004        conditions.extend(
10005            witness.expected_transitions.iter().map(|transition| {
10006                format!("({})", self.render_witness_transition_formula(transition))
10007            }),
10008        );
10009        conditions.extend(
10010            witness
10011                .expected_transition_order
10012                .iter()
10013                .map(|order| format!("({})", self.render_witness_transition_order_formula(order))),
10014        );
10015        conditions
10016    }
10017
10018    fn render_witness_obligation_formula(
10019        &self,
10020        witness: &CompositionWitness,
10021        formula: String,
10022    ) -> String {
10023        if Self::witness_has_explicit_progress(witness) {
10024            format!(
10025                "{} => ({formula})",
10026                composition_witness_completion_name(&witness.name)
10027            )
10028        } else {
10029            format!("<> ({formula})")
10030        }
10031    }
10032
10033    fn render_literal_expr(&self, expr: &Expr) -> String {
10034        match expr {
10035            Expr::Bool(value) => {
10036                if *value {
10037                    "TRUE".into()
10038                } else {
10039                    "FALSE".into()
10040                }
10041            }
10042            Expr::U64(value) => value.to_string(),
10043            Expr::U64Max => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
10044            Expr::String(value) => tla_string(value),
10045            Expr::NamedVariant { enum_name, variant } => render_named_variant_value(
10046                enum_name.as_str(),
10047                variant.as_str(),
10048                &self.named_bindings,
10049            ),
10050            Expr::None => "None".into(),
10051            Expr::Some(inner) => format!("Some({})", self.render_literal_expr(inner)),
10052            Expr::SeqLiteral(items) => {
10053                let rendered = items
10054                    .iter()
10055                    .map(|item| self.render_literal_expr(item))
10056                    .collect::<Vec<_>>()
10057                    .join(", ");
10058                format!("<<{rendered}>>")
10059            }
10060            Expr::EmptySet => "{}".into(),
10061            Expr::EmptyMap => "<< >>".into(),
10062            // A populated map literal (witness inputs, manifests) as a TLC
10063            // function; never the `None` fallback below.
10064            Expr::MapLiteral(entries) => {
10065                let rendered = entries
10066                    .iter()
10067                    .map(|(key, value)| {
10068                        format!(
10069                            "{} :> {}",
10070                            self.render_literal_expr(key),
10071                            self.render_literal_expr(value)
10072                        )
10073                    })
10074                    .collect::<Vec<_>>()
10075                    .join(" @@ ");
10076                format!("({rendered})")
10077            }
10078            _ => "None".into(),
10079        }
10080    }
10081
10082    fn render_witness_state_formula(
10083        &self,
10084        state: &meerkat_machine_schema::CompositionWitnessState,
10085    ) -> String {
10086        let mut clauses = Vec::new();
10087        if let Some(phase) = &state.phase {
10088            clauses.push(format!(
10089                "{} = {}",
10090                self.phase_var(&state.machine),
10091                tla_string(phase)
10092            ));
10093        }
10094        for field in &state.fields {
10095            clauses.push(format!(
10096                "{} = {}",
10097                self.field_var(&state.machine, &field.field),
10098                self.render_literal_expr(&field.expr)
10099            ));
10100        }
10101        if clauses.is_empty() {
10102            "TRUE".into()
10103        } else {
10104            clauses.join(" /\\ ")
10105        }
10106    }
10107
10108    fn render_witness_transition_formula(
10109        &self,
10110        transition: &meerkat_machine_schema::CompositionWitnessTransition,
10111    ) -> String {
10112        format!(
10113            "\\E packet \\in observed_transitions : /\\ packet.machine = {} /\\ packet.transition = {}",
10114            tla_string(&transition.machine),
10115            tla_string(&transition.transition)
10116        )
10117    }
10118
10119    fn render_witness_transition_order_formula(
10120        &self,
10121        ordering: &meerkat_machine_schema::CompositionWitnessTransitionOrder,
10122    ) -> String {
10123        format!(
10124            "\\E earlier \\in observed_transitions, later \\in observed_transitions : /\\ earlier.machine = {} /\\ earlier.transition = {} /\\ later.machine = {} /\\ later.transition = {} /\\ earlier.step < later.step",
10125            tla_string(&ordering.earlier.machine),
10126            tla_string(&ordering.earlier.transition),
10127            tla_string(&ordering.later.machine),
10128            tla_string(&ordering.later.transition),
10129        )
10130    }
10131
10132    fn route_packet_expr(
10133        &self,
10134        route_name: impl AsRef<str>,
10135        from_machine: impl AsRef<str>,
10136        effect_variant: impl AsRef<str>,
10137        to_machine: impl AsRef<str>,
10138        to_input_variant: impl AsRef<str>,
10139        payload_expr: &str,
10140        effect_id_expr: &str,
10141        source_transition: impl AsRef<str>,
10142    ) -> String {
10143        let to_machine = to_machine.as_ref();
10144        format!(
10145            "[route |-> {}, source_machine |-> {}, effect |-> {}, target_machine |-> {}, target_input |-> {}, payload |-> {}, actor |-> {}, effect_id |-> {}, source_transition |-> {}]",
10146            tla_string(route_name),
10147            tla_string(from_machine),
10148            tla_string(effect_variant),
10149            tla_string(to_machine),
10150            tla_string(to_input_variant),
10151            payload_expr,
10152            tla_string(self.actor(to_machine)),
10153            effect_id_expr,
10154            tla_string(source_transition)
10155        )
10156    }
10157
10158    fn render_machine_transition_action(
10159        &self,
10160        compiler: &mut MachineTlaCompiler<'_>,
10161        instance_id: &str,
10162        transition: &TransitionSchema,
10163        out: &mut String,
10164    ) -> std::result::Result<(), CompositionTlaError> {
10165        let machine = self.machine(instance_id);
10166        let action_name = self.machine_transition_name(instance_id, transition);
10167        let binding_types = compiler.binding_type_map(transition);
10168        let binding_env = transition
10169            .on
10170            .bindings()
10171            .iter()
10172            .map(|binding| {
10173                (
10174                    binding.as_str().to_owned(),
10175                    format!("packet.payload.{}", tla_ident(binding)),
10176                )
10177            })
10178            .collect::<BTreeMap<String, _>>();
10179        let params = transition
10180            .on
10181            .bindings()
10182            .iter()
10183            .map(|binding| format!("arg_{}", tla_ident(binding)))
10184            .collect::<Vec<_>>();
10185
10186        if params.is_empty() {
10187            writeln!(out, "{} ==", action_name);
10188        } else {
10189            pushln!(out, "{}({}) ==", action_name, params.join(", "));
10190        }
10191
10192        let phase_var = self.phase_var(instance_id);
10193        let from_guard = if transition.from.len() == 1 {
10194            format!("{} = {}", phase_var, tla_string(&transition.from[0]))
10195        } else {
10196            transition
10197                .from
10198                .iter()
10199                .map(|phase| format!("{} = {}", phase_var, tla_string(phase)))
10200                .collect::<Vec<_>>()
10201                .join(" \\/ ")
10202        };
10203
10204        pushln!(out, "    /\\ \\E packet \\in SeqElements(pending_inputs) :");
10205        writeln!(
10206            out,
10207            "       /\\ packet.machine = {}",
10208            tla_string(instance_id)
10209        )
10210        .expect("write to string");
10211        writeln!(
10212            out,
10213            "       /\\ packet.variant = {}",
10214            tla_string(transition.on.variant_str())
10215        )
10216        .expect("write to string");
10217        for binding in transition.on.bindings() {
10218            let arg_name = format!("arg_{}", tla_ident(binding));
10219            writeln!(
10220                out,
10221                "       /\\ packet.payload.{} = {}",
10222                tla_ident(binding),
10223                arg_name
10224            )
10225            .expect("write to string");
10226        }
10227        writeln!(
10228            out,
10229            "       /\\ ~HigherPriorityReady({})",
10230            tla_string(self.actor(instance_id))
10231        )
10232        .expect("write to string");
10233        writeln!(out, "       /\\ {}", from_guard);
10234
10235        let field_env = self.machine_field_env(instance_id);
10236        for guard in &transition.guards {
10237            writeln!(
10238                out,
10239                "       /\\ {}",
10240                compiler.render_guard(guard, &field_env, &binding_env, &binding_types)
10241            )
10242            .expect("write to string");
10243        }
10244
10245        let next_env = compiler.compile_updates(
10246            &action_name,
10247            &field_env,
10248            &binding_env,
10249            &binding_types,
10250            &transition.updates,
10251        );
10252        let effect_id_expr = "(model_step_count + 1)".to_string();
10253        let current_phase_symbol = compiler.phase_symbol.clone();
10254        compiler.phase_symbol = Some(tla_string(&transition.to));
10255        let effect_packets = transition
10256            .emit
10257            .iter()
10258            .map(|effect| {
10259                let payload_fields = effect
10260                    .fields
10261                    .iter()
10262                    .map(|(field, expr)| {
10263                        (
10264                            field.as_str().to_owned(),
10265                            compiler.render_expr_with_types(
10266                                expr,
10267                                &next_env,
10268                                &binding_env,
10269                                &binding_types,
10270                            ),
10271                        )
10272                    })
10273                    .collect::<BTreeMap<String, _>>();
10274                (
10275                    effect.variant.as_str().to_owned(),
10276                    format!(
10277                        "[machine |-> {}, variant |-> {}, payload |-> {}, effect_id |-> {}, source_transition |-> {}]",
10278                        tla_string(instance_id),
10279                        tla_string(&effect.variant),
10280                        self.payload_record_expr(&payload_fields),
10281                        effect_id_expr,
10282                        tla_string(&transition.name)
10283                    ),
10284                    payload_fields,
10285                )
10286            })
10287            .collect::<Vec<_>>();
10288        compiler.phase_symbol = current_phase_symbol;
10289
10290        let mut queued_route_packets = Vec::new();
10291        let mut immediate_route_packets = Vec::new();
10292        let mut owner_route_quantifiers = Vec::new();
10293        for (effect_variant, _effect_packet, payload_fields) in &effect_packets {
10294            for route in self.schema.routes.iter().filter(|route| {
10295                route.from_machine.as_str() == instance_id
10296                    && route.effect_variant.as_str() == effect_variant.as_str()
10297            }) {
10298                let (target_payload, route_owner_quantifiers) = self.target_payload_for_route(
10299                    machine,
10300                    effect_variant,
10301                    payload_fields,
10302                    route,
10303                    compiler,
10304                    &next_env,
10305                    &binding_env,
10306                    &binding_types,
10307                );
10308                for quantifier in route_owner_quantifiers {
10309                    if !owner_route_quantifiers.contains(&quantifier) {
10310                        owner_route_quantifiers.push(quantifier);
10311                    }
10312                }
10313                let route_packet = self.route_packet_expr(
10314                    &route.name,
10315                    instance_id,
10316                    effect_variant,
10317                    &route.to.machine,
10318                    &route.to.input_variant,
10319                    &target_payload,
10320                    &effect_id_expr,
10321                    &transition.name,
10322                );
10323                match route.delivery {
10324                    RouteDelivery::Enqueue => {
10325                        queued_route_packets.push((route_packet, target_payload))
10326                    }
10327                    RouteDelivery::Immediate => immediate_route_packets.push((
10328                        route_packet,
10329                        self.input_packet_expr_from_payload_expr(
10330                            &route.to.machine,
10331                            &route.to.input_variant,
10332                            &target_payload,
10333                            "route",
10334                            &route.name,
10335                            instance_id,
10336                            effect_variant,
10337                            &effect_id_expr,
10338                        ),
10339                    )),
10340                }
10341            }
10342        }
10343
10344        writeln!(
10345            out,
10346            "       /\\ {}' = {}",
10347            phase_var,
10348            tla_string(&transition.to)
10349        )
10350        .expect("write to string");
10351        let touched = machine
10352            .state
10353            .fields
10354            .iter()
10355            .filter_map(|field| {
10356                let next = next_env.get(field.name.as_str())?;
10357                if field_env
10358                    .get(field.name.as_str())
10359                    .is_some_and(|current| next != current)
10360                {
10361                    Some((field.name.as_str(), next.as_str()))
10362                } else {
10363                    None
10364                }
10365            })
10366            .collect::<Vec<_>>();
10367        for (field, expr) in &touched {
10368            writeln!(
10369                out,
10370                "       /\\ {}' = {}",
10371                self.field_var(instance_id, field),
10372                expr
10373            )
10374            .expect("write to string");
10375        }
10376
10377        let mut unchanged_machine_vars = Vec::new();
10378        for instance in &self.schema.machines {
10379            if instance.instance_id.as_str() == instance_id {
10380                for field in &machine.state.fields {
10381                    if !touched.iter().any(|(name, _)| *name == field.name.as_str()) {
10382                        unchanged_machine_vars
10383                            .push(self.field_var(instance_id, field.name.as_str()));
10384                    }
10385                }
10386            } else {
10387                unchanged_machine_vars.push(self.phase_var(instance.instance_id.as_str()));
10388                let other_machine = self.machine(instance.instance_id.as_str());
10389                for field in &other_machine.state.fields {
10390                    unchanged_machine_vars
10391                        .push(self.field_var(instance.instance_id.as_str(), field.name.as_str()));
10392                }
10393            }
10394        }
10395
10396        unchanged_machine_vars.push("witness_current_script_input".into());
10397        unchanged_machine_vars.push("witness_remaining_script_inputs".into());
10398
10399        if !unchanged_machine_vars.is_empty() {
10400            self.render_unchanged_vars(out, "       /\\ ", &unchanged_machine_vars);
10401        }
10402
10403        let pending_inputs_next = self.append_if_missing_chain(
10404            format!("SeqRemove(pending_inputs, packet)"),
10405            &immediate_route_packets
10406                .iter()
10407                .map(|(_, input_packet)| input_packet)
10408                .cloned()
10409                .collect::<Vec<_>>(),
10410        );
10411        let pending_routes_next = self.append_if_missing_chain(
10412            "pending_routes".into(),
10413            &queued_route_packets
10414                .iter()
10415                .map(|(route_packet, _)| route_packet)
10416                .cloned()
10417                .collect::<Vec<_>>(),
10418        );
10419        let delivered_routes_next = if immediate_route_packets.is_empty() {
10420            "delivered_routes".into()
10421        } else {
10422            format!(
10423                "delivered_routes \\cup {{ {} }}",
10424                immediate_route_packets
10425                    .iter()
10426                    .map(|(route_packet, _)| route_packet)
10427                    .cloned()
10428                    .collect::<Vec<_>>()
10429                    .join(", ")
10430            )
10431        };
10432        let observed_inputs_next = {
10433            let immediate_inputs = immediate_route_packets
10434                .iter()
10435                .map(|(_, input_packet)| input_packet)
10436                .cloned()
10437                .collect::<Vec<_>>();
10438            self.union_set_items("observed_inputs".into(), &immediate_inputs)
10439        };
10440        let emitted_effects_next = if effect_packets.is_empty() {
10441            "emitted_effects".into()
10442        } else {
10443            format!(
10444                "emitted_effects \\cup {{ {} }}",
10445                effect_packets
10446                    .iter()
10447                    .map(|(_, effect_packet, _)| effect_packet)
10448                    .cloned()
10449                    .collect::<Vec<_>>()
10450                    .join(", ")
10451            )
10452        };
10453        let observed_transitions_next = format!(
10454            "observed_transitions \\cup {{{}}}",
10455            self.transition_packet_expr(instance_id, transition)
10456        );
10457
10458        // Compute obligation set updates: when a transition emits an effect
10459        // that matches a handoff_protocol, add a record to the obligation set
10460        // with the protocol's declared obligation fields from the effect payload.
10461        let mut obligation_updates: BTreeMap<String, String> = BTreeMap::new();
10462        for (effect_variant, _effect_packet, payload_fields) in &effect_packets {
10463            for protocol in &self.schema.handoff_protocols {
10464                if protocol.producer_instance.as_str() == instance_id
10465                    && protocol.effect_variant.as_str() == effect_variant.as_str()
10466                {
10467                    let var = self.obligation_var(protocol);
10468                    let mut record_fields: Vec<String> =
10469                        Vec::with_capacity(protocol.obligation_fields.len() + 1);
10470                    record_fields.push("effect_id |-> (model_step_count + 1)".to_string());
10471                    for field in &protocol.obligation_fields {
10472                        let tla_field = tla_ident(field);
10473                        // Fail closed: an obligation field that is absent from
10474                        // the matching effect's payload used to be papered over
10475                        // with an `"unknown_<field>"` sentinel literal.
10476                        let value =
10477                            payload_fields.get(field.as_str()).cloned().ok_or_else(|| {
10478                                CompositionTlaError::UnknownObligationField {
10479                                    composition: self.schema.name.as_str().to_owned(),
10480                                    protocol: protocol.name.as_str().to_owned(),
10481                                    effect: effect_variant.clone(),
10482                                    field: field.as_str().to_owned(),
10483                                }
10484                            })?;
10485                        record_fields.push(format!("{} |-> {}", tla_field, value));
10486                    }
10487                    let record = if record_fields.is_empty() {
10488                        "\"token\"".to_string()
10489                    } else {
10490                        format!("[{}]", record_fields.join(", "))
10491                    };
10492                    obligation_updates.insert(var.clone(), format!("{} \\cup {{{}}}", var, record));
10493                }
10494            }
10495        }
10496
10497        let route_update_prefix = if owner_route_quantifiers.is_empty() {
10498            "       /\\"
10499        } else {
10500            writeln!(
10501                out,
10502                "       /\\ \\E {} :",
10503                owner_route_quantifiers.join(", ")
10504            )
10505            .expect("write to string");
10506            "           /\\"
10507        };
10508        writeln!(
10509            out,
10510            "{route_update_prefix} pending_inputs' = {pending_inputs_next}"
10511        )
10512        .expect("write to string");
10513        writeln!(
10514            out,
10515            "{route_update_prefix} observed_inputs' = {observed_inputs_next}"
10516        )
10517        .expect("write to string");
10518        writeln!(
10519            out,
10520            "{route_update_prefix} pending_routes' = {pending_routes_next}"
10521        )
10522        .expect("write to string");
10523        writeln!(
10524            out,
10525            "{route_update_prefix} delivered_routes' = {delivered_routes_next}"
10526        )
10527        .expect("write to string");
10528        writeln!(
10529            out,
10530            "{route_update_prefix} emitted_effects' = {emitted_effects_next}"
10531        )
10532        .expect("write to string");
10533        writeln!(
10534            out,
10535            "{route_update_prefix} observed_transitions' = {observed_transitions_next}"
10536        )
10537        .expect("write to string");
10538        // Write obligation variable updates — touched protocols get \cup, untouched get UNCHANGED
10539        let all_obligation_vars = self.obligation_vars();
10540        let mut unchanged_obligation_vars = Vec::new();
10541        for ovar in &all_obligation_vars {
10542            if let Some(next_expr) = obligation_updates.get(ovar) {
10543                writeln!(out, "{route_update_prefix} {}' = {}", ovar, next_expr)
10544                    .expect("write to string");
10545            } else {
10546                unchanged_obligation_vars.push(ovar.clone());
10547            }
10548        }
10549        if !unchanged_obligation_vars.is_empty() {
10550            let unchanged_prefix = format!("{route_update_prefix} ");
10551            self.render_unchanged_vars(out, &unchanged_prefix, &unchanged_obligation_vars);
10552        }
10553        writeln!(
10554            out,
10555            "{route_update_prefix} model_step_count' = model_step_count + 1"
10556        )
10557        .expect("write to string");
10558        Ok(())
10559    }
10560
10561    fn target_payload_for_route(
10562        &self,
10563        source_machine: &MachineSchema,
10564        effect_variant: &str,
10565        effect_payload_fields: &BTreeMap<String, String>,
10566        route: &Route,
10567        compiler: &MachineTlaCompiler<'_>,
10568        next_env: &BTreeMap<String, String>,
10569        binding_env: &BTreeMap<String, String>,
10570        binding_types: &BTreeMap<String, TypeRef>,
10571    ) -> (String, Vec<String>) {
10572        let target_machine = self.machine(route.to.machine.as_str());
10573        let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
10574            return (String::new(), Vec::new());
10575        };
10576        let Ok(source_effect_variant) = source_machine.effects.variant_named(effect_variant) else {
10577            return (String::new(), Vec::new());
10578        };
10579        let mut owner_context_quantifiers = Vec::new();
10580        let bindings = route
10581            .bindings
10582            .iter()
10583            .map(|binding| {
10584                let expr = match &binding.source {
10585                    RouteBindingSource::Field {
10586                        from_field,
10587                        allow_named_alias: _,
10588                    } => effect_payload_fields
10589                        .get(from_field.as_str())
10590                        .cloned()
10591                        .or_else(|| {
10592                            source_effect_variant
10593                                .fields
10594                                .iter()
10595                                .find(|field| field.name == *from_field)
10596                                .map(|_| format!("packet.payload.{}", tla_ident(from_field)))
10597                        })
10598                        .unwrap_or_else(|| "None".to_string()),
10599                    RouteBindingSource::Literal(expr) => {
10600                        compiler.render_expr_with_types(expr, next_env, binding_env, binding_types)
10601                    }
10602                    RouteBindingSource::OwnerProvided => {
10603                        if let Some(target_field) = target_variant
10604                            .fields
10605                            .iter()
10606                            .find(|field| field.name == binding.to_field)
10607                        {
10608                            let var_name = format!(
10609                                "route_owner_ctx_{}_{}",
10610                                tla_ident(&route.name),
10611                                tla_ident(&binding.to_field)
10612                            );
10613                            let domain = self.binding_domain_for_binding(
10614                                route.to.machine.as_str(),
10615                                Some(target_variant.name.as_str()),
10616                                binding.to_field.as_str(),
10617                                &target_field.ty,
10618                            );
10619                            owner_context_quantifiers.push(format!("{var_name} \\in {domain}"));
10620                            var_name
10621                        } else {
10622                            "\"owner_val\"".to_string()
10623                        }
10624                    }
10625                };
10626                (binding.to_field.as_str().to_owned(), expr)
10627            })
10628            .collect::<BTreeMap<String, _>>();
10629        let payload_fields = target_variant
10630            .fields
10631            .iter()
10632            .map(|field| {
10633                let expr = bindings
10634                    .get(field.name.as_str())
10635                    .cloned()
10636                    .unwrap_or_else(|| default_state_init_expr(&field.ty));
10637                (field.name.as_str().to_owned(), expr)
10638            })
10639            .collect::<BTreeMap<String, _>>();
10640        (
10641            self.payload_record_expr(&payload_fields),
10642            owner_context_quantifiers,
10643        )
10644    }
10645
10646    fn append_if_missing_chain(&self, base: String, items: &[String]) -> String {
10647        items.iter().fold(base, |expr, item| {
10648            format!("AppendIfMissing({expr}, {item})")
10649        })
10650    }
10651
10652    fn union_set_items(&self, base: String, items: &[String]) -> String {
10653        if items.is_empty() {
10654            base
10655        } else {
10656            format!("{base} \\cup {{{}}}", items.join(", "))
10657        }
10658    }
10659
10660    fn transition_packet_expr(&self, instance_id: &str, transition: &TransitionSchema) -> String {
10661        format!(
10662            "[machine |-> {}, transition |-> {}, actor |-> {}, step |-> (model_step_count + 1), from_phase |-> {}, to_phase |-> {}]",
10663            tla_string(instance_id),
10664            tla_string(&transition.name),
10665            tla_string(self.actor(instance_id)),
10666            self.phase_var(instance_id),
10667            tla_string(&transition.to)
10668        )
10669    }
10670}
10671
10672#[derive(Clone, Copy)]
10673enum OrderingOperator {
10674    Lt,
10675    Lte,
10676    Gt,
10677    Gte,
10678}
10679
10680struct MachineTlaCompiler<'a> {
10681    schema: &'a MachineSchema,
10682    named_bindings: BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
10683    helper_defs: Vec<String>,
10684    helper_counter: usize,
10685    helper_prefix: Option<String>,
10686    phase_symbol: Option<String>,
10687    field_env_override: Option<BTreeMap<String, String>>,
10688    unchanged_frames: UnchangedFrameInterner,
10689    /// Set when an ordering comparison renders through `OptionLt` /
10690    /// `OptionLe`; the module then defines them. Shared by every compiler
10691    /// that renders into the same module.
10692    option_order_used: Rc<Cell<bool>>,
10693}
10694
10695impl<'a> MachineTlaCompiler<'a> {
10696    fn new(schema: &'a MachineSchema) -> Self {
10697        Self {
10698            schema,
10699            named_bindings: collect_machine_named_bindings(schema),
10700            helper_defs: Vec::new(),
10701            helper_counter: 0,
10702            helper_prefix: None,
10703            phase_symbol: None,
10704            field_env_override: None,
10705            unchanged_frames: UnchangedFrameInterner::default(),
10706            option_order_used: Rc::default(),
10707        }
10708    }
10709
10710    fn new_with_helper_prefix(schema: &'a MachineSchema, helper_prefix: impl Into<String>) -> Self {
10711        Self {
10712            schema,
10713            named_bindings: collect_machine_named_bindings(schema),
10714            helper_defs: Vec::new(),
10715            helper_counter: 0,
10716            helper_prefix: Some(helper_prefix.into()),
10717            phase_symbol: None,
10718            field_env_override: None,
10719            unchanged_frames: UnchangedFrameInterner::default(),
10720            option_order_used: Rc::default(),
10721        }
10722    }
10723
10724    fn with_option_order_flag(mut self, option_order_used: Rc<Cell<bool>>) -> Self {
10725        self.option_order_used = option_order_used;
10726        self
10727    }
10728
10729    fn with_phase_symbol(mut self, phase_symbol: impl Into<String>) -> Self {
10730        self.phase_symbol = Some(phase_symbol.into());
10731        self
10732    }
10733
10734    fn with_field_env_override(mut self, field_env_override: BTreeMap<String, String>) -> Self {
10735        self.field_env_override = Some(field_env_override);
10736        self
10737    }
10738
10739    fn render(&mut self) -> std::result::Result<String, CompositionTlaError> {
10740        let mut out = String::new();
10741        let constants = collect_binding_domains(self.schema);
10742        let named_samples = collect_machine_named_type_samples(self.schema);
10743        let named_bindings = collect_machine_named_bindings(self.schema);
10744
10745        pushln!(&mut out, "---- MODULE model ----");
10746        pushln!(&mut out, "EXTENDS TLC, Naturals, Sequences, FiniteSets");
10747        pushln!(&mut out);
10748        writeln!(
10749            &mut out,
10750            "\\* Generated semantic machine model for {}.",
10751            self.schema.machine
10752        )
10753        .expect("write to string");
10754        pushln!(&mut out);
10755
10756        let mut model_constants = constants
10757            .iter()
10758            .filter(|(_, ty)| {
10759                !matches!(
10760                    ty,
10761                    TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
10762                )
10763            })
10764            .map(|(name, _)| name)
10765            .cloned()
10766            .collect::<Vec<_>>();
10767        model_constants.extend(
10768            machine_input_sample_constants(self.schema)
10769                .into_iter()
10770                .map(|(constant, _)| constant),
10771        );
10772        model_constants.extend(
10773            machine_input_typed_sample_constants(self.schema)
10774                .into_iter()
10775                .map(|(constant, _, _)| constant),
10776        );
10777        if machine_uses_u64_max(self.schema) {
10778            model_constants.push(TLA_RUST_U64_MAX_CONSTANT.to_owned());
10779        }
10780        if !model_constants.is_empty() {
10781            let constant_list = model_constants.join(", ");
10782            if model_constants
10783                .iter()
10784                .any(|constant| constant == TLA_RUST_U64_MAX_CONSTANT)
10785            {
10786                pushln!(
10787                    &mut out,
10788                    "\\* RustU64Max is the TLA boundary for Expr::U64Max; production generated Rust renders u64::MAX."
10789                );
10790            }
10791            writeln!(&mut out, "CONSTANTS {constant_list}");
10792            pushln!(&mut out);
10793        }
10794
10795        pushln!(&mut out, "None == [tag |-> \"none\", value |-> \"none\"]");
10796        writeln!(&mut out, "Some(v) == [tag |-> \"some\", value |-> v]");
10797        pushln!(&mut out);
10798        let option_order_anchor = out.len();
10799
10800        push_cfg_assignment_operator_definitions(
10801            &mut out,
10802            &constants,
10803            &named_bindings,
10804            &CfgAssignmentOperatorProfile {
10805                suffix: "Ci".to_owned(),
10806                explicit_values: self.schema.tlc_model.as_ref().map(|model| &model.ci),
10807                sample_cardinality: machine_cfg_sample_cardinality(self.schema, false),
10808                domain_overrides: None,
10809                named_samples: &named_samples,
10810                include_string_samples: false,
10811            },
10812        );
10813        push_cfg_assignment_operator_definitions(
10814            &mut out,
10815            &constants,
10816            &named_bindings,
10817            &CfgAssignmentOperatorProfile {
10818                suffix: "Deep".to_owned(),
10819                explicit_values: self.schema.tlc_model.as_ref().map(|model| &model.deep),
10820                sample_cardinality: machine_cfg_sample_cardinality(self.schema, true),
10821                domain_overrides: Some(&self.schema.deep_domain_overrides),
10822                named_samples: &with_guard_binding_string_samples(&named_samples, self.schema),
10823                include_string_samples: !machine_uses_session_id_string_bridge(self.schema),
10824            },
10825        );
10826
10827        for (name, ty) in ordered_composite_domain_definitions(&constants) {
10828            let definition = match ty {
10829                TypeRef::Seq(inner) => render_sequence_domain_definition(inner),
10830                TypeRef::Option(inner) => render_option_domain_definition(inner),
10831                TypeRef::Map(key, value) => render_map_domain_definition(key, value),
10832                _ => continue,
10833            };
10834            writeln!(&mut out, "{} == {}", name, definition).expect("write to string");
10835        }
10836        if constants.values().any(|ty| {
10837            matches!(
10838                ty,
10839                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
10840            )
10841        }) {
10842            pushln!(&mut out);
10843        }
10844        // What each profile's config assigns a `CiSamples` input field's
10845        // constant: the CI profile the declared values, the Deep profile the
10846        // field type's whole domain (defined above).
10847        let typed_samples = machine_input_typed_sample_constants(self.schema);
10848        for (constant, samples, ty) in &typed_samples {
10849            writeln!(
10850                &mut out,
10851                "{} == {}",
10852                cfg_assignment_operator_name(constant, "Ci"),
10853                render_explicit_values(samples)
10854            )
10855            .expect("write to string");
10856            writeln!(
10857                &mut out,
10858                "{} == {}",
10859                cfg_assignment_operator_name(constant, "Deep"),
10860                self.binding_domain_for_type(ty)
10861            )
10862            .expect("write to string");
10863        }
10864        if !typed_samples.is_empty() {
10865            pushln!(&mut out);
10866        }
10867        writeln!(
10868            &mut out,
10869            "MapLookup(map, key) == IF key \\in DOMAIN map THEN map[key] ELSE None"
10870        )
10871        .expect("write to string");
10872        writeln!(
10873            &mut out,
10874            "MapSet(map, key, value) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN value ELSE map[x]]"
10875        )
10876        .expect("write to string");
10877        writeln!(
10878            &mut out,
10879            "MapIncrement(map, key, amount) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN (IF key \\in DOMAIN map THEN map[key] ELSE 0) + amount ELSE map[x]]"
10880        )
10881        .expect("write to string");
10882        writeln!(
10883            &mut out,
10884            "MapDecrement(map, key, amount) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN (IF key \\in DOMAIN map THEN map[key] ELSE 0) - amount ELSE map[x]]"
10885        )
10886        .expect("write to string");
10887        writeln!(
10888            &mut out,
10889            "MapRemove(map, key) == [x \\in DOMAIN map \\ {{key}} |-> map[x]]"
10890        )
10891        .expect("write to string");
10892        writeln!(
10893            &mut out,
10894            "StartsWith(seq, prefix) == /\\ Len(prefix) <= Len(seq) /\\ SubSeq(seq, 1, Len(prefix)) = prefix"
10895        )
10896        .expect("write to string");
10897        writeln!(
10898            &mut out,
10899            "SeqElements(seq) == {{seq[i] : i \\in 1..Len(seq)}}"
10900        )
10901        .expect("write to string");
10902        writeln!(
10903            &mut out,
10904            "Count(seq, value) == Cardinality({{i \\in DOMAIN seq : seq[i] = value}})"
10905        )
10906        .expect("write to string");
10907        if !self.schema.tlc_representative_inputs.is_empty() {
10908            writeln!(
10909                &mut out,
10910                "{TLC_REPRESENTATIVE_DOMAIN_HELPER}(values) == IF values = {{}} THEN {{}} ELSE {{CHOOSE value \\in values : TRUE}}"
10911            )
10912            .expect("write to string");
10913        }
10914        writeln!(
10915            &mut out,
10916            "RECURSIVE SeqRemove(_, _)\nSeqRemove(seq, value) == IF Len(seq) = 0 THEN <<>> ELSE IF Head(seq) = value THEN SeqRemove(Tail(seq), value) ELSE <<Head(seq)>> \\o SeqRemove(Tail(seq), value)"
10917        )
10918        .expect("write to string");
10919        writeln!(
10920            &mut out,
10921            "RECURSIVE SeqRemoveAll(_, _)\nSeqRemoveAll(seq, values) == IF Len(values) = 0 THEN seq ELSE SeqRemoveAll(SeqRemove(seq, Head(values)), Tail(values))"
10922        )
10923        .expect("write to string");
10924        pushln!(&mut out);
10925
10926        let variable_list = std::iter::once("phase".to_string())
10927            .chain(std::iter::once("model_step_count".to_string()))
10928            .chain(
10929                self.schema
10930                    .state
10931                    .fields
10932                    .iter()
10933                    .map(|field| field.name.as_str().to_owned()),
10934            )
10935            .collect::<Vec<_>>()
10936            .join(", ");
10937        pushln!(&mut out, "VARIABLES {variable_list}");
10938        pushln!(&mut out);
10939        let vars = std::iter::once("phase".to_string())
10940            .chain(std::iter::once("model_step_count".to_string()))
10941            .chain(
10942                self.schema
10943                    .state
10944                    .fields
10945                    .iter()
10946                    .map(|field| field.name.as_str().to_owned()),
10947            )
10948            .collect::<Vec<_>>();
10949        pushln!(&mut out, "vars == << {} >>", vars.join(", "));
10950        pushln!(&mut out);
10951
10952        for helper in helper_dependency_order(self.schema)? {
10953            self.render_helper(&mut out, helper);
10954        }
10955        if self.schema.machine.as_str() == "MobMachine" {
10956            self.render_mob_machine_native_helpers(&mut out);
10957        }
10958        if self.schema.machine.as_str() == "MeerkatMachine" {
10959            self.render_meerkat_machine_native_helpers(&mut out);
10960        }
10961        if self.schema.machine.as_str() == "RuntimeDeliveryMachine" {
10962            self.render_runtime_delivery_native_helpers(&mut out);
10963        }
10964        if self.schema.machine.as_str() == "SessionDocumentMachine" {
10965            self.render_session_document_native_helpers(&mut out);
10966        }
10967        if !self.schema.helpers.is_empty() || !self.schema.derived.is_empty() {
10968            pushln!(&mut out);
10969        }
10970
10971        pushln!(&mut out, "Init ==");
10972        writeln!(
10973            &mut out,
10974            "    /\\ phase = {}",
10975            tla_string(&self.schema.state.init.phase)
10976        )
10977        .expect("write to string");
10978        pushln!(&mut out, "    /\\ model_step_count = 0");
10979        for field in &self.schema.state.fields {
10980            let init_expr = self
10981                .schema
10982                .state
10983                .init
10984                .fields
10985                .iter()
10986                .find(|item| item.field == field.name)
10987                .map(|item| self.render_expr(&item.expr, &BTreeMap::new(), &BTreeMap::new()))
10988                .unwrap_or_else(|| default_state_init_expr(&field.ty));
10989            pushln!(&mut out, "    /\\ {} = {}", field.name, init_expr);
10990        }
10991        pushln!(&mut out);
10992
10993        let mut rendered_transitions = Vec::new();
10994        for transition in &self.schema.transitions {
10995            let mut rendered = String::new();
10996            self.render_transition(&mut rendered, transition);
10997            rendered_transitions.push(rendered);
10998        }
10999
11000        if !self.schema.state.terminal_phases.is_empty() {
11001            let terminal_guard = if self.schema.state.terminal_phases.len() == 1 {
11002                format!(
11003                    "phase = {}",
11004                    tla_string(&self.schema.state.terminal_phases[0])
11005                )
11006            } else {
11007                self.schema
11008                    .state
11009                    .terminal_phases
11010                    .iter()
11011                    .map(|phase| format!("phase = {}", tla_string(phase)))
11012                    .collect::<Vec<_>>()
11013                    .join(" \\/ ")
11014            };
11015            pushln!(&mut out, "TerminalStutter ==");
11016            pushln!(&mut out, "    /\\ {}", terminal_guard);
11017            pushln!(&mut out, "    /\\ UNCHANGED vars");
11018            pushln!(&mut out);
11019        }
11020
11021        // Fail closed on a frame-name collision: the rendered transitions
11022        // already reference one name for two different frames, so returning the
11023        // module would silently give an action the wrong frame condition.
11024        if let Some(collision) = self.unchanged_frames.collision() {
11025            return Err(CompositionTlaError::MachineUnchangedFrameCollision {
11026                machine: self.schema.machine.as_str().to_owned(),
11027                collision: collision.clone(),
11028            });
11029        }
11030        // Every frame variable is in scope from the VARIABLES declaration
11031        // above, and every reference is in the transition bodies below.
11032        out.push_str(&self.unchanged_frames.definitions_block());
11033
11034        if !self.helper_defs.is_empty() {
11035            for helper in &self.helper_defs {
11036                pushln!(&mut out, "{helper}");
11037                pushln!(&mut out);
11038            }
11039        }
11040
11041        for transition in &rendered_transitions {
11042            pushln!(&mut out, "{transition}");
11043            pushln!(&mut out);
11044        }
11045
11046        pushln!(&mut out, "Next ==");
11047        for transition in &self.schema.transitions {
11048            let call = if transition.on.bindings().is_empty() {
11049                transition.name.as_str().to_owned()
11050            } else {
11051                let binding_types = self.binding_type_map(transition);
11052                let forced_bool_literals =
11053                    transition_forced_bool_literals(transition, &binding_types);
11054                let binding_env = transition
11055                    .on
11056                    .bindings()
11057                    .iter()
11058                    .map(|binding| {
11059                        (
11060                            binding.as_str().to_owned(),
11061                            self.local_binding_name(binding.as_str()),
11062                        )
11063                    })
11064                    .collect::<BTreeMap<_, _>>();
11065                let mut prefix = String::new();
11066                for binding in transition.on.bindings() {
11067                    if forced_bool_literals.contains_key(binding.as_str()) {
11068                        continue;
11069                    }
11070                    let Some(ty) = binding_types.get(binding.as_str()) else {
11071                        return Ok(String::new());
11072                    };
11073                    let domain = self.binding_domain_for_binding(
11074                        trigger_input_variant(transition),
11075                        binding.as_str(),
11076                        ty,
11077                    );
11078                    let domain =
11079                        if transition_uses_tlc_representative_payload(self.schema, transition) {
11080                            tlc_representative_domain(domain)
11081                        } else {
11082                            domain
11083                        };
11084                    let local = binding_env
11085                        .get(binding.as_str())
11086                        .cloned()
11087                        .unwrap_or_else(|| binding.as_str().to_owned());
11088                    prefix.push_str(&format!("\\E {local} \\in {domain} : "));
11089                }
11090                let args = transition
11091                    .on
11092                    .bindings()
11093                    .iter()
11094                    .map(|binding| {
11095                        forced_bool_literals
11096                            .get(binding.as_str())
11097                            .map(|value| tla_bool_literal(*value).to_owned())
11098                            .unwrap_or_else(|| {
11099                                binding_env
11100                                    .get(binding.as_str())
11101                                    .cloned()
11102                                    .unwrap_or_else(|| binding.as_str().to_owned())
11103                            })
11104                    })
11105                    .collect::<Vec<_>>()
11106                    .join(", ");
11107                // Hoist the source-phase guard ahead of the parameter
11108                // quantifiers. The guard is the first conjunct of the action
11109                // body too, so the disjunct is unchanged in meaning, but TLC
11110                // no longer splits it into one action per parameter tuple
11111                // that it must enumerate in every state: states outside the
11112                // source phase reject the whole disjunct at once.
11113                let from_guard = transition
11114                    .from
11115                    .iter()
11116                    .map(|phase| format!("phase = {}", tla_string(phase)))
11117                    .collect::<Vec<_>>()
11118                    .join(" \\/ ");
11119                if prefix.is_empty() || from_guard.is_empty() {
11120                    format!("{prefix}{}({})", transition.name, args)
11121                } else {
11122                    format!("({from_guard}) /\\ {prefix}{}({})", transition.name, args)
11123                }
11124            };
11125            pushln!(&mut out, "    \\/ {}", call);
11126        }
11127        if !self.schema.state.terminal_phases.is_empty() {
11128            pushln!(&mut out, "    \\/ TerminalStutter");
11129        }
11130        pushln!(&mut out);
11131
11132        for invariant in &self.schema.invariants {
11133            writeln!(
11134                &mut out,
11135                "{} == {}",
11136                invariant.name,
11137                self.render_expr(&invariant.expr, &BTreeMap::new(), &BTreeMap::new())
11138            )
11139            .expect("write to string");
11140        }
11141        pushln!(&mut out);
11142
11143        writeln!(
11144            &mut out,
11145            "CiStateConstraint == {}",
11146            render_machine_state_constraint(self.schema, false)
11147        )
11148        .expect("write to string");
11149        writeln!(
11150            &mut out,
11151            "DeepStateConstraint == {}",
11152            render_machine_state_constraint(self.schema, true)
11153        )
11154        .expect("write to string");
11155        pushln!(&mut out);
11156
11157        pushln!(&mut out, "Spec == Init /\\ [][Next]_vars");
11158        pushln!(&mut out);
11159        for invariant in &self.schema.invariants {
11160            pushln!(&mut out, "THEOREM Spec => []{}", invariant.name);
11161        }
11162        pushln!(&mut out);
11163        writeln!(
11164            &mut out,
11165            "============================================================================="
11166        )
11167        .expect("write to string");
11168
11169        if self.option_order_used.get() {
11170            out.insert_str(option_order_anchor, TLA_OPTION_ORDER_DEFINITIONS);
11171        }
11172        Ok(out)
11173    }
11174
11175    fn render_helper(&self, out: &mut String, helper: &HelperSchema) {
11176        let params = helper
11177            .params
11178            .iter()
11179            .map(|field| self.local_binding_name(field.name.as_str()))
11180            .collect::<Vec<_>>()
11181            .join(", ");
11182        let binding_env = helper
11183            .params
11184            .iter()
11185            .map(|field| {
11186                (
11187                    field.name.as_str().to_owned(),
11188                    self.local_binding_name(field.name.as_str()),
11189                )
11190            })
11191            .collect::<BTreeMap<String, _>>();
11192        let field_env = self.field_env_override.clone().unwrap_or_else(|| {
11193            self.schema
11194                .state
11195                .fields
11196                .iter()
11197                .map(|field| {
11198                    (
11199                        field.name.as_str().to_owned(),
11200                        field.name.as_str().to_owned(),
11201                    )
11202                })
11203                .collect::<BTreeMap<String, _>>()
11204        });
11205        let binding_types = helper
11206            .params
11207            .iter()
11208            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
11209            .collect::<BTreeMap<String, _>>();
11210        if helper.params.is_empty() {
11211            writeln!(
11212                out,
11213                "{} == {}",
11214                self.scoped_helper_name(&helper.name),
11215                self.render_expr_with_types(&helper.body, &field_env, &binding_env, &binding_types)
11216            )
11217            .expect("write to string");
11218        } else {
11219            writeln!(
11220                out,
11221                "{}({}) == {}",
11222                self.scoped_helper_name(&helper.name),
11223                params,
11224                self.render_expr_with_types(&helper.body, &field_env, &binding_env, &binding_types)
11225            )
11226            .expect("write to string");
11227        }
11228    }
11229
11230    fn render_runtime_delivery_native_helpers(&self, out: &mut String) {
11231        writeln!(
11232            out,
11233            "{}(current, recipient, outcome) ==",
11234            self.scoped_helper_name("runtime_delivery_recipient_outcomes_after_set")
11235        )
11236        .expect("write to string");
11237        pushln!(out, "    MapSet(current, recipient, outcome)");
11238    }
11239
11240    fn render_session_document_native_helpers(&self, out: &mut String) {
11241        writeln!(
11242            out,
11243            "{}(current, slot, value) ==",
11244            self.scoped_helper_name("session_document_instruction_slot_after_set")
11245        )
11246        .expect("write to string");
11247        pushln!(out, "    MapSet(current, slot, value)");
11248        // The body bytes of the Active slots; a slot the bytes map does not
11249        // name counts nothing (the Rust authorities agree).
11250        writeln!(
11251            out,
11252            "{}(slot_effect, slot_bytes) ==",
11253            self.scoped_helper_name("session_document_instruction_active_bytes")
11254        )
11255        .expect("write to string");
11256        pushln!(
11257            out,
11258            "    LET RECURSIVE SessionDocumentInstructionActiveBytesOver(_)"
11259        );
11260        pushln!(
11261            out,
11262            "        SessionDocumentInstructionActiveBytesOver(instruction_slots) =="
11263        );
11264        pushln!(out, "            IF instruction_slots = {{}} THEN 0");
11265        pushln!(
11266            out,
11267            "            ELSE LET instruction_slot == CHOOSE candidate_slot \\in instruction_slots : TRUE"
11268        );
11269        pushln!(
11270            out,
11271            "                 IN (IF slot_effect[instruction_slot] = \"Active\" /\\ instruction_slot \\in DOMAIN slot_bytes"
11272        );
11273        pushln!(
11274            out,
11275            "                     THEN slot_bytes[instruction_slot] ELSE 0)"
11276        );
11277        pushln!(
11278            out,
11279            "                    + SessionDocumentInstructionActiveBytesOver(instruction_slots \\ {{instruction_slot}})"
11280        );
11281        pushln!(
11282            out,
11283            "    IN SessionDocumentInstructionActiveBytesOver(DOMAIN slot_effect)"
11284        );
11285        // The entries of a slot map whose slot is Active: what an
11286        // application puts in effect (the Rust authorities agree).
11287        writeln!(
11288            out,
11289            "{}(slot_effect, slot_values) ==",
11290            self.scoped_helper_name("session_document_instruction_active_slots")
11291        )
11292        .expect("write to string");
11293        pushln!(
11294            out,
11295            "    [instruction_slot \\in {{candidate_slot \\in DOMAIN slot_values :"
11296        );
11297        pushln!(
11298            out,
11299            "            candidate_slot \\in DOMAIN slot_effect /\\ slot_effect[candidate_slot] = \"Active\"}}"
11300        );
11301        pushln!(out, "        |-> slot_values[instruction_slot]]");
11302        // Per activation key, the rows a retirement leaves retired: every
11303        // row but the newest, or the recovered count when that is more; a
11304        // key the retired map does not name counts none (the Rust
11305        // authorities agree).
11306        writeln!(
11307            out,
11308            "{}(activation_rows, activation_retired) ==",
11309            self.scoped_helper_name("session_document_activation_retired_after")
11310        )
11311        .expect("write to string");
11312        pushln!(out, "    [activation_key \\in DOMAIN activation_rows |->");
11313        pushln!(
11314            out,
11315            "        LET retired_count == IF activation_key \\in DOMAIN activation_retired THEN activation_retired[activation_key] ELSE 0"
11316        );
11317        pushln!(
11318            out,
11319            "            superseded_count == IF activation_rows[activation_key] > 0 THEN activation_rows[activation_key] - 1 ELSE 0"
11320        );
11321        pushln!(
11322            out,
11323            "        IN IF retired_count >= superseded_count THEN retired_count ELSE superseded_count]"
11324        );
11325    }
11326
11327    fn render_meerkat_machine_native_helpers(&self, out: &mut String) {
11328        let prefix = |name: &str| self.scoped_helper_name(name);
11329        writeln!(
11330            out,
11331            "{}(current, candidate) ==",
11332            prefix("meerkat_machine_session_id_matches_string")
11333        )
11334        .expect("write to string");
11335        pushln!(out, "    current # None /\\ current.value = candidate");
11336        writeln!(
11337            out,
11338            "{}(endpoints, endpoint_count) ==",
11339            prefix("meerkat_peer_endpoint_set_cardinality_matches")
11340        )
11341        .expect("write to string");
11342        pushln!(out, "    Cardinality(endpoints) = endpoint_count");
11343        writeln!(
11344            out,
11345            "{}(endpoints, peer_id) ==",
11346            prefix("meerkat_peer_endpoint_set_contains_peer_id")
11347        )
11348        .expect("write to string");
11349        pushln!(
11350            out,
11351            "    \\E endpoint \\in endpoints: endpoint.peer_id = peer_id"
11352        );
11353        writeln!(
11354            out,
11355            "{}(endpoint, peer_id) ==",
11356            prefix("meerkat_peer_endpoint_option_peer_id_matches")
11357        )
11358        .expect("write to string");
11359        pushln!(
11360            out,
11361            "    endpoint # None /\\ endpoint.value.peer_id = peer_id"
11362        );
11363        writeln!(
11364            out,
11365            "{}(endpoint, peer_id) ==",
11366            prefix("meerkat_peer_endpoint_peer_id_matches")
11367        )
11368        .expect("write to string");
11369        pushln!(out, "    endpoint.peer_id = peer_id");
11370        writeln!(
11371            out,
11372            "{}(endpoints) ==",
11373            prefix("meerkat_peer_endpoint_set_peer_ids_unique")
11374        )
11375        .expect("write to string");
11376        pushln!(
11377            out,
11378            "    Cardinality(endpoints) = Cardinality({{ endpoint.peer_id : endpoint \\in endpoints }})"
11379        );
11380        writeln!(
11381            out,
11382            "{}(rows, operation_by_authority, operation_id) ==",
11383            prefix("meerkat_machine_live_bridge_authority_rows_without_operation")
11384        )
11385        .expect("write to string");
11386        pushln!(
11387            out,
11388            "    [authority_id \\in {{ candidate \\in DOMAIN rows : IF candidate \\in DOMAIN operation_by_authority THEN operation_by_authority[candidate] # operation_id ELSE TRUE }} |-> rows[authority_id]]"
11389        );
11390        writeln!(
11391            out,
11392            "{}(authorities, operation_by_authority, operation_id) ==",
11393            prefix("meerkat_machine_live_bridge_authorities_without_operation")
11394        )
11395        .expect("write to string");
11396        pushln!(
11397            out,
11398            "    {{ authority_id \\in authorities : IF authority_id \\in DOMAIN operation_by_authority THEN operation_by_authority[authority_id] # operation_id ELSE TRUE }}"
11399        );
11400        // The inputs still bound to one run: its batch and its durable joins,
11401        // staged or, in a resumed run, applied by a committed round. The
11402        // parameters are prefixed: TLA+ forbids a parameter named like a
11403        // state variable (`input_phases`).
11404        writeln!(
11405            out,
11406            "{}(arg_run_associations, arg_input_phases, arg_run_id) ==",
11407            prefix("meerkat_machine_run_contributor_count")
11408        )
11409        .expect("write to string");
11410        pushln!(
11411            out,
11412            "    Cardinality({{ arg_input_id \\in DOMAIN arg_run_associations : IF arg_run_associations[arg_input_id] = arg_run_id /\\ arg_input_id \\in DOMAIN arg_input_phases THEN arg_input_phases[arg_input_id] \\in {{\"Staged\", \"Applied\", \"AppliedPendingConsumption\"}} ELSE FALSE }})"
11413        );
11414        // The most contributors one run's commit names. A defined operator,
11415        // not a literal in the guard, so a bounded audit can substitute a
11416        // small bound (`meerkat_machine_run_contributor_limit <- ...`) and
11417        // explore the refused join.
11418        writeln!(
11419            out,
11420            "{} == {}",
11421            prefix("meerkat_machine_run_contributor_limit"),
11422            meerkat_machine_schema::catalog::dsl::meerkat_machine::command_capabilities::RUNTIME_LOOP_BATCH_MAX_INPUTS
11423        )
11424        .expect("write to string");
11425    }
11426
11427    fn render_mob_machine_native_helpers(&self, out: &mut String) {
11428        let prefix = |name: &str| self.scoped_helper_name(name);
11429        let local = |name: &str| self.local_binding_name(name);
11430        // Row #181: compute the next monotone respawn generation for an
11431        // identity. Missing identity starts at generation zero. A retained
11432        // u64::MAX generation has no successor and must never wrap to zero.
11433        writeln!(
11434            out,
11435            "{}(arg_identity_runtime_generations, arg_agent_identity) ==",
11436            prefix("mob_machine_next_respawn_generation")
11437        )
11438        .expect("write to string");
11439        pushln!(
11440            out,
11441            "    IF arg_agent_identity \\notin DOMAIN arg_identity_runtime_generations"
11442        );
11443        pushln!(out, "    THEN Some(0)");
11444        pushln!(
11445            out,
11446            "    ELSE IF arg_identity_runtime_generations[arg_agent_identity] = {TLA_RUST_U64_MAX_CONSTANT}"
11447        );
11448        pushln!(out, "         THEN None");
11449        pushln!(
11450            out,
11451            "         ELSE Some(arg_identity_runtime_generations[arg_agent_identity] + 1)"
11452        );
11453        // The generation a new incarnation mints: one past the larger of the
11454        // retained generation and the recovered high-water, zero for an
11455        // identity in neither map, and no successor past the Rust u64
11456        // ceiling. Recovery replay keeps the operator above, which reads the
11457        // retained map only.
11458        writeln!(
11459            out,
11460            "{}(arg_identity_runtime_generations, arg_identity_generation_highwater, arg_agent_identity) ==",
11461            prefix("mob_machine_next_minted_generation")
11462        )
11463        .expect("write to string");
11464        pushln!(
11465            out,
11466            "    LET retained == IF arg_agent_identity \\in DOMAIN arg_identity_runtime_generations"
11467        );
11468        pushln!(
11469            out,
11470            "                    THEN arg_identity_runtime_generations[arg_agent_identity] ELSE 0"
11471        );
11472        pushln!(
11473            out,
11474            "        highwater == IF arg_agent_identity \\in DOMAIN arg_identity_generation_highwater"
11475        );
11476        pushln!(
11477            out,
11478            "                     THEN arg_identity_generation_highwater[arg_agent_identity] ELSE 0"
11479        );
11480        pushln!(
11481            out,
11482            "        base == IF retained >= highwater THEN retained ELSE highwater"
11483        );
11484        pushln!(
11485            out,
11486            "    IN IF arg_agent_identity \\notin DOMAIN arg_identity_runtime_generations /\\ arg_agent_identity \\notin DOMAIN arg_identity_generation_highwater"
11487        );
11488        pushln!(out, "       THEN Some(0)");
11489        pushln!(
11490            out,
11491            "       ELSE IF base = {TLA_RUST_U64_MAX_CONSTANT} THEN None ELSE Some(base + 1)"
11492        );
11493        // Supervisor epochs use the same non-wrapping u64 successor relation
11494        // in both plain and Option-valued recovered tuples. These operators
11495        // deliberately mention the Rust u64 ceiling so TLC cannot admit
11496        // MAX -> 0 as a successor through unbounded integer arithmetic.
11497        writeln!(
11498            out,
11499            "{}(arg_current, arg_next) ==",
11500            prefix("mob_machine_u64_is_exact_successor")
11501        )
11502        .expect("write to string");
11503        pushln!(out, "    /\\ arg_current # {TLA_RUST_U64_MAX_CONSTANT}");
11504        pushln!(out, "    /\\ arg_next = arg_current + 1");
11505        writeln!(
11506            out,
11507            "{}(arg_current, arg_next) ==",
11508            prefix("mob_machine_optional_u64_is_exact_successor")
11509        )
11510        .expect("write to string");
11511        pushln!(out, "    /\\ arg_current # {TLA_RUST_U64_MAX_CONSTANT}");
11512        pushln!(out, "    /\\ arg_next = Some(arg_current + 1)");
11513        // Remote-turn custody admission is a native MobMachine reducer because
11514        // it enforces aggregate cardinality and correlation-key uniqueness
11515        // across all three custody sets. Keep this operator structurally
11516        // equivalent to the Rust helper in the canonical MobMachine catalog.
11517        writeln!(
11518            out,
11519            "{}(pending, committed, resolved, candidate) ==",
11520            prefix("mob_machine_remote_turn_custody_admits")
11521        )
11522        .expect("write to string");
11523        pushln!(
11524            out,
11525            "    LET same_member_host_count == Cardinality({{ row \\in pending : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11526        );
11527        pushln!(
11528            out,
11529            "            + Cardinality({{ row \\in committed : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11530        );
11531        pushln!(
11532            out,
11533            "            + Cardinality({{ row \\in resolved : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11534        );
11535        pushln!(
11536            out,
11537            "    IN /\\ Cardinality(pending) + Cardinality(committed) + Cardinality(resolved) < 4096"
11538        );
11539        pushln!(out, "       /\\ candidate.dispatch_sequence > 0");
11540        pushln!(out, "       /\\ candidate.input_id # \"\"");
11541        pushln!(out, "       /\\ candidate.run_id # \"\"");
11542        pushln!(out, "       /\\ candidate.step_id # \"\"");
11543        pushln!(out, "       /\\ candidate.host_id # \"\"");
11544        pushln!(out, "       /\\ candidate.member_session_id # \"\"");
11545        for rows in ["pending", "committed", "resolved"] {
11546            pushln!(
11547                out,
11548                "       /\\ \\A row \\in {rows} : /\\ row.dispatch_sequence # candidate.dispatch_sequence /\\ \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11549            );
11550        }
11551        pushln!(out, "       /\\ same_member_host_count < 256");
11552        // Placed completion/kickoff helpers. TLC treats canonical UUID lexical
11553        // shape as an abstract non-empty string property; Rust performs the
11554        // stricter parse-and-roundtrip check at the executable boundary.
11555        writeln!(
11556            out,
11557            "{}(candidate) ==",
11558            prefix("mob_machine_placed_completion_obligation_well_formed")
11559        )
11560        .expect("write to string");
11561        pushln!(out, "    /\\ candidate.agent_identity # \"\"");
11562        pushln!(out, "    /\\ candidate.host_id # \"\"");
11563        pushln!(out, "    /\\ candidate.host_binding_generation > 0");
11564        pushln!(out, "    /\\ candidate.member_session_id # \"\"");
11565        pushln!(out, "    /\\ candidate.dispatch_sequence > 0");
11566        pushln!(out, "    /\\ candidate.input_id # \"\"");
11567        writeln!(
11568            out,
11569            "{}(pending, resolved, candidate) ==",
11570            prefix("mob_machine_placed_completion_custody_admits")
11571        )
11572        .expect("write to string");
11573        pushln!(out, "    LET rows == pending \\cup resolved");
11574        pushln!(
11575            out,
11576            "        same_member_host == Cardinality({{ row \\in rows : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11577        );
11578        pushln!(out, "    IN /\\ Cardinality(rows) < 4096");
11579        pushln!(
11580            out,
11581            "       /\\ \\A row \\in rows : /\\ row.dispatch_sequence # candidate.dispatch_sequence /\\ \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11582        );
11583        pushln!(out, "       /\\ same_member_host < 256");
11584        writeln!(
11585            out,
11586            "{}(active_run, active_layer, active_members, layer_phases, layer_dispositions) ==",
11587            prefix("mob_machine_adaptive_lifecycle_drained")
11588        )
11589        .expect("write to string");
11590        pushln!(out, "    /\\ active_run = None");
11591        pushln!(out, "    /\\ DOMAIN active_layer = {{}}");
11592        pushln!(
11593            out,
11594            "    /\\ \\A run_id \\in DOMAIN active_members : active_members[run_id] = 0"
11595        );
11596        pushln!(out, "    /\\ \\A layer_id \\in DOMAIN layer_phases :");
11597        pushln!(
11598            out,
11599            "           \\/ layer_phases[layer_id] = \"Validating\""
11600        );
11601        pushln!(
11602            out,
11603            "           \\/ /\\ layer_id \\in DOMAIN layer_dispositions"
11604        );
11605        pushln!(
11606            out,
11607            "              /\\ layer_phases[layer_id] \\in {{\"Completed\", \"SetupFailed\", \"RunFailed\", \"ResultInvalid\", \"Canceled\"}}"
11608        );
11609        writeln!(
11610            out,
11611            "{}(adaptive_run_id, active_layer, active_members, layer_run, layer_phases, layer_dispositions) ==",
11612            prefix("mob_machine_adaptive_run_custody_drained")
11613        )
11614        .expect("write to string");
11615        pushln!(out, "    /\\ adaptive_run_id \\notin DOMAIN active_layer");
11616        pushln!(
11617            out,
11618            "    /\\ (IF adaptive_run_id \\in DOMAIN active_members THEN active_members[adaptive_run_id] ELSE 0) = 0"
11619        );
11620        pushln!(out, "    /\\ \\A layer_id \\in DOMAIN layer_run :");
11621        pushln!(out, "           \\/ layer_run[layer_id] # adaptive_run_id");
11622        pushln!(
11623            out,
11624            "           \\/ /\\ layer_id \\in DOMAIN layer_dispositions"
11625        );
11626        pushln!(out, "              /\\ layer_id \\in DOMAIN layer_phases");
11627        pushln!(
11628            out,
11629            "              /\\ layer_phases[layer_id] \\in {{\"Completed\", \"SetupFailed\", \"RunFailed\", \"ResultInvalid\", \"Canceled\"}}"
11630        );
11631        writeln!(
11632            out,
11633            "{}(started, callback_pending, failed, cancelled, kickoff_errors, identity, outcome_kind, outcome_error, closure_kind) ==",
11634            prefix("mob_machine_finalized_placed_kickoff_recovery_well_formed")
11635        )
11636        .expect("write to string");
11637        pushln!(
11638            out,
11639            "    /\\ Cardinality({{ kickoff_phase \\in {{\"Started\", \"CallbackPending\", \"Failed\", \"Cancelled\"}} :"
11640        );
11641        pushln!(
11642            out,
11643            "           CASE kickoff_phase = \"Started\" -> identity \\in started"
11644        );
11645        pushln!(
11646            out,
11647            "             [] kickoff_phase = \"CallbackPending\" -> identity \\in callback_pending"
11648        );
11649        pushln!(
11650            out,
11651            "             [] kickoff_phase = \"Failed\" -> identity \\in failed"
11652        );
11653        pushln!(
11654            out,
11655            "             [] OTHER -> identity \\in cancelled }}) = 1"
11656        );
11657        pushln!(
11658            out,
11659            "    /\\ CASE outcome_kind = \"Failed\" -> outcome_error # None"
11660        );
11661        pushln!(
11662            out,
11663            "          [] outcome_kind = \"RejectedNoEffect\" -> /\\ outcome_error # None /\\ outcome_error.value # \"\""
11664        );
11665        pushln!(out, "          [] OTHER -> outcome_error = None");
11666        pushln!(
11667            out,
11668            "    /\\ CASE closure_kind = \"Acknowledged\" -> /\\ outcome_kind # \"RejectedNoEffect\" /\\ outcome_kind # \"Disposed\""
11669        );
11670        pushln!(
11671            out,
11672            "          [] closure_kind = \"RejectedNoEffect\" -> outcome_kind = \"RejectedNoEffect\""
11673        );
11674        pushln!(
11675            out,
11676            "          [] OTHER -> outcome_kind # \"RejectedNoEffect\""
11677        );
11678        pushln!(
11679            out,
11680            "    /\\ CASE identity \\in cancelled -> identity \\notin DOMAIN kickoff_errors"
11681        );
11682        pushln!(
11683            out,
11684            "          [] identity \\in started -> /\\ outcome_kind = \"Started\" /\\ identity \\notin DOMAIN kickoff_errors"
11685        );
11686        pushln!(
11687            out,
11688            "          [] identity \\in callback_pending -> /\\ outcome_kind = \"CallbackPending\" /\\ identity \\notin DOMAIN kickoff_errors"
11689        );
11690        pushln!(
11691            out,
11692            "          [] OTHER -> /\\ outcome_kind \\in {{\"Failed\", \"RejectedNoEffect\"}} /\\ identity \\in DOMAIN kickoff_errors /\\ outcome_error = Some(kickoff_errors[identity])"
11693        );
11694        writeln!(
11695            out,
11696            "{}(candidate) ==",
11697            prefix("mob_machine_placed_kickoff_obligation_well_formed")
11698        )
11699        .expect("write to string");
11700        pushln!(out, "    /\\ candidate.agent_identity # \"\"");
11701        pushln!(out, "    /\\ candidate.host_id # \"\"");
11702        pushln!(out, "    /\\ candidate.host_binding_generation > 0");
11703        pushln!(out, "    /\\ candidate.member_session_id # \"\"");
11704        pushln!(out, "    /\\ candidate.input_id # \"\"");
11705        pushln!(out, "    /\\ candidate.objective_id # \"\"");
11706        writeln!(
11707            out,
11708            "{}(pending_kickoffs, resolved_kickoffs, retained_kickoffs, pending_turns, committed_turns, resolved_turns, pending_completions, resolved_completions, candidate) ==",
11709            prefix("mob_machine_placed_kickoff_correlation_available")
11710        )
11711        .expect("write to string");
11712        pushln!(
11713            out,
11714            "    /\\ \\A row \\in pending_kickoffs \\cup resolved_kickoffs : /\\ row.agent_identity # candidate.agent_identity /\\ \\lnot (/\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11715        );
11716        pushln!(
11717            out,
11718            "    /\\ \\A identity \\in DOMAIN retained_kickoffs : retained_kickoffs[identity].agent_identity # candidate.agent_identity"
11719        );
11720        pushln!(
11721            out,
11722            "    /\\ \\A row \\in pending_turns \\cup committed_turns \\cup resolved_turns : \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11723        );
11724        pushln!(
11725            out,
11726            "    /\\ \\A row \\in pending_completions \\cup resolved_completions : \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11727        );
11728        writeln!(
11729            out,
11730            "{}(pending, resolved, agent_identity) ==",
11731            prefix("mob_machine_placed_kickoff_custody_absent_for_identity")
11732        )
11733        .expect("write to string");
11734        pushln!(
11735            out,
11736            "    \\A row \\in pending \\cup resolved : row.agent_identity # agent_identity"
11737        );
11738        writeln!(
11739            out,
11740            "{}(pending, resolved, host_id) ==",
11741            prefix("mob_machine_placed_kickoff_custody_absent_for_host")
11742        )
11743        .expect("write to string");
11744        pushln!(
11745            out,
11746            "    \\A row \\in pending \\cup resolved : row.host_id # host_id"
11747        );
11748        writeln!(
11749            out,
11750            "{}(pending, resolved, retained, candidate) ==",
11751            prefix("mob_machine_remote_turn_input_id_available_to_kickoff")
11752        )
11753        .expect("write to string");
11754        pushln!(
11755            out,
11756            "    /\\ \\A row \\in pending \\cup resolved : \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11757        );
11758        pushln!(
11759            out,
11760            "    /\\ \\A identity \\in DOMAIN retained : \\lnot (/\\ retained[identity].agent_identity = candidate.agent_identity /\\ retained[identity].host_id = candidate.host_id /\\ retained[identity].generation = candidate.generation /\\ retained[identity].fence_token = candidate.fence_token /\\ retained[identity].input_id = candidate.input_id)"
11761        );
11762        // Retirement atomically prunes every local wiring edge incident to
11763        // the retiring identity. This mirrors the catalog-native Rust helper
11764        // and keeps cold replay from resurrecting topology to an absent member.
11765        writeln!(
11766            out,
11767            "{}(arg_wiring_edges, arg_agent_identity) ==",
11768            prefix("mob_machine_wiring_edges_without_identity")
11769        )
11770        .expect("write to string");
11771        pushln!(
11772            out,
11773            "    {{ edge \\in arg_wiring_edges : /\\ edge.a # arg_agent_identity /\\ edge.b # arg_agent_identity }}"
11774        );
11775        // An edge's other end, and the owned edges a removal leaves (every
11776        // owned edge of the removed identity ends, whichever end owns it):
11777        // the catalog-native Rust helpers' mirrors.
11778        writeln!(
11779            out,
11780            "{}(arg_edge, arg_agent_identity) ==",
11781            prefix("mob_machine_wiring_edge_other")
11782        )
11783        .expect("write to string");
11784        pushln!(
11785            out,
11786            "    IF arg_edge.a = arg_agent_identity THEN arg_edge.b ELSE arg_edge.a"
11787        );
11788        writeln!(
11789            out,
11790            "{}(arg_identity_edge_owners, arg_agent_identity) ==",
11791            prefix("mob_machine_owned_edges_without_identity")
11792        )
11793        .expect("write to string");
11794        pushln!(
11795            out,
11796            "    [edge \\in {{ e \\in DOMAIN arg_identity_edge_owners : /\\ e.a # arg_agent_identity /\\ e.b # arg_agent_identity }} |-> arg_identity_edge_owners[edge]]"
11797        );
11798        writeln!(
11799            out,
11800            "{}(arg_external_peer_edges, arg_agent_identity) ==",
11801            prefix("mob_machine_external_peer_edges_without_identity")
11802        )
11803        .expect("write to string");
11804        pushln!(
11805            out,
11806            "    {{ edge \\in arg_external_peer_edges : edge.local # arg_agent_identity }}"
11807        );
11808        writeln!(
11809            out,
11810            "{}(arg_external_peer_edges_by_key, arg_agent_identity) ==",
11811            prefix("mob_machine_external_peer_edges_by_key_without_identity")
11812        )
11813        .expect("write to string");
11814        pushln!(
11815            out,
11816            "    [key \\in {{ key \\in DOMAIN arg_external_peer_edges_by_key : key.local # arg_agent_identity }} |-> arg_external_peer_edges_by_key[key]]"
11817        );
11818        // The next sessions of the pending FreshSession rotations, which a
11819        // destroy's admission abandons. A SameSession rotation names its
11820        // member's own session, which the destroy's retirement of that member
11821        // disposes of. Mirror of the catalog-native Rust helper.
11822        writeln!(
11823            out,
11824            "{}(arg_member_rotation_session_ids, arg_member_rotation_targets) ==",
11825            prefix("mob_machine_fresh_rotation_sessions")
11826        )
11827        .expect("write to string");
11828        pushln!(
11829            out,
11830            "    [id \\in {{ id \\in DOMAIN arg_member_rotation_session_ids : ~(id \\in DOMAIN arg_member_rotation_targets /\\ arg_member_rotation_targets[id] = \"SameSession\") }} |-> arg_member_rotation_session_ids[id]]"
11831        );
11832        // Row #351: reconcile-membership spawn/retire set helpers. The DSL
11833        // ReconcileMembership effect emits calls to these, but they had no TLA+
11834        // operator definitions, so TLC reported "Unknown operator" for
11835        // MobMachine (and any composition embedding it). Mirror of the Rust
11836        // helpers in `catalog::dsl::mob_machine`: spawn = desired identities not
11837        // yet bound to a runtime; retire = currently-bound identities that are
11838        // no longer desired, gated on `retire_stale` (empty set otherwise).
11839        // `identity_to_runtime` is the bound-identity function (DOMAIN = the
11840        // currently-bound identities); `desired` is the target identity set.
11841        // Both range over workers only: an identity entry (DOMAIN of
11842        // `identity_entry_origins`) is never spawned or retired by them, and
11843        // neither is a reserved name (`identity_entry_tombstones`, never
11844        // seated, is never spawned; `identity_entry_unreadable` is neither
11845        // spawned nor retired).
11846        writeln!(
11847            out,
11848            "{}(arg_identity_to_runtime, arg_identity_entry_origins, arg_identity_entry_tombstones, arg_identity_entry_unreadable, arg_desired) ==",
11849            prefix("mob_machine_members_to_spawn")
11850        )
11851        .expect("write to string");
11852        pushln!(
11853            out,
11854            "    {{ member \\in arg_desired : member \\notin DOMAIN arg_identity_to_runtime /\\ member \\notin DOMAIN arg_identity_entry_origins /\\ member \\notin arg_identity_entry_tombstones /\\ member \\notin arg_identity_entry_unreadable }}"
11855        );
11856        writeln!(
11857            out,
11858            "{}(arg_identity_to_runtime, arg_identity_entry_origins, arg_identity_entry_unreadable, arg_desired, arg_retire_stale) ==",
11859            prefix("mob_machine_members_to_retire")
11860        )
11861        .expect("write to string");
11862        pushln!(out, "    IF arg_retire_stale");
11863        pushln!(
11864            out,
11865            "    THEN {{ member \\in DOMAIN arg_identity_to_runtime : member \\notin arg_desired /\\ member \\notin DOMAIN arg_identity_entry_origins /\\ member \\notin arg_identity_entry_unreadable }}"
11866        );
11867        pushln!(out, "    ELSE {{}}");
11868        // Placed-carrier cleanup is identity-exclusive and carries the exact
11869        // durable operation tuple. Both operators are native Rust helpers in
11870        // the catalog, so every standalone/composition TLA namespace must
11871        // define their semantic twins explicitly.
11872        writeln!(
11873            out,
11874            "{}(arg_obligations, arg_agent_identity) ==",
11875            prefix("mob_machine_placed_cleanup_absent_for_identity")
11876        )
11877        .expect("write to string");
11878        pushln!(
11879            out,
11880            "    \\A obligation \\in arg_obligations : obligation.agent_identity # arg_agent_identity"
11881        );
11882        writeln!(
11883            out,
11884            "{}(arg_agent_identity, arg_spawn_id, arg_generation, arg_fence_token, arg_provision_operation_id, arg_operation_owner_session_id, arg_expected_phase) ==",
11885            prefix("mob_machine_placed_cleanup_obligation")
11886        )
11887        .expect("write to string");
11888        pushln!(
11889            out,
11890            "    [agent_identity |-> arg_agent_identity, spawn_id |-> arg_spawn_id, generation |-> arg_generation, fence_token |-> arg_fence_token, provision_operation_id |-> arg_provision_operation_id, operation_owner_session_id |-> arg_operation_owner_session_id, expected_phase |-> arg_expected_phase]"
11891        );
11892        // A placed carrier is live only at the exact currently bound host
11893        // generation. Keep every partial-map read behind a TLA IF so sampled
11894        // malformed/partial states evaluate to FALSE instead of indexing an
11895        // absent function key.
11896        writeln!(
11897            out,
11898            "{}(arg_member_placement, arg_current_binding_generations, arg_host_bind_phase, arg_host_binding_generations, arg_agent_identity) ==",
11899            prefix("mob_machine_placed_carrier_binding_active")
11900        )
11901        .expect("write to string");
11902        pushln!(
11903            out,
11904            "    IF arg_agent_identity \\notin DOMAIN arg_member_placement"
11905        );
11906        pushln!(out, "    THEN FALSE");
11907        pushln!(
11908            out,
11909            "    ELSE LET host == arg_member_placement[arg_agent_identity]"
11910        );
11911        pushln!(
11912            out,
11913            "         IN IF host \\notin DOMAIN arg_host_bind_phase"
11914        );
11915        pushln!(out, "            THEN FALSE");
11916        pushln!(
11917            out,
11918            "            ELSE IF arg_host_bind_phase[host] # \"Bound\""
11919        );
11920        pushln!(out, "                 THEN FALSE");
11921        pushln!(
11922            out,
11923            "                 ELSE IF arg_agent_identity \\notin DOMAIN arg_current_binding_generations"
11924        );
11925        pushln!(out, "                      THEN FALSE");
11926        pushln!(
11927            out,
11928            "                      ELSE LET generation == arg_current_binding_generations[arg_agent_identity]"
11929        );
11930        pushln!(out, "                           IN /\\ generation > 0");
11931        pushln!(
11932            out,
11933            "                              /\\ host \\in DOMAIN arg_host_binding_generations"
11934        );
11935        pushln!(
11936            out,
11937            "                              /\\ arg_host_binding_generations[host] = generation"
11938        );
11939        writeln!(
11940            out,
11941            "{}(arg_host_id, arg_binding_generation) ==",
11942            prefix("mob_machine_host_binding_generation_tombstone")
11943        )
11944        .expect("write to string");
11945        pushln!(
11946            out,
11947            "    [host_id |-> arg_host_id, binding_generation |-> arg_binding_generation]"
11948        );
11949        // Cleanup after a revoke is authorized only when the exact retained
11950        // carrier generation has a durable revocation tombstone and that host
11951        // is no longer Bound.
11952        writeln!(
11953            out,
11954            "{}(arg_member_placement, arg_current_binding_generations, arg_host_bind_phase, arg_confirmed_revocations, arg_agent_identity) ==",
11955            prefix("mob_machine_placed_carrier_binding_confirmed_revoked")
11956        )
11957        .expect("write to string");
11958        pushln!(
11959            out,
11960            "    IF arg_agent_identity \\notin DOMAIN arg_member_placement"
11961        );
11962        pushln!(out, "    THEN FALSE");
11963        pushln!(
11964            out,
11965            "    ELSE LET host == arg_member_placement[arg_agent_identity]"
11966        );
11967        pushln!(
11968            out,
11969            "         IN IF arg_agent_identity \\notin DOMAIN arg_current_binding_generations"
11970        );
11971        pushln!(out, "            THEN FALSE");
11972        pushln!(
11973            out,
11974            "            ELSE LET generation == arg_current_binding_generations[arg_agent_identity]"
11975        );
11976        pushln!(out, "                 IN /\\ generation > 0");
11977        pushln!(
11978            out,
11979            "                    /\\ (IF host \\in DOMAIN arg_host_bind_phase THEN arg_host_bind_phase[host] # \"Bound\" ELSE TRUE)"
11980        );
11981        pushln!(
11982            out,
11983            "                    /\\ [host_id |-> host, binding_generation |-> generation] \\in arg_confirmed_revocations"
11984        );
11985        // Mob-coordination temporal predicates (work-intent / resource-claim
11986        // expiry). The DSL emits calls to these guards but they had no TLA+
11987        // definitions, so TLC reported "Unknown operator" for MobMachine (and
11988        // for any composition embedding it). The expires-at argument is the
11989        // stored `Option<u64>` (`Some(ms)`/`None`) and `now_ms` is a raw value;
11990        // `e # None /\ e.value <= now_ms` short-circuits when there is no expiry.
11991        // Resource-claim status arrives as the raw status string.
11992        writeln!(
11993            out,
11994            "{}(expires_at_ms, now_ms) ==",
11995            prefix("mob_coordination_expired_at")
11996        )
11997        .expect("write to string");
11998        pushln!(out, "    /\\ expires_at_ms # None");
11999        pushln!(out, "    /\\ expires_at_ms.value <= now_ms");
12000        writeln!(
12001            out,
12002            "{}(expires_at_ms, now_ms) == ~{}(expires_at_ms, now_ms)",
12003            prefix("mob_coordination_work_intent_unexpired"),
12004            prefix("mob_coordination_expired_at")
12005        )
12006        .expect("write to string");
12007        writeln!(
12008            out,
12009            "{}(expires_at_ms, now_ms) == ~{}(expires_at_ms, now_ms)",
12010            prefix("mob_coordination_resource_claim_unexpired"),
12011            prefix("mob_coordination_expired_at")
12012        )
12013        .expect("write to string");
12014        writeln!(
12015            out,
12016            "{}(status, expires_at_ms, now_ms) ==",
12017            prefix("mob_coordination_resource_claim_active_at")
12018        )
12019        .expect("write to string");
12020        pushln!(out, "    /\\ status = \"Active\"");
12021        writeln!(
12022            out,
12023            "    /\\ ~{}(expires_at_ms, now_ms)",
12024            prefix("mob_coordination_expired_at")
12025        )
12026        .expect("write to string");
12027        writeln!(
12028            out,
12029            "{}(status, expires_at_ms, now_ms) == ~{}(status, expires_at_ms, now_ms)",
12030            prefix("mob_coordination_resource_claim_inactive_at"),
12031            prefix("mob_coordination_resource_claim_active_at")
12032        )
12033        .expect("write to string");
12034        writeln!(
12035            out,
12036            "{}(edges_by_key, edge) ==",
12037            prefix("mob_machine_external_peer_edge_has_matching_key")
12038        )
12039        .expect("write to string");
12040        pushln!(
12041            out,
12042            "    LET key == [local |-> edge.local, name |-> edge.endpoint.name]"
12043        );
12044        pushln!(out, "    IN /\\ key \\in DOMAIN edges_by_key");
12045        pushln!(out, "       /\\ edges_by_key[key] = edge");
12046        writeln!(
12047            out,
12048            "{}(edge) == edge.local",
12049            prefix("mob_machine_external_peer_edge_local")
12050        )
12051        .expect("write to string");
12052        writeln!(
12053            out,
12054            "{}(edge) == edge.endpoint.peer_id",
12055            prefix("mob_machine_external_peer_edge_peer_id")
12056        )
12057        .expect("write to string");
12058        writeln!(
12059            out,
12060            "{}(key, edge) ==",
12061            prefix("mob_machine_external_peer_key_matches_edge")
12062        )
12063        .expect("write to string");
12064        pushln!(out, "    /\\ key.local = edge.local");
12065        pushln!(out, "    /\\ key.name = edge.endpoint.name");
12066        writeln!(
12067            out,
12068            "{}(key, agent_identity) == key.local = agent_identity",
12069            prefix("mob_machine_external_peer_key_matches_local")
12070        )
12071        .expect("write to string");
12072        writeln!(
12073            out,
12074            "{}(edges, agent_identity) ==",
12075            prefix("mob_machine_external_peer_identity_absent")
12076        )
12077        .expect("write to string");
12078        pushln!(
12079            out,
12080            "    \\A edge \\in edges : edge.endpoint.name /= agent_identity"
12081        );
12082        writeln!(
12083            out,
12084            "{}({}, agent_identity) ==",
12085            prefix("mob_machine_identity_has_session_binding"),
12086            local("member_session_bindings")
12087        )
12088        .expect("write to string");
12089        pushln!(
12090            out,
12091            "    /\\ agent_identity \\in DOMAIN {}",
12092            local("member_session_bindings")
12093        );
12094        pushln!(
12095            out,
12096            "    /\\ {}[agent_identity] /= \"\"",
12097            local("member_session_bindings")
12098        );
12099        writeln!(
12100            out,
12101            "{}({}, {}, {}, expected_runtime_ids) ==",
12102            prefix("mob_machine_session_bound_live_runtime_ids_match"),
12103            local("identity_to_runtime"),
12104            local("member_session_bindings"),
12105            local("live_runtime_ids")
12106        )
12107        .expect("write to string");
12108        pushln!(
12109            out,
12110            "    LET eligible_ids == {{ candidate \\in DOMAIN {} : {}[candidate] /= \"\" /\\ candidate \\in DOMAIN {} /\\ {}[candidate] \\in {} }}",
12111            local("member_session_bindings"),
12112            local("member_session_bindings"),
12113            local("identity_to_runtime"),
12114            local("identity_to_runtime"),
12115            local("live_runtime_ids")
12116        );
12117        pushln!(
12118            out,
12119            "    IN expected_runtime_ids = {{ {}[id] : id \\in eligible_ids }}",
12120            local("identity_to_runtime")
12121        );
12122        writeln!(
12123            out,
12124            "{}(endpoint) == endpoint.peer_id",
12125            prefix("mob_machine_member_peer_endpoint_peer_id")
12126        )
12127        .expect("write to string");
12128        writeln!(
12129            out,
12130            "{}(host_id, peer_id) == host_id = peer_id",
12131            prefix("mob_machine_host_id_matches_peer_id")
12132        )
12133        .expect("write to string");
12134        writeln!(
12135            out,
12136            "{}(current_endpoints, prior_endpoints, agent_identity, candidate_endpoint) ==",
12137            prefix("mob_machine_member_peer_id_available_for_identity")
12138        )
12139        .expect("write to string");
12140        pushln!(
12141            out,
12142            "    /\\ \\A other_identity \\in DOMAIN current_endpoints : other_identity = agent_identity \\/ current_endpoints[other_identity].peer_id /= candidate_endpoint.peer_id"
12143        );
12144        pushln!(
12145            out,
12146            "    /\\ \\A other_identity \\in DOMAIN prior_endpoints : other_identity = agent_identity \\/ \\A endpoint \\in prior_endpoints[other_identity] : endpoint.peer_id /= candidate_endpoint.peer_id"
12147        );
12148        writeln!(
12149            out,
12150            "{}(edges, agent_identity) ==",
12151            prefix("mob_machine_member_has_no_external_peer_edges")
12152        )
12153        .expect("write to string");
12154        pushln!(
12155            out,
12156            "    \\A edge \\in edges : edge.local /= agent_identity"
12157        );
12158        writeln!(
12159            out,
12160            "{}(all_prior_endpoints, agent_identity, current_endpoint, next_endpoint) ==",
12161            prefix("mob_machine_member_prior_peer_endpoints_after_migration")
12162        )
12163        .expect("write to string");
12164        pushln!(
12165            out,
12166            "    LET prior == IF agent_identity \\in DOMAIN all_prior_endpoints THEN all_prior_endpoints[agent_identity] ELSE {{}}"
12167        );
12168        pushln!(
12169            out,
12170            "        retained == {{ endpoint \\in (prior \\cup {{current_endpoint}}) : endpoint.peer_id /= next_endpoint.peer_id }}"
12171        );
12172        pushln!(out, "    IN IF retained = {{}}");
12173        pushln!(
12174            out,
12175            "       THEN [id \\in (DOMAIN all_prior_endpoints \\ {{agent_identity}}) |-> all_prior_endpoints[id]]"
12176        );
12177        pushln!(
12178            out,
12179            "       ELSE [id \\in (DOMAIN all_prior_endpoints \\cup {{agent_identity}}) |-> IF id = agent_identity THEN retained ELSE all_prior_endpoints[id]]"
12180        );
12181        writeln!(
12182            out,
12183            "{}(endpoint_identity, migrated_identity, retained_peer_endpoint, current_peer_ids) ==",
12184            prefix("mob_machine_member_endpoint_migration_cleanup_peer_id")
12185        )
12186        .expect("write to string");
12187        pushln!(
12188            out,
12189            "    IF endpoint_identity = migrated_identity THEN retained_peer_endpoint.peer_id ELSE current_peer_ids[endpoint_identity]"
12190        );
12191        writeln!(
12192            out,
12193            "{}(edge) == edge.a",
12194            prefix("mob_machine_wiring_edge_a")
12195        )
12196        .expect("write to string");
12197        writeln!(
12198            out,
12199            "{}(edge) == edge.b",
12200            prefix("mob_machine_wiring_edge_b")
12201        )
12202        .expect("write to string");
12203        writeln!(
12204            out,
12205            "{}(edge, agent_identity) == edge.a = agent_identity \\/ edge.b = agent_identity",
12206            prefix("mob_machine_wiring_edge_contains_identity")
12207        )
12208        .expect("write to string");
12209        writeln!(
12210            out,
12211            "{}({}, {}, agent_identity) ==",
12212            prefix("mob_machine_member_peer_overlay_complete"),
12213            local("wiring_edges"),
12214            local("member_peer_endpoints")
12215        )
12216        .expect("write to string");
12217        pushln!(
12218            out,
12219            "    \\A edge \\in {}: IF edge.a = agent_identity THEN edge.b \\in DOMAIN {} ELSE IF edge.b = agent_identity THEN edge.a \\in DOMAIN {} ELSE TRUE",
12220            local("wiring_edges"),
12221            local("member_peer_endpoints"),
12222            local("member_peer_endpoints")
12223        );
12224        writeln!(
12225            out,
12226            "{}({}, {}, {}, agent_identity) ==",
12227            prefix("mob_machine_member_peer_overlay"),
12228            local("wiring_edges"),
12229            local("member_peer_endpoints"),
12230            local("external_peer_edges")
12231        )
12232        .expect("write to string");
12233        pushln!(
12234            out,
12235            "    LET outgoing_edges == {{ edge \\in {} : edge.a = agent_identity /\\ edge.b \\in DOMAIN {} }}",
12236            local("wiring_edges"),
12237            local("member_peer_endpoints")
12238        );
12239        pushln!(
12240            out,
12241            "        incoming_edges == {{ edge \\in {} : edge.b = agent_identity /\\ edge.a \\in DOMAIN {} }}",
12242            local("wiring_edges"),
12243            local("member_peer_endpoints")
12244        );
12245        pushln!(
12246            out,
12247            "        local_external_edges == {{ edge \\in {} : edge.local = agent_identity }}",
12248            local("external_peer_edges")
12249        );
12250        pushln!(
12251            out,
12252            "    IN {{ {}[edge.b] : edge \\in outgoing_edges }}",
12253            local("member_peer_endpoints")
12254        );
12255        pushln!(
12256            out,
12257            "       \\cup {{ {}[edge.a] : edge \\in incoming_edges }}",
12258            local("member_peer_endpoints")
12259        );
12260        pushln!(
12261            out,
12262            "       \\cup {{ [name |-> edge.endpoint.name, peer_id |-> edge.endpoint.peer_id, address |-> edge.endpoint.address, signing_key |-> edge.endpoint.signing_key, transport |-> \"Tcp\"] : edge \\in local_external_edges }}"
12263        );
12264        writeln!(
12265            out,
12266            "{}({}, a_identity, b_identity) == \\E edge \\in {}: (edge.a = a_identity /\\ edge.b = b_identity) \\/ (edge.a = b_identity /\\ edge.b = a_identity)",
12267            prefix("mob_machine_wiring_contains_pair"),
12268            local("wiring_edges"),
12269            local("wiring_edges")
12270        )
12271        .expect("write to string");
12272        writeln!(
12273            out,
12274            "{}({}, {}, agent_identity, excluded_identity) ==",
12275            prefix("mob_machine_member_peer_overlay_without_identity_complete"),
12276            local("wiring_edges"),
12277            local("member_peer_endpoints")
12278        )
12279        .expect("write to string");
12280        pushln!(
12281            out,
12282            "    \\A edge \\in {}: IF edge.a = agent_identity /\\ edge.b # excluded_identity THEN edge.b \\in DOMAIN {} ELSE IF edge.b = agent_identity /\\ edge.a # excluded_identity THEN edge.a \\in DOMAIN {} ELSE TRUE",
12283            local("wiring_edges"),
12284            local("member_peer_endpoints"),
12285            local("member_peer_endpoints")
12286        );
12287        writeln!(
12288            out,
12289            "{}({}, {}, {}, agent_identity, excluded_identity) ==",
12290            prefix("mob_machine_member_peer_overlay_without_identity"),
12291            local("wiring_edges"),
12292            local("member_peer_endpoints"),
12293            local("external_peer_edges")
12294        )
12295        .expect("write to string");
12296        pushln!(
12297            out,
12298            "    LET outgoing_edges == {{ edge \\in {} : edge.a = agent_identity /\\ edge.b # excluded_identity /\\ edge.b \\in DOMAIN {} }}",
12299            local("wiring_edges"),
12300            local("member_peer_endpoints")
12301        );
12302        pushln!(
12303            out,
12304            "        incoming_edges == {{ edge \\in {} : edge.b = agent_identity /\\ edge.a # excluded_identity /\\ edge.a \\in DOMAIN {} }}",
12305            local("wiring_edges"),
12306            local("member_peer_endpoints")
12307        );
12308        pushln!(
12309            out,
12310            "        local_external_edges == {{ edge \\in {} : edge.local = agent_identity }}",
12311            local("external_peer_edges")
12312        );
12313        pushln!(
12314            out,
12315            "    IN {{ {}[edge.b] : edge \\in outgoing_edges }}",
12316            local("member_peer_endpoints")
12317        );
12318        pushln!(
12319            out,
12320            "       \\cup {{ {}[edge.a] : edge \\in incoming_edges }}",
12321            local("member_peer_endpoints")
12322        );
12323        pushln!(
12324            out,
12325            "       \\cup {{ [name |-> edge.endpoint.name, peer_id |-> edge.endpoint.peer_id, address |-> edge.endpoint.address, signing_key |-> edge.endpoint.signing_key, transport |-> \"Tcp\"] : edge \\in local_external_edges }}"
12326        );
12327        writeln!(
12328            out,
12329            "{}({}, {}, {}, agent_identity, excluded_identity) ==",
12330            prefix("mob_machine_member_peer_overlay_without_identity_peer_ids_unique"),
12331            local("wiring_edges"),
12332            local("member_peer_endpoints"),
12333            local("external_peer_edges")
12334        )
12335        .expect("write to string");
12336        writeln!(
12337            out,
12338            "    LET overlay == {}({}, {}, {}, agent_identity, excluded_identity) IN Cardinality(overlay) = Cardinality({{endpoint.peer_id : endpoint \\in overlay}})",
12339            prefix("mob_machine_member_peer_overlay_without_identity"),
12340            local("wiring_edges"),
12341            local("member_peer_endpoints"),
12342            local("external_peer_edges")
12343        )
12344        .expect("write to string");
12345        writeln!(
12346            out,
12347            "{}({}, {}, {}, agent_identity) ==",
12348            prefix("mob_machine_member_peer_overlay_peer_ids_unique"),
12349            local("wiring_edges"),
12350            local("member_peer_endpoints"),
12351            local("external_peer_edges")
12352        )
12353        .expect("write to string");
12354        writeln!(
12355            out,
12356            "    LET overlay == {}({}, {}, {}, agent_identity) IN Cardinality(overlay) = Cardinality({{endpoint.peer_id : endpoint \\in overlay}})",
12357            prefix("mob_machine_member_peer_overlay"),
12358            local("wiring_edges"),
12359            local("member_peer_endpoints"),
12360            local("external_peer_edges")
12361        )
12362        .expect("write to string");
12363        writeln!(
12364            out,
12365            "{}(edge, a_identity, b_identity) ==",
12366            prefix("mob_machine_wiring_edge_matches_members")
12367        )
12368        .expect("write to string");
12369        pushln!(out, "    /\\ edge.a = a_identity");
12370        pushln!(out, "    /\\ edge.b = b_identity");
12371        writeln!(
12372            out,
12373            "{}(all_statuses, run_id, step_id, status) ==",
12374            prefix("mob_machine_run_step_status_after_set")
12375        )
12376        .expect("write to string");
12377        pushln!(
12378            out,
12379            "    LET current == IF run_id \\in DOMAIN all_statuses THEN all_statuses[run_id] ELSE [x \\in {{}} |-> None]"
12380        );
12381        pushln!(
12382            out,
12383            "    IN MapSet(all_statuses, run_id, MapSet(current, step_id, Some(status)))"
12384        );
12385        writeln!(
12386            out,
12387            "{}(all_statuses, run_id) ==",
12388            prefix("mob_machine_run_step_status_after_cancel_unfinished")
12389        )
12390        .expect("write to string");
12391        pushln!(
12392            out,
12393            "    LET current == IF run_id \\in DOMAIN all_statuses THEN all_statuses[run_id] ELSE [x \\in {{}} |-> None]"
12394        );
12395        pushln!(
12396            out,
12397            "        folded == [step_id \\in DOMAIN current |-> IF current[step_id] = None \\/ current[step_id] = Some(\"Dispatched\") THEN Some(\"Canceled\") ELSE current[step_id]]"
12398        );
12399        pushln!(out, "    IN MapSet(all_statuses, run_id, folded)");
12400        writeln!(
12401            out,
12402            "{}(all_values, run_id, step_id, value) ==",
12403            prefix("mob_machine_run_step_bool_after_set")
12404        )
12405        .expect("write to string");
12406        pushln!(
12407            out,
12408            "    LET current == IF run_id \\in DOMAIN all_values THEN all_values[run_id] ELSE [x \\in {{}} |-> FALSE]"
12409        );
12410        pushln!(
12411            out,
12412            "    IN MapSet(all_values, run_id, MapSet(current, step_id, value))"
12413        );
12414        writeln!(
12415            out,
12416            "{}(all_results, run_id, step_id, result) ==",
12417            prefix("mob_machine_run_step_condition_result_after_set")
12418        )
12419        .expect("write to string");
12420        pushln!(
12421            out,
12422            "    LET current == IF run_id \\in DOMAIN all_results THEN all_results[run_id] ELSE [x \\in {{}} |-> None]"
12423        );
12424        pushln!(
12425            out,
12426            "    IN MapSet(all_results, run_id, MapSet(current, step_id, Some(result)))"
12427        );
12428        writeln!(
12429            out,
12430            "{}(all_counts, run_id, step_id, value) ==",
12431            prefix("mob_machine_run_step_u64_after_set")
12432        )
12433        .expect("write to string");
12434        pushln!(
12435            out,
12436            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12437        );
12438        pushln!(
12439            out,
12440            "    IN MapSet(all_counts, run_id, MapSet(current, step_id, value))"
12441        );
12442        writeln!(
12443            out,
12444            "{}(all_counts, run_id, step_id, delta) ==",
12445            prefix("mob_machine_run_step_u64_after_increment")
12446        )
12447        .expect("write to string");
12448        pushln!(
12449            out,
12450            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12451        );
12452        pushln!(
12453            out,
12454            "        current_value == IF step_id \\in DOMAIN current THEN current[step_id] ELSE 0"
12455        );
12456        pushln!(
12457            out,
12458            "    IN MapSet(all_counts, run_id, MapSet(current, step_id, current_value + delta))"
12459        );
12460        writeln!(
12461            out,
12462            "{}(all_counts, run_id, retry_key, delta) ==",
12463            prefix("mob_machine_run_retry_count_after_increment")
12464        )
12465        .expect("write to string");
12466        pushln!(
12467            out,
12468            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12469        );
12470        pushln!(
12471            out,
12472            "        current_value == IF retry_key \\in DOMAIN current THEN current[retry_key] ELSE 0"
12473        );
12474        pushln!(
12475            out,
12476            "    IN MapSet(all_counts, run_id, MapSet(current, retry_key, current_value + delta))"
12477        );
12478        writeln!(
12479            out,
12480            "{}(all_values, frame_id, node_id, value) ==",
12481            prefix("mob_machine_frame_node_bool_after_set")
12482        )
12483        .expect("write to string");
12484        pushln!(
12485            out,
12486            "    LET current == IF frame_id \\in DOMAIN all_values THEN all_values[frame_id] ELSE [x \\in {{}} |-> FALSE]"
12487        );
12488        pushln!(
12489            out,
12490            "    IN MapSet(all_values, frame_id, MapSet(current, node_id, value))"
12491        );
12492        writeln!(
12493            out,
12494            "{}(status) == status \\in {{\"Completed\", \"Failed\", \"Skipped\", \"Canceled\"}}",
12495            prefix("mob_machine_node_terminal")
12496        )
12497        .expect("write to string");
12498        writeln!(
12499            out,
12500            "{}(status) ==",
12501            prefix("mob_machine_step_status_from_frame_node_status")
12502        )
12503        .expect("write to string");
12504        pushln!(out, "    IF status = \"Completed\" THEN \"Completed\"");
12505        pushln!(out, "    ELSE IF status = \"Skipped\" THEN \"Skipped\"");
12506        pushln!(out, "    ELSE IF status = \"Failed\" THEN \"Failed\"");
12507        pushln!(out, "    ELSE IF status = \"Canceled\" THEN \"Canceled\"");
12508        pushln!(out, "    ELSE \"Dispatched\"");
12509        writeln!(
12510            out,
12511            "{}(all_statuses, frame_branches, ordered_nodes_by_frame, frame_id, node_id) ==",
12512            prefix("mob_machine_frame_node_status_after_admit")
12513        )
12514        .expect("write to string");
12515        pushln!(
12516            out,
12517            "    LET current == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12518        );
12519        pushln!(
12520            out,
12521            "        branches == IF frame_id \\in DOMAIN frame_branches THEN frame_branches[frame_id] ELSE [x \\in {{}} |-> None]"
12522        );
12523        pushln!(
12524            out,
12525            "        admitted_branch == IF node_id \\in DOMAIN branches THEN branches[node_id] ELSE None"
12526        );
12527        pushln!(
12528            out,
12529            "        after_branch_reservation == [candidate \\in DOMAIN current |->"
12530        );
12531        pushln!(out, "            IF admitted_branch # None");
12532        pushln!(out, "                /\\ candidate # node_id");
12533        pushln!(out, "                /\\ candidate \\in DOMAIN branches");
12534        pushln!(
12535            out,
12536            "                /\\ branches[candidate] = admitted_branch"
12537        );
12538        pushln!(out, "                /\\ current[candidate] = \"Ready\"");
12539        pushln!(out, "            THEN \"Pending\" ELSE current[candidate]]");
12540        pushln!(
12541            out,
12542            "        after_admit == MapSet(after_branch_reservation, node_id, \"Running\")"
12543        );
12544        pushln!(out, "    IN MapSet(all_statuses, frame_id, after_admit)");
12545        writeln!(
12546            out,
12547            "{}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id) ==",
12548            prefix("mob_machine_frame_ready_queue_after_terminal")
12549        )
12550        .expect("write to string");
12551        pushln!(
12552            out,
12553            "    LET statuses == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12554        );
12555        pushln!(
12556            out,
12557            "        ordered == IF frame_id \\in DOMAIN ordered_nodes_by_frame THEN ordered_nodes_by_frame[frame_id] ELSE <<>>"
12558        );
12559        pushln!(
12560            out,
12561            "    IN MapSet(all_ready_queues, frame_id, SelectSeq(ordered, LAMBDA candidate: candidate \\in DOMAIN statuses /\\ statuses[candidate] = \"Ready\"))"
12562        );
12563        writeln!(
12564            out,
12565            "{}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id) ==",
12566            prefix("mob_machine_frame_ready_queue_after_admit")
12567        )
12568        .expect("write to string");
12569        writeln!(
12570            out,
12571            "    {}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id)",
12572            prefix("mob_machine_frame_ready_queue_after_terminal")
12573        )
12574        .expect("write to string");
12575        writeln!(
12576            out,
12577            "{}(current, branches, node_id, terminal_status) ==",
12578            prefix("mob_machine_frame_node_status_after_terminal_branch")
12579        )
12580        .expect("write to string");
12581        pushln!(
12582            out,
12583            "    LET after_terminal == MapSet(current, node_id, terminal_status)"
12584        );
12585        pushln!(out, "    IN [candidate \\in DOMAIN after_terminal |->");
12586        pushln!(
12587            out,
12588            "        IF terminal_status = \"Completed\" /\\ candidate # node_id"
12589        );
12590        pushln!(
12591            out,
12592            "            /\\ candidate \\in DOMAIN branches /\\ node_id \\in DOMAIN branches"
12593        );
12594        pushln!(out, "            /\\ branches[node_id] # None");
12595        pushln!(
12596            out,
12597            "            /\\ branches[candidate] = branches[node_id]"
12598        );
12599        writeln!(
12600            out,
12601            "            /\\ ~{}(after_terminal[candidate])",
12602            prefix("mob_machine_node_terminal")
12603        )
12604        .expect("write to string");
12605        pushln!(
12606            out,
12607            "            /\\ after_terminal[candidate] # \"Running\""
12608        );
12609        pushln!(
12610            out,
12611            "        THEN \"Skipped\" ELSE after_terminal[candidate]]"
12612        );
12613        writeln!(
12614            out,
12615            "{}(after_branch, dependencies, dependency_modes) ==",
12616            prefix("mob_machine_frame_node_status_after_terminal_dependencies")
12617        )
12618        .expect("write to string");
12619        pushln!(out, "    [candidate \\in DOMAIN after_branch |->");
12620        pushln!(
12621            out,
12622            "        IF after_branch[candidate] # \"Pending\" THEN after_branch[candidate]"
12623        );
12624        pushln!(
12625            out,
12626            "        ELSE LET deps == IF candidate \\in DOMAIN dependencies THEN dependencies[candidate] ELSE <<>>"
12627        );
12628        pushln!(
12629            out,
12630            "                 mode == IF candidate \\in DOMAIN dependency_modes THEN dependency_modes[candidate] ELSE \"All\""
12631        );
12632        pushln!(out, "                 failed == Len(deps) # 0");
12633        pushln!(
12634            out,
12635            "                     /\\ ((mode = \"All\" /\\ \\E dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] \\in {{\"Failed\", \"Skipped\", \"Canceled\"}})"
12636        );
12637        pushln!(
12638            out,
12639            "                         \\/ (mode = \"Any\" /\\ \\A dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] \\in {{\"Failed\", \"Skipped\", \"Canceled\"}}))"
12640        );
12641        pushln!(out, "                 satisfied == Len(deps) = 0");
12642        pushln!(
12643            out,
12644            "                     \\/ (mode = \"All\" /\\ \\A dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] = \"Completed\")"
12645        );
12646        pushln!(
12647            out,
12648            "                     \\/ (mode = \"Any\" /\\ \\E dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] = \"Completed\")"
12649        );
12650        pushln!(
12651            out,
12652            "             IN IF failed THEN \"Skipped\" ELSE IF satisfied THEN \"Ready\" ELSE after_branch[candidate]]"
12653        );
12654        writeln!(
12655            out,
12656            "{}(all_statuses, frame_branches, ordered_nodes_by_frame, dependencies_by_frame, dependency_modes_by_frame, frame_id, node_id, terminal_status) ==",
12657            prefix("mob_machine_frame_node_status_after_terminal")
12658        )
12659        .expect("write to string");
12660        pushln!(
12661            out,
12662            "    LET current == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12663        );
12664        pushln!(
12665            out,
12666            "        branches == IF frame_id \\in DOMAIN frame_branches THEN frame_branches[frame_id] ELSE [x \\in {{}} |-> None]"
12667        );
12668        pushln!(
12669            out,
12670            "        dependencies == IF frame_id \\in DOMAIN dependencies_by_frame THEN dependencies_by_frame[frame_id] ELSE [x \\in {{}} |-> <<>>]"
12671        );
12672        pushln!(
12673            out,
12674            "        dependency_modes == IF frame_id \\in DOMAIN dependency_modes_by_frame THEN dependency_modes_by_frame[frame_id] ELSE [x \\in {{}} |-> \"All\"]"
12675        );
12676        writeln!(
12677            out,
12678            "        after_branch == {}(current, branches, node_id, terminal_status)",
12679            prefix("mob_machine_frame_node_status_after_terminal_branch")
12680        )
12681        .expect("write to string");
12682        writeln!(
12683            out,
12684            "        after_dependencies == {}(after_branch, dependencies, dependency_modes)",
12685            prefix("mob_machine_frame_node_status_after_terminal_dependencies")
12686        )
12687        .expect("write to string");
12688        pushln!(
12689            out,
12690            "    IN MapSet(all_statuses, frame_id, after_dependencies)"
12691        );
12692        // Operator instructions: the snapshot natives below are defined over
12693        // the session document's slot-set natives (the body bytes of a slot
12694        // set's Active slots), rendered for this machine too.
12695        self.render_session_document_native_helpers(out);
12696        // The widest member snapshot the records allow: the shared records
12697        // (every slot that is not member-targeted) plus the most one name
12698        // holds of its own, alone or together with what another name's
12699        // records pass to that name's forks (any name may be seated as a
12700        // fork of another). A slot is member-targeted while its kind is
12701        // Member or MemberAndForks and the member map names it (the Rust
12702        // authorities agree).
12703        writeln!(
12704            out,
12705            "{}(target_kind, target_member) ==",
12706            prefix("mob_machine_instruction_widest_snapshot_slots")
12707        )
12708        .expect("write to string");
12709        pushln!(
12710            out,
12711            "    LET member_slots == {{candidate_slot \\in DOMAIN target_kind : target_kind[candidate_slot] \\in {{\"Member\", \"MemberAndForks\"}} /\\ candidate_slot \\in DOMAIN target_member}}"
12712        );
12713        pushln!(
12714            out,
12715            "        instruction_fork_slots == {{candidate_slot \\in member_slots : target_kind[candidate_slot] = \"MemberAndForks\"}}"
12716        );
12717        pushln!(
12718            out,
12719            "        instruction_member_names == {{target_member[named_slot] : named_slot \\in member_slots}}"
12720        );
12721        pushln!(
12722            out,
12723            "        InstructionOwnOf(named_member) == Cardinality({{own_slot \\in member_slots : target_member[own_slot] = named_member}})"
12724        );
12725        pushln!(
12726            out,
12727            "        InstructionForForksOf(named_member) == Cardinality({{own_slot \\in instruction_fork_slots : target_member[own_slot] = named_member}})"
12728        );
12729        pushln!(
12730            out,
12731            "        instruction_snapshots == {{InstructionOwnOf(named_member) : named_member \\in instruction_member_names}} \\cup {{InstructionOwnOf(name_pair[1]) + InstructionForForksOf(name_pair[2]) : name_pair \\in {{candidate_pair \\in instruction_member_names \\X instruction_member_names : candidate_pair[1] # candidate_pair[2]}}}}"
12732        );
12733        pushln!(
12734            out,
12735            "        widest_own == IF instruction_snapshots = {{}} THEN 0 ELSE CHOOSE snapshot_size \\in instruction_snapshots : \\A other_size \\in instruction_snapshots : snapshot_size >= other_size"
12736        );
12737        pushln!(
12738            out,
12739            "    IN Cardinality(DOMAIN target_kind \\ member_slots) + widest_own"
12740        );
12741        // The same snapshot's Active body bytes; a slot the bytes map does
12742        // not name counts nothing.
12743        writeln!(
12744            out,
12745            "{}(slot_effect, slot_bytes, target_kind, target_member) ==",
12746            prefix("mob_machine_instruction_widest_snapshot_active_bytes")
12747        )
12748        .expect("write to string");
12749        pushln!(
12750            out,
12751            "    LET member_slots == {{candidate_slot \\in DOMAIN slot_effect : candidate_slot \\in DOMAIN target_kind /\\ target_kind[candidate_slot] \\in {{\"Member\", \"MemberAndForks\"}} /\\ candidate_slot \\in DOMAIN target_member}}"
12752        );
12753        pushln!(
12754            out,
12755            "        instruction_fork_slots == {{candidate_slot \\in member_slots : target_kind[candidate_slot] = \"MemberAndForks\"}}"
12756        );
12757        pushln!(
12758            out,
12759            "        instruction_member_names == {{target_member[named_slot] : named_slot \\in member_slots}}"
12760        );
12761        writeln!(
12762            out,
12763            "        ActiveBytesOf(instruction_slots) == {}([instruction_slot \\in instruction_slots |-> slot_effect[instruction_slot]], slot_bytes)",
12764            prefix("session_document_instruction_active_bytes")
12765        )
12766        .expect("write to string");
12767        pushln!(
12768            out,
12769            "        InstructionOwnOf(named_member) == ActiveBytesOf({{own_slot \\in member_slots : target_member[own_slot] = named_member}})"
12770        );
12771        pushln!(
12772            out,
12773            "        InstructionForForksOf(named_member) == ActiveBytesOf({{own_slot \\in instruction_fork_slots : target_member[own_slot] = named_member}})"
12774        );
12775        pushln!(
12776            out,
12777            "        instruction_snapshots == {{InstructionOwnOf(named_member) : named_member \\in instruction_member_names}} \\cup {{InstructionOwnOf(name_pair[1]) + InstructionForForksOf(name_pair[2]) : name_pair \\in {{candidate_pair \\in instruction_member_names \\X instruction_member_names : candidate_pair[1] # candidate_pair[2]}}}}"
12778        );
12779        pushln!(
12780            out,
12781            "        widest_own == IF instruction_snapshots = {{}} THEN 0 ELSE CHOOSE snapshot_size \\in instruction_snapshots : \\A other_size \\in instruction_snapshots : snapshot_size >= other_size"
12782        );
12783        pushln!(
12784            out,
12785            "    IN ActiveBytesOf(DOMAIN slot_effect \\ member_slots) + widest_own"
12786        );
12787        // The records of the widest member snapshot once a write is applied:
12788        // the widest snapshot of the record maps the write leaves, where the
12789        // slot takes the write's kind and names the write's member or no
12790        // member (the Rust authorities agree, without building those maps).
12791        writeln!(
12792            out,
12793            "{}(target_kind, target_member, slot, kind, member) ==",
12794            prefix("mob_machine_instruction_write_snapshot_slots")
12795        )
12796        .expect("write to string");
12797        pushln!(out, "    LET kind_after == MapSet(target_kind, slot, kind)");
12798        pushln!(
12799            out,
12800            "        member_after == IF member = None THEN [other_slot \\in DOMAIN target_member \\ {{slot}} |-> target_member[other_slot]] ELSE MapSet(target_member, slot, member.value)"
12801        );
12802        writeln!(
12803            out,
12804            "    IN {}(kind_after, member_after)",
12805            prefix("mob_machine_instruction_widest_snapshot_slots")
12806        )
12807        .expect("write to string");
12808        // The same snapshot's Active body bytes, with the written slot
12809        // Active at its body bytes.
12810        writeln!(
12811            out,
12812            "{}(slot_effect, slot_bytes, target_kind, target_member, slot, body_bytes, kind, member) ==",
12813            prefix("mob_machine_instruction_write_snapshot_active_bytes")
12814        )
12815        .expect("write to string");
12816        pushln!(
12817            out,
12818            "    LET effect_after == MapSet(slot_effect, slot, \"Active\")"
12819        );
12820        pushln!(
12821            out,
12822            "        bytes_after == MapSet(slot_bytes, slot, body_bytes)"
12823        );
12824        pushln!(out, "        kind_after == MapSet(target_kind, slot, kind)");
12825        pushln!(
12826            out,
12827            "        member_after == IF member = None THEN [other_slot \\in DOMAIN target_member \\ {{slot}} |-> target_member[other_slot]] ELSE MapSet(target_member, slot, member.value)"
12828        );
12829        writeln!(
12830            out,
12831            "    IN {}(effect_after, bytes_after, kind_after, member_after)",
12832            prefix("mob_machine_instruction_widest_snapshot_active_bytes")
12833        )
12834        .expect("write to string");
12835    }
12836
12837    fn render_transition(&mut self, out: &mut String, transition: &TransitionSchema) {
12838        let binding_types = self.binding_type_map(transition);
12839        let binding_env = transition
12840            .on
12841            .bindings()
12842            .iter()
12843            .map(|binding| {
12844                (
12845                    binding.as_str().to_owned(),
12846                    self.local_binding_name(binding.as_str()),
12847                )
12848            })
12849            .collect::<BTreeMap<String, _>>();
12850        let params = transition
12851            .on
12852            .bindings()
12853            .iter()
12854            .map(|binding| {
12855                binding_env
12856                    .get(binding.as_str())
12857                    .cloned()
12858                    .unwrap_or_else(|| binding.as_str().to_owned())
12859            })
12860            .collect::<Vec<_>>()
12861            .join(", ");
12862        if params.is_empty() {
12863            writeln!(out, "{} ==", transition.name);
12864        } else {
12865            pushln!(out, "{}({}) ==", transition.name, params);
12866        }
12867
12868        let from_guard = if transition.from.len() == 1 {
12869            format!("phase = {}", tla_string(&transition.from[0]))
12870        } else {
12871            transition
12872                .from
12873                .iter()
12874                .map(|phase| format!("phase = {}", tla_string(phase)))
12875                .collect::<Vec<_>>()
12876                .join(" \\/ ")
12877        };
12878        pushln!(out, "    /\\ {}", from_guard);
12879
12880        let mut env = self
12881            .schema
12882            .state
12883            .fields
12884            .iter()
12885            .map(|field| {
12886                (
12887                    field.name.as_str().to_owned(),
12888                    field.name.as_str().to_owned(),
12889                )
12890            })
12891            .collect::<BTreeMap<String, _>>();
12892
12893        for guard in &transition.guards {
12894            writeln!(
12895                out,
12896                "    /\\ {}",
12897                self.render_guard(guard, &env, &binding_env, &binding_types)
12898            )
12899            .expect("write to string");
12900        }
12901
12902        env = self.compile_updates(
12903            transition.name.as_str(),
12904            &env,
12905            &binding_env,
12906            &binding_types,
12907            &transition.updates,
12908        );
12909
12910        pushln!(out, "    /\\ phase' = {}", tla_string(&transition.to));
12911        pushln!(out, "    /\\ model_step_count' = model_step_count + 1");
12912        let touched = self
12913            .schema
12914            .state
12915            .fields
12916            .iter()
12917            .filter_map(|field| {
12918                let next = env.get(field.name.as_str())?;
12919                if next != field.name.as_str() {
12920                    Some((field.name.as_str(), next.as_str()))
12921                } else {
12922                    None
12923                }
12924            })
12925            .collect::<Vec<_>>();
12926
12927        for (field, expr) in &touched {
12928            pushln!(out, "    /\\ {}' = {}", field, expr);
12929        }
12930
12931        let unchanged = self
12932            .schema
12933            .state
12934            .fields
12935            .iter()
12936            .filter(|field| !touched.iter().any(|(name, _)| *name == field.name.as_str()))
12937            .map(|field| field.name.as_str().to_owned())
12938            .collect::<Vec<_>>();
12939        if !unchanged.is_empty() {
12940            // Machine frames are never chunked: the split policy is a
12941            // composition-scale TLC mitigation, and applying it here would
12942            // change the emitted formula for wide machines.
12943            let name = self
12944                .unchanged_frames
12945                .intern(unchanged_frame_body(&unchanged, None));
12946            pushln!(out, "    /\\ {name}");
12947        }
12948    }
12949
12950    fn render_guard(
12951        &self,
12952        guard: &Guard,
12953        env: &BTreeMap<String, String>,
12954        binding_env: &BTreeMap<String, String>,
12955        binding_types: &BTreeMap<String, TypeRef>,
12956    ) -> String {
12957        self.render_expr_with_types(&guard.expr, env, binding_env, binding_types)
12958    }
12959
12960    fn binding_type_map(&self, transition: &TransitionSchema) -> BTreeMap<String, TypeRef> {
12961        let mut map = BTreeMap::new();
12962        if let Some(variant) = transition_trigger_variant(self.schema, transition) {
12963            for binding in transition.on.bindings() {
12964                if let Some(field) = variant.fields.iter().find(|field| field.name == *binding) {
12965                    map.insert(binding.as_str().to_owned(), field.ty.clone());
12966                }
12967            }
12968        }
12969        map
12970    }
12971
12972    fn local_binding_name(&self, name: impl AsRef<str>) -> String {
12973        let name = name.as_ref();
12974        let candidate = tla_ident(name);
12975        if candidate == "phase"
12976            || self
12977                .schema
12978                .state
12979                .fields
12980                .iter()
12981                .any(|field| field.name.as_str() == name)
12982        {
12983            format!("arg_{candidate}")
12984        } else {
12985            candidate
12986        }
12987    }
12988
12989    fn binding_domain_for_type(&self, ty: &TypeRef) -> String {
12990        match ty {
12991            TypeRef::Bool => "BOOLEAN".into(),
12992            TypeRef::U32 | TypeRef::U64 => "0..2".into(),
12993            TypeRef::String => "StringValues".into(),
12994            TypeRef::Named(_)
12995            | TypeRef::Enum(_)
12996            | TypeRef::Seq(_)
12997            | TypeRef::Set(_)
12998            | TypeRef::Option(_)
12999            | TypeRef::Map(_, _) => domain_constant_name(ty),
13000        }
13001    }
13002
13003    /// Payload domain for one bound field of `input`: the declared input
13004    /// field domain if the schema has one, otherwise the type's default.
13005    fn binding_domain_for_binding(
13006        &self,
13007        input: Option<&str>,
13008        binding: &str,
13009        ty: &TypeRef,
13010    ) -> String {
13011        let declared = input.and_then(|input| {
13012            self.schema
13013                .input_field_domain(input, binding)
13014                .map(|domain| (input, domain))
13015        });
13016        match declared {
13017            Some((_, meerkat_machine_schema::InputFieldDomainKind::StateField(state_field))) => {
13018                format!("{{{}}}", state_field.as_str())
13019            }
13020            Some((_, meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(values))) => {
13021                additional_values_domain(&self.binding_domain_for_type(ty), values)
13022            }
13023            // A model constant that each profile's config assigns: the CI
13024            // profile the declared values, the Deep profile those and `0..2`
13025            // for `CiValues`, the field type's whole domain for `CiSamples`.
13026            Some((
13027                input,
13028                meerkat_machine_schema::InputFieldDomainKind::CiValues(_)
13029                | meerkat_machine_schema::InputFieldDomainKind::CiSamples(_),
13030            )) => input_samples_constant_name(input, binding),
13031            None => self.binding_domain_for_type(ty),
13032        }
13033    }
13034
13035    fn compile_updates(
13036        &mut self,
13037        transition_name: &str,
13038        env: &BTreeMap<String, String>,
13039        binding_env: &BTreeMap<String, String>,
13040        binding_types: &BTreeMap<String, TypeRef>,
13041        updates: &[Update],
13042    ) -> BTreeMap<String, String> {
13043        let mut current = env.clone();
13044        for update in updates {
13045            self.apply_update(
13046                transition_name,
13047                &mut current,
13048                binding_env,
13049                binding_types,
13050                update,
13051            );
13052        }
13053        current
13054    }
13055
13056    fn apply_update(
13057        &mut self,
13058        transition_name: &str,
13059        env: &mut BTreeMap<String, String>,
13060        binding_env: &BTreeMap<String, String>,
13061        binding_types: &BTreeMap<String, TypeRef>,
13062        update: &Update,
13063    ) {
13064        match update {
13065            Update::Assign { field, expr } => {
13066                let value = self.render_expr_with_types(expr, env, binding_env, binding_types);
13067                env.insert(field.as_str().to_owned(), value);
13068            }
13069            Update::Increment { field, amount } => {
13070                let current = env
13071                    .get(field.as_str())
13072                    .cloned()
13073                    .unwrap_or_else(|| field.as_str().to_owned());
13074                env.insert(field.as_str().to_owned(), format!("({current}) + {amount}"));
13075            }
13076            Update::Decrement { field, amount } => {
13077                let current = env
13078                    .get(field.as_str())
13079                    .cloned()
13080                    .unwrap_or_else(|| field.as_str().to_owned());
13081                env.insert(field.as_str().to_owned(), format!("({current}) - {amount}"));
13082            }
13083            Update::MapInsert { field, key, value } => {
13084                let current = env
13085                    .get(field.as_str())
13086                    .cloned()
13087                    .unwrap_or_else(|| field.as_str().to_owned());
13088                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
13089                let value_expr =
13090                    self.render_expr_with_types(value, env, binding_env, binding_types);
13091                env.insert(
13092                    field.as_str().to_owned(),
13093                    format!("MapSet({current}, {key_expr}, {value_expr})"),
13094                );
13095            }
13096            Update::MapRemove { field, key } => {
13097                let current = env
13098                    .get(field.as_str())
13099                    .cloned()
13100                    .unwrap_or_else(|| field.as_str().to_owned());
13101                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
13102                env.insert(
13103                    field.as_str().to_owned(),
13104                    format!("MapRemove({current}, {key_expr})"),
13105                );
13106            }
13107            Update::MapIncrement { field, key, amount } => {
13108                let current = env
13109                    .get(field.as_str())
13110                    .cloned()
13111                    .unwrap_or_else(|| field.as_str().to_owned());
13112                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
13113                env.insert(
13114                    field.as_str().to_owned(),
13115                    format!("MapIncrement({current}, {key_expr}, {amount})"),
13116                );
13117            }
13118            Update::MapDecrement { field, key, amount } => {
13119                let current = env
13120                    .get(field.as_str())
13121                    .cloned()
13122                    .unwrap_or_else(|| field.as_str().to_owned());
13123                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
13124                env.insert(
13125                    field.as_str().to_owned(),
13126                    format!("MapDecrement({current}, {key_expr}, {amount})"),
13127                );
13128            }
13129            Update::SetInsert { field, value } => {
13130                // The field's pending value may be an unparenthesized
13131                // conditional (`IF c THEN a ELSE b`); spliced bare as the left
13132                // operand, the ELSE branch would capture the set operator.
13133                let current = env
13134                    .get(field.as_str())
13135                    .map(|value| tla_delimited(value))
13136                    .unwrap_or_else(|| field.as_str().to_owned());
13137                let value_expr =
13138                    self.render_expr_with_types(value, env, binding_env, binding_types);
13139                env.insert(
13140                    field.as_str().to_owned(),
13141                    format!("({current} \\cup {{{value_expr}}})"),
13142                );
13143            }
13144            Update::SetRemove { field, value } => {
13145                // The field's pending value may be an unparenthesized
13146                // conditional (`IF c THEN a ELSE b`); spliced bare as the left
13147                // operand, the ELSE branch would capture the set operator.
13148                let current = env
13149                    .get(field.as_str())
13150                    .map(|value| tla_delimited(value))
13151                    .unwrap_or_else(|| field.as_str().to_owned());
13152                let value_expr =
13153                    self.render_expr_with_types(value, env, binding_env, binding_types);
13154                env.insert(
13155                    field.as_str().to_owned(),
13156                    format!("({current} \\ {{{value_expr}}})"),
13157                );
13158            }
13159            Update::SeqAppend { field, value } => {
13160                let current = env
13161                    .get(field.as_str())
13162                    .cloned()
13163                    .unwrap_or_else(|| field.as_str().to_owned());
13164                let value_expr =
13165                    self.render_expr_with_types(value, env, binding_env, binding_types);
13166                env.insert(
13167                    field.as_str().to_owned(),
13168                    format!("Append({current}, {value_expr})"),
13169                );
13170            }
13171            Update::SeqPrepend { field, values } => {
13172                let current = env
13173                    .get(field.as_str())
13174                    .cloned()
13175                    .unwrap_or_else(|| field.as_str().to_owned());
13176                let value_expr =
13177                    self.render_expr_with_types(values, env, binding_env, binding_types);
13178                env.insert(
13179                    field.as_str().to_owned(),
13180                    format!("({value_expr} \\o {current})"),
13181                );
13182            }
13183            Update::SeqPopFront { field } => {
13184                let current = env
13185                    .get(field.as_str())
13186                    .cloned()
13187                    .unwrap_or_else(|| field.as_str().to_owned());
13188                env.insert(field.as_str().to_owned(), format!("Tail({current})"));
13189            }
13190            Update::SeqRemoveValue { field, value } => {
13191                let current = env
13192                    .get(field.as_str())
13193                    .cloned()
13194                    .unwrap_or_else(|| field.as_str().to_owned());
13195                let value_expr =
13196                    self.render_expr_with_types(value, env, binding_env, binding_types);
13197                env.insert(
13198                    field.as_str().to_owned(),
13199                    format!("SeqRemove({current}, {value_expr})"),
13200                );
13201            }
13202            Update::SeqRemoveAll { field, values } => {
13203                let current = env
13204                    .get(field.as_str())
13205                    .cloned()
13206                    .unwrap_or_else(|| field.as_str().to_owned());
13207                let value_expr =
13208                    self.render_expr_with_types(values, env, binding_env, binding_types);
13209                env.insert(
13210                    field.as_str().to_owned(),
13211                    format!("SeqRemoveAll({current}, {value_expr})"),
13212                );
13213            }
13214            Update::Conditional {
13215                condition,
13216                then_updates,
13217                else_updates,
13218            } => {
13219                let base = env.clone();
13220                let mut then_env = base.clone();
13221                for update in then_updates {
13222                    self.apply_update(
13223                        transition_name,
13224                        &mut then_env,
13225                        binding_env,
13226                        binding_types,
13227                        update,
13228                    );
13229                }
13230                let mut else_env = base.clone();
13231                for update in else_updates {
13232                    self.apply_update(
13233                        transition_name,
13234                        &mut else_env,
13235                        binding_env,
13236                        binding_types,
13237                        update,
13238                    );
13239                }
13240                let condition_expr =
13241                    self.render_expr_with_types(condition, &base, binding_env, binding_types);
13242                let touched = union_touched_fields(&base, &then_env, &else_env);
13243                for field in touched {
13244                    let then_expr = then_env
13245                        .get(&field)
13246                        .cloned()
13247                        .unwrap_or_else(|| field.clone());
13248                    let else_expr = else_env
13249                        .get(&field)
13250                        .cloned()
13251                        .unwrap_or_else(|| field.clone());
13252                    env.insert(
13253                        field.clone(),
13254                        format!("IF {condition_expr} THEN {then_expr} ELSE {else_expr}"),
13255                    );
13256                }
13257            }
13258            Update::ForEach {
13259                binding,
13260                over,
13261                updates,
13262            } => {
13263                let helper_index = self.helper_counter;
13264                self.helper_counter += 1;
13265                let over_expr = self.render_expr_with_types(over, env, binding_env, binding_types);
13266                let touched = collect_update_fields(updates);
13267                // Every touched field's fold reads the other fields as they
13268                // were BEFORE the loop: the loop below writes each fold back
13269                // into `env` as it goes, so reading `env` there would hand a
13270                // later field the earlier field's post-loop value (all of its
13271                // iterations already applied), not the value an iteration
13272                // reads in the sequential kernel.
13273                let base_env = env.clone();
13274                let referenced_bindings = collect_update_bindings(updates)
13275                    .into_iter()
13276                    .filter(|item| item != binding)
13277                    .collect::<BTreeSet<_>>();
13278                let referenced_fields = collect_update_fields_exprs(updates)
13279                    .into_iter()
13280                    .filter(|field| {
13281                        touched.contains(field) || base_env.get(field.as_str()) != Some(field)
13282                    })
13283                    .collect::<BTreeSet<_>>();
13284
13285                for field in touched {
13286                    let current = base_env
13287                        .get(&field)
13288                        .cloned()
13289                        .unwrap_or_else(|| field.clone());
13290                    let helper_name = format!(
13291                        "{}_ForEach{}_{}",
13292                        tla_ident(transition_name),
13293                        helper_index,
13294                        tla_ident(&field)
13295                    );
13296                    let collection_kind = infer_collection_kind(over, self.schema, binding_types);
13297
13298                    let mut param_defs = Vec::new();
13299                    let mut call_args = vec![current.clone(), over_expr.clone()];
13300                    let mut helper_binding_env = binding_env.clone();
13301                    helper_binding_env.insert(binding.clone(), binding.clone());
13302                    let mut helper_field_env = self
13303                        .schema
13304                        .state
13305                        .fields
13306                        .iter()
13307                        .map(|item| (item.name.as_str().to_owned(), item.name.as_str().to_owned()))
13308                        .collect::<BTreeMap<String, _>>();
13309                    helper_field_env.insert(field.clone(), "acc".into());
13310
13311                    for outer_binding in &referenced_bindings {
13312                        let param = format!("outer_{}", tla_ident(outer_binding));
13313                        param_defs.push(param.clone());
13314                        call_args.push(
13315                            binding_env
13316                                .get(outer_binding)
13317                                .cloned()
13318                                .unwrap_or_else(|| outer_binding.clone()),
13319                        );
13320                        helper_binding_env.insert(outer_binding.clone(), param);
13321                    }
13322
13323                    for ref_field in &referenced_fields {
13324                        if *ref_field == field {
13325                            continue;
13326                        }
13327                        let current_expr = base_env
13328                            .get(ref_field)
13329                            .cloned()
13330                            .unwrap_or_else(|| ref_field.clone());
13331                        if current_expr != *ref_field {
13332                            let param = format!("captured_{}", tla_ident(ref_field));
13333                            param_defs.push(param.clone());
13334                            call_args.push(current_expr);
13335                            helper_field_env.insert(ref_field.clone(), param);
13336                        }
13337                    }
13338
13339                    let body_expr = self.compile_for_each_field_body(
13340                        &field,
13341                        &helper_field_env,
13342                        &helper_binding_env,
13343                        binding_types,
13344                        updates,
13345                    );
13346
13347                    let helper_def = match collection_kind {
13348                        CollectionKind::Sequence => render_sequence_foreach_helper(
13349                            &helper_name,
13350                            binding,
13351                            &param_defs,
13352                            &body_expr,
13353                        ),
13354                        CollectionKind::Set => render_set_foreach_helper(
13355                            &helper_name,
13356                            binding,
13357                            &param_defs,
13358                            &body_expr,
13359                        ),
13360                    };
13361                    self.helper_defs.push(helper_def);
13362                    env.insert(
13363                        field.clone(),
13364                        format!("{}({})", helper_name, call_args.join(", ")),
13365                    );
13366                }
13367            }
13368        }
13369    }
13370
13371    fn compile_for_each_field_body(
13372        &mut self,
13373        target_field: &str,
13374        env: &BTreeMap<String, String>,
13375        binding_env: &BTreeMap<String, String>,
13376        binding_types: &BTreeMap<String, TypeRef>,
13377        updates: &[Update],
13378    ) -> String {
13379        let mut current = env.clone();
13380        for update in updates {
13381            self.apply_update_for_target(
13382                target_field,
13383                &mut current,
13384                binding_env,
13385                binding_types,
13386                update,
13387            );
13388        }
13389        current
13390            .get(target_field)
13391            .cloned()
13392            .unwrap_or_else(|| target_field.to_owned())
13393    }
13394
13395    fn apply_update_for_target(
13396        &mut self,
13397        target_field: &str,
13398        env: &mut BTreeMap<String, String>,
13399        binding_env: &BTreeMap<String, String>,
13400        binding_types: &BTreeMap<String, TypeRef>,
13401        update: &Update,
13402    ) {
13403        match update {
13404            Update::Conditional {
13405                condition,
13406                then_updates,
13407                else_updates,
13408            } => {
13409                let base = env.clone();
13410                let mut then_env = base.clone();
13411                for update in then_updates {
13412                    self.apply_update_for_target(
13413                        target_field,
13414                        &mut then_env,
13415                        binding_env,
13416                        binding_types,
13417                        update,
13418                    );
13419                }
13420                let mut else_env = base.clone();
13421                for update in else_updates {
13422                    self.apply_update_for_target(
13423                        target_field,
13424                        &mut else_env,
13425                        binding_env,
13426                        binding_types,
13427                        update,
13428                    );
13429                }
13430                let base_expr = base
13431                    .get(target_field)
13432                    .cloned()
13433                    .unwrap_or_else(|| target_field.to_owned());
13434                let then_expr = then_env
13435                    .get(target_field)
13436                    .cloned()
13437                    .unwrap_or_else(|| base_expr.clone());
13438                let else_expr = else_env
13439                    .get(target_field)
13440                    .cloned()
13441                    .unwrap_or_else(|| base_expr.clone());
13442                if then_expr != base_expr || else_expr != base_expr {
13443                    let condition_expr =
13444                        self.render_expr_with_types(condition, &base, binding_env, binding_types);
13445                    env.insert(
13446                        target_field.to_owned(),
13447                        format!("IF {condition_expr} THEN {then_expr} ELSE {else_expr}"),
13448                    );
13449                }
13450            }
13451            Update::ForEach {
13452                binding,
13453                over,
13454                updates,
13455            } => {
13456                let helper_index = self.helper_counter;
13457                self.helper_counter += 1;
13458                let over_expr = self.render_expr_with_types(over, env, binding_env, binding_types);
13459                let helper_name = format!(
13460                    "{}_NestedForEach{}_{}",
13461                    tla_ident(target_field),
13462                    helper_index,
13463                    tla_ident(binding)
13464                );
13465                let collection_kind = infer_collection_kind(over, self.schema, binding_types);
13466                let mut nested_binding_env = binding_env.clone();
13467                nested_binding_env.insert(binding.clone(), binding.clone());
13468                let mut nested_env = env.clone();
13469                nested_env.insert(target_field.to_owned(), "acc".into());
13470                let body_expr = self.compile_for_each_field_body(
13471                    target_field,
13472                    &nested_env,
13473                    &nested_binding_env,
13474                    binding_types,
13475                    updates,
13476                );
13477                let helper_def = match collection_kind {
13478                    CollectionKind::Sequence => {
13479                        render_sequence_foreach_helper(&helper_name, binding, &[], &body_expr)
13480                    }
13481                    CollectionKind::Set => {
13482                        render_set_foreach_helper(&helper_name, binding, &[], &body_expr)
13483                    }
13484                };
13485                self.helper_defs.push(helper_def);
13486                let current = env
13487                    .get(target_field)
13488                    .cloned()
13489                    .unwrap_or_else(|| target_field.to_owned());
13490                env.insert(
13491                    target_field.to_owned(),
13492                    format!("{}({}, {})", helper_name, current, over_expr),
13493                );
13494            }
13495            _ => {
13496                let before = env
13497                    .get(target_field)
13498                    .cloned()
13499                    .unwrap_or_else(|| target_field.to_owned());
13500                self.apply_update(
13501                    &format!("Target{}", target_field),
13502                    env,
13503                    binding_env,
13504                    binding_types,
13505                    update,
13506                );
13507                let after = env
13508                    .get(target_field)
13509                    .cloned()
13510                    .unwrap_or_else(|| target_field.to_owned());
13511                if after == before {
13512                    env.insert(target_field.to_owned(), before);
13513                }
13514            }
13515        }
13516    }
13517
13518    fn render_expr(
13519        &self,
13520        expr: &Expr,
13521        env: &BTreeMap<String, String>,
13522        binding_env: &BTreeMap<String, String>,
13523    ) -> String {
13524        self.render_expr_with_types(expr, env, binding_env, &BTreeMap::new())
13525    }
13526
13527    fn scoped_helper_name(&self, helper: &str) -> String {
13528        match &self.helper_prefix {
13529            Some(prefix) => format!("{prefix}{}", tla_ident(helper)),
13530            None => helper.to_owned(),
13531        }
13532    }
13533
13534    fn render_expr_with_types(
13535        &self,
13536        expr: &Expr,
13537        env: &BTreeMap<String, String>,
13538        binding_env: &BTreeMap<String, String>,
13539        binding_types: &BTreeMap<String, TypeRef>,
13540    ) -> String {
13541        match expr {
13542            Expr::Bool(value) => {
13543                if *value {
13544                    "TRUE".into()
13545                } else {
13546                    "FALSE".into()
13547                }
13548            }
13549            Expr::U64(value) => value.to_string(),
13550            Expr::U64Max => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
13551            Expr::String(value) => tla_string(value),
13552            Expr::NamedVariant { enum_name, variant } => render_named_variant_value(
13553                enum_name.as_str(),
13554                variant.as_str(),
13555                &self.named_bindings,
13556            ),
13557            Expr::FieldAccess { base, field } => format!(
13558                "{}.{}",
13559                self.render_expr_with_types(base, env, binding_env, binding_types),
13560                tla_ident(field.as_str())
13561            ),
13562            Expr::EnumVariantIs { value, variant, .. } => format!(
13563                "({}.tag = {})",
13564                self.render_expr_with_types(value, env, binding_env, binding_types),
13565                tla_string(variant.as_str())
13566            ),
13567            Expr::EnumStringSetPayload {
13568                value,
13569                variant,
13570                field,
13571                ..
13572            } => {
13573                let rendered = self.render_expr_with_types(value, env, binding_env, binding_types);
13574                let tag = tla_string(variant.as_str());
13575                let field = tla_ident(field.as_str());
13576                format!("(IF {rendered}.tag = {tag} THEN {rendered}.{field} ELSE {{}})")
13577            }
13578            Expr::EmptySet => "{}".into(),
13579            Expr::EmptyMap => "[x \\in {} |-> None]".into(),
13580            Expr::SeqLiteral(items) => format!(
13581                "<<{}>>",
13582                items
13583                    .iter()
13584                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13585                    .collect::<Vec<_>>()
13586                    .join(", ")
13587            ),
13588            Expr::CurrentPhase => self.phase_symbol.clone().unwrap_or_else(|| "phase".into()),
13589            Expr::Phase(value) => tla_string(value),
13590            // A field already assigned earlier in the same update block reads
13591            // its pending value, which may be an unparenthesized compound
13592            // (a conditional update renders `IF c THEN a ELSE b`). Spliced bare
13593            // into a larger expression, TLA+ precedence would capture the
13594            // surrounding operator: `IF c THEN a ELSE b = x` parses as
13595            // `IF c THEN a ELSE (b = x)`. Delimit every substituted value.
13596            Expr::Field(name) => match env.get(name.as_str()) {
13597                Some(value) if value != name.as_str() => tla_delimited(value),
13598                Some(value) => value.clone(),
13599                None => name.as_str().to_owned(),
13600            },
13601            Expr::Binding(name) => binding_env
13602                .get(name)
13603                .cloned()
13604                .unwrap_or_else(|| name.clone()),
13605            Expr::Variant(name) => tla_string(name),
13606            Expr::None => "None".into(),
13607            Expr::IfElse {
13608                condition,
13609                then_expr,
13610                else_expr,
13611            } => format!(
13612                "(IF {} THEN {} ELSE {})",
13613                self.render_expr_with_types(condition, env, binding_env, binding_types),
13614                self.render_expr_with_types(then_expr, env, binding_env, binding_types),
13615                self.render_expr_with_types(else_expr, env, binding_env, binding_types)
13616            ),
13617            Expr::Not(inner) => format!(
13618                "~({})",
13619                self.render_expr_with_types(inner, env, binding_env, binding_types)
13620            ),
13621            Expr::And(items) => join_exprs(
13622                &items
13623                    .iter()
13624                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13625                    .collect::<Vec<_>>(),
13626                " /\\ ",
13627            ),
13628            Expr::Or(items) => render_or_short_circuit(
13629                &items
13630                    .iter()
13631                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13632                    .collect::<Vec<_>>(),
13633            ),
13634            Expr::Eq(left, right) => format!(
13635                "({} = {})",
13636                self.render_expr_with_types(left, env, binding_env, binding_types),
13637                self.render_expr_with_types(right, env, binding_env, binding_types)
13638            ),
13639            Expr::Neq(left, right) => format!(
13640                "({} # {})",
13641                self.render_expr_with_types(left, env, binding_env, binding_types),
13642                self.render_expr_with_types(right, env, binding_env, binding_types)
13643            ),
13644            Expr::Add(left, right) => format!(
13645                "({} + {})",
13646                self.render_expr_with_types(left, env, binding_env, binding_types),
13647                self.render_expr_with_types(right, env, binding_env, binding_types)
13648            ),
13649            Expr::Sub(left, right) => format!(
13650                "({} - {})",
13651                self.render_expr_with_types(left, env, binding_env, binding_types),
13652                self.render_expr_with_types(right, env, binding_env, binding_types)
13653            ),
13654            Expr::Gt(left, right) => self.render_ordering(
13655                OrderingOperator::Gt,
13656                left,
13657                right,
13658                env,
13659                binding_env,
13660                binding_types,
13661            ),
13662            Expr::Gte(left, right) => self.render_ordering(
13663                OrderingOperator::Gte,
13664                left,
13665                right,
13666                env,
13667                binding_env,
13668                binding_types,
13669            ),
13670            Expr::Lt(left, right) => self.render_ordering(
13671                OrderingOperator::Lt,
13672                left,
13673                right,
13674                env,
13675                binding_env,
13676                binding_types,
13677            ),
13678            Expr::Lte(left, right) => self.render_ordering(
13679                OrderingOperator::Lte,
13680                left,
13681                right,
13682                env,
13683                binding_env,
13684                binding_types,
13685            ),
13686            Expr::Contains { collection, value } => format!(
13687                "({} \\in {})",
13688                self.render_expr_with_types(value, env, binding_env, binding_types),
13689                self.render_collection_domain(collection, env, binding_env, binding_types)
13690            ),
13691            Expr::MapContainsKey { map, key } => format!(
13692                "({} \\in DOMAIN {})",
13693                self.render_expr_with_types(key, env, binding_env, binding_types),
13694                self.render_expr_with_types(map, env, binding_env, binding_types)
13695            ),
13696            Expr::SeqStartsWith { seq, prefix } => format!(
13697                "StartsWith({}, {})",
13698                self.render_expr_with_types(seq, env, binding_env, binding_types),
13699                self.render_expr_with_types(prefix, env, binding_env, binding_types)
13700            ),
13701            Expr::SeqElements(inner) => format!(
13702                "SeqElements({})",
13703                self.render_expr_with_types(inner, env, binding_env, binding_types)
13704            ),
13705            Expr::Len(inner) => {
13706                // The kernel counts the entries of a sequence, set or map
13707                // alike; TLA+ `Len` is defined only on sequences.
13708                let rendered = self.render_expr_with_types(inner, env, binding_env, binding_types);
13709                match self.infer_expr_type_for_render(inner, binding_types) {
13710                    Some(TypeRef::Map(_, _)) => format!("Cardinality(DOMAIN {rendered})"),
13711                    Some(ty) if self.type_renders_as_set(&ty) => {
13712                        format!("Cardinality({rendered})")
13713                    }
13714                    _ => format!("Len({rendered})"),
13715                }
13716            }
13717            Expr::Count { collection, value } => format!(
13718                "Count({}, {})",
13719                self.render_expr_with_types(collection, env, binding_env, binding_types),
13720                self.render_expr_with_types(value, env, binding_env, binding_types)
13721            ),
13722            Expr::Head(inner) => format!(
13723                "Head({})",
13724                self.render_expr_with_types(inner, env, binding_env, binding_types)
13725            ),
13726            Expr::MapKeys(inner) => format!(
13727                "DOMAIN {}",
13728                self.render_expr_with_types(inner, env, binding_env, binding_types)
13729            ),
13730            Expr::MapGet { map, key } => format!(
13731                "{}",
13732                if self.is_scalar_value_projection(map, key, binding_types) {
13733                    self.render_expr_with_types(map, env, binding_env, binding_types)
13734                } else {
13735                    format!(
13736                        "(IF {} \\in DOMAIN {} THEN {}[{}] ELSE {})",
13737                        self.render_expr_with_types(key, env, binding_env, binding_types),
13738                        self.render_expr_with_types(map, env, binding_env, binding_types),
13739                        self.render_expr_with_types(map, env, binding_env, binding_types),
13740                        self.render_expr_with_types(key, env, binding_env, binding_types),
13741                        self.map_absent_value_expr(map, binding_types)
13742                    )
13743                }
13744            ),
13745            // A populated map literal as a TLC function: `k1 :> v1 @@ k2 :> v2`
13746            // (the TLC module every generated model extends).
13747            Expr::MapLiteral(entries) => format!(
13748                "({})",
13749                entries
13750                    .iter()
13751                    .map(|(key, value)| format!(
13752                        "{} :> {}",
13753                        self.render_expr_with_types(key, env, binding_env, binding_types),
13754                        self.render_expr_with_types(value, env, binding_env, binding_types)
13755                    ))
13756                    .collect::<Vec<_>>()
13757                    .join(" @@ ")
13758            ),
13759            // Strict read: plain function application, so TLC reports an
13760            // error if a reachable state reads a key outside DOMAIN (#1811).
13761            Expr::MapValue { map, key } => format!(
13762                "({})[{}]",
13763                self.render_expr_with_types(map, env, binding_env, binding_types),
13764                self.render_expr_with_types(key, env, binding_env, binding_types)
13765            ),
13766            Expr::Some(inner) => format!(
13767                "Some({})",
13768                self.render_expr_with_types(inner, env, binding_env, binding_types)
13769            ),
13770            Expr::Call { helper, args } => format!(
13771                "{}",
13772                if args.is_empty() {
13773                    self.scoped_helper_name(helper)
13774                } else {
13775                    format!(
13776                        "{}({})",
13777                        self.scoped_helper_name(helper),
13778                        args.iter()
13779                            .map(|arg| self.render_expr_with_types(
13780                                arg,
13781                                env,
13782                                binding_env,
13783                                binding_types
13784                            ))
13785                            .collect::<Vec<_>>()
13786                            .join(", ")
13787                    )
13788                }
13789            ),
13790            Expr::Quantified {
13791                quantifier,
13792                binding,
13793                over,
13794                body,
13795            } => {
13796                let keyword = match quantifier {
13797                    Quantifier::Any => "\\E",
13798                    Quantifier::All => "\\A",
13799                };
13800                let mut nested_bindings = binding_env.clone();
13801                nested_bindings.insert(binding.clone(), binding.clone());
13802                let mut nested_binding_types = binding_types.clone();
13803                if let Some(item_ty) = self.collection_item_type(over, binding_types) {
13804                    nested_binding_types.insert(binding.clone(), item_ty);
13805                }
13806                format!(
13807                    "({} {} \\in {} : {})",
13808                    keyword,
13809                    binding,
13810                    self.render_collection_domain(over, env, binding_env, binding_types),
13811                    self.render_expr_with_types(body, env, &nested_bindings, &nested_binding_types)
13812                )
13813            }
13814        }
13815    }
13816
13817    /// `left op right` for an ordering comparison. With an `Option` operand
13818    /// it takes Rust's order through `OptionLt` / `OptionLe` (see
13819    /// [`TLA_OPTION_ORDER_DEFINITIONS`]); otherwise the TLA+ operator.
13820    fn render_ordering(
13821        &self,
13822        operator: OrderingOperator,
13823        left: &Expr,
13824        right: &Expr,
13825        env: &BTreeMap<String, String>,
13826        binding_env: &BTreeMap<String, String>,
13827        binding_types: &BTreeMap<String, TypeRef>,
13828    ) -> String {
13829        let left_tla = self.render_expr_with_types(left, env, binding_env, binding_types);
13830        let right_tla = self.render_expr_with_types(right, env, binding_env, binding_types);
13831        if !self.is_option_operand(left, binding_types)
13832            && !self.is_option_operand(right, binding_types)
13833        {
13834            let symbol = match operator {
13835                OrderingOperator::Lt => "<",
13836                OrderingOperator::Lte => "<=",
13837                OrderingOperator::Gt => ">",
13838                OrderingOperator::Gte => ">=",
13839            };
13840            return format!("({left_tla} {symbol} {right_tla})");
13841        }
13842        self.option_order_used.set(true);
13843        match operator {
13844            OrderingOperator::Lt => format!("OptionLt({left_tla}, {right_tla})"),
13845            OrderingOperator::Lte => format!("OptionLe({left_tla}, {right_tla})"),
13846            OrderingOperator::Gt => format!("OptionLt({right_tla}, {left_tla})"),
13847            OrderingOperator::Gte => format!("OptionLe({right_tla}, {left_tla})"),
13848        }
13849    }
13850
13851    /// Whether `expr` is an `Option` value: a `None` / `Some` literal, or an
13852    /// operand whose type is `Option<_>` (a field, a trigger binding or helper
13853    /// parameter, a helper call, a map read, the `get_copied` / `get_cloned`
13854    /// lowering).
13855    fn is_option_operand(&self, expr: &Expr, binding_types: &BTreeMap<String, TypeRef>) -> bool {
13856        matches!(expr, Expr::None | Expr::Some(_))
13857            || matches!(
13858                self.infer_expr_type_for_render(expr, binding_types),
13859                Some(TypeRef::Option(_))
13860            )
13861    }
13862
13863    fn infer_expr_type_for_render(
13864        &self,
13865        expr: &Expr,
13866        binding_types: &BTreeMap<String, TypeRef>,
13867    ) -> Option<TypeRef> {
13868        // A projection into a structural record (`restrictions.lifetime.unresolved`)
13869        // takes the declared type of the record field, so `.len()` on a
13870        // field-presence set reached through one renders as `Cardinality`.
13871        if let Expr::FieldAccess { base, field } = expr {
13872            let TypeRef::Named(record) = self.infer_expr_type_for_render(base, binding_types)?
13873            else {
13874                return None;
13875            };
13876            let meerkat_machine_schema::RustTypeAtom::TypePathStruct { fields, .. } =
13877                self.named_bindings.get(record.as_str())?
13878            else {
13879                return None;
13880            };
13881            return match &fields
13882                .iter()
13883                .find(|candidate| candidate.name == *field)?
13884                .atom
13885            {
13886                meerkat_machine_schema::TypePathStructFieldAtom::String => Some(TypeRef::String),
13887                meerkat_machine_schema::TypePathStructFieldAtom::Named(name) => {
13888                    Some(TypeRef::Named(name.clone()))
13889                }
13890                meerkat_machine_schema::TypePathStructFieldAtom::OptionalNamed(name) => {
13891                    Some(TypeRef::Option(Box::new(TypeRef::Named(name.clone()))))
13892                }
13893            };
13894        }
13895        let field_types = self
13896            .schema
13897            .state
13898            .fields
13899            .iter()
13900            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
13901            .collect::<BTreeMap<String, _>>();
13902        let helper_returns = self
13903            .schema
13904            .helpers
13905            .iter()
13906            .chain(self.schema.derived.iter())
13907            .map(|helper| (helper.name.clone(), helper.returns.clone()))
13908            .collect::<BTreeMap<String, _>>();
13909        infer_expr_type(expr, &field_types, &helper_returns, binding_types)
13910    }
13911
13912    fn type_renders_as_set(&self, ty: &TypeRef) -> bool {
13913        match ty {
13914            TypeRef::Set(_) => true,
13915            TypeRef::Named(name) => matches!(
13916                self.named_bindings.get(name.as_str()),
13917                Some(meerkat_machine_schema::RustTypeAtom::TypePathFieldPresenceSet { .. })
13918            ),
13919            TypeRef::Enum(name) => matches!(
13920                self.named_bindings.get(name.as_str()),
13921                Some(meerkat_machine_schema::RustTypeAtom::TypePathFieldPresenceSet { .. })
13922            ),
13923            _ => false,
13924        }
13925    }
13926
13927    fn render_collection_domain(
13928        &self,
13929        over: &Expr,
13930        env: &BTreeMap<String, String>,
13931        binding_env: &BTreeMap<String, String>,
13932        binding_types: &BTreeMap<String, TypeRef>,
13933    ) -> String {
13934        let rendered = self.render_expr_with_types(over, env, binding_env, binding_types);
13935        match self.collection_item_type(over, binding_types) {
13936            Some(_) if self.is_sequence_expr(over, binding_types) => {
13937                format!("SeqElements({rendered})")
13938            }
13939            _ => rendered,
13940        }
13941    }
13942
13943    fn collection_item_type(
13944        &self,
13945        expr: &Expr,
13946        binding_types: &BTreeMap<String, TypeRef>,
13947    ) -> Option<TypeRef> {
13948        match expr {
13949            Expr::Field(name) => self
13950                .schema
13951                .state
13952                .fields
13953                .iter()
13954                .find(|field| field.name == *name)
13955                .and_then(|field| match &field.ty {
13956                    TypeRef::Seq(inner) | TypeRef::Set(inner) => Some((**inner).clone()),
13957                    _ => None,
13958                }),
13959            Expr::Binding(name) => binding_types.get(name).and_then(|ty| match ty {
13960                TypeRef::Seq(inner) | TypeRef::Set(inner) => Some((**inner).clone()),
13961                _ => None,
13962            }),
13963            Expr::EnumStringSetPayload { .. } => Some(TypeRef::String),
13964            Expr::SeqLiteral(items) => {
13965                if let Some(first) = items.first() {
13966                    self.scalar_expr_type(first, binding_types)
13967                } else {
13968                    Some(TypeRef::String)
13969                }
13970            }
13971            Expr::MapKeys(_) | Expr::EmptySet => Some(TypeRef::String),
13972            _ => None,
13973        }
13974    }
13975
13976    fn scalar_expr_type(
13977        &self,
13978        expr: &Expr,
13979        binding_types: &BTreeMap<String, TypeRef>,
13980    ) -> Option<TypeRef> {
13981        match expr {
13982            Expr::Bool(_) => Some(TypeRef::Bool),
13983            Expr::U64(_) | Expr::U64Max => Some(TypeRef::U64),
13984            Expr::String(_) | Expr::Phase(_) | Expr::Variant(_) => Some(TypeRef::String),
13985            Expr::NamedVariant { enum_name, .. } => Some(TypeRef::Enum(enum_name.clone())),
13986            Expr::FieldAccess { .. } => None,
13987            Expr::EnumVariantIs { .. } => Some(TypeRef::Bool),
13988            Expr::EnumStringSetPayload { .. } => Some(TypeRef::Set(Box::new(TypeRef::String))),
13989            Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
13990                self.map_value_type(map, binding_types)
13991            }
13992            Expr::Field(name) => self
13993                .schema
13994                .state
13995                .fields
13996                .iter()
13997                .find(|field| field.name == *name)
13998                .map(|field| &field.ty)
13999                .cloned(),
14000            Expr::Binding(name) => binding_types.get(name).cloned(),
14001            _ => None,
14002        }
14003    }
14004
14005    fn is_scalar_value_projection(
14006        &self,
14007        map: &Expr,
14008        key: &Expr,
14009        binding_types: &BTreeMap<String, TypeRef>,
14010    ) -> bool {
14011        matches!(key, Expr::String(value) if value == "value")
14012            && matches!(
14013                self.scalar_expr_type(map, binding_types),
14014                Some(
14015                    TypeRef::Bool
14016                        | TypeRef::U32
14017                        | TypeRef::U64
14018                        | TypeRef::String
14019                        | TypeRef::Enum(_)
14020                        | TypeRef::Named(_)
14021                )
14022            )
14023    }
14024
14025    fn map_value_type(
14026        &self,
14027        expr: &Expr,
14028        binding_types: &BTreeMap<String, TypeRef>,
14029    ) -> Option<TypeRef> {
14030        match expr {
14031            Expr::Field(name) => self
14032                .schema
14033                .state
14034                .fields
14035                .iter()
14036                .find(|field| field.name == *name)
14037                .and_then(|field| match &field.ty {
14038                    TypeRef::Map(_, value) => Some((**value).clone()),
14039                    _ => None,
14040                }),
14041            Expr::Binding(name) => binding_types.get(name).and_then(|ty| match ty {
14042                TypeRef::Map(_, value) => Some((**value).clone()),
14043                _ => None,
14044            }),
14045            _ => None,
14046        }
14047    }
14048
14049    fn map_absent_value_expr(
14050        &self,
14051        expr: &Expr,
14052        binding_types: &BTreeMap<String, TypeRef>,
14053    ) -> String {
14054        self.map_value_type(expr, binding_types)
14055            .map(|ty| default_absent_map_value_expr(&ty))
14056            .unwrap_or_else(|| "None".into())
14057    }
14058
14059    fn is_sequence_expr(&self, expr: &Expr, binding_types: &BTreeMap<String, TypeRef>) -> bool {
14060        match expr {
14061            Expr::Field(name) => self
14062                .schema
14063                .state
14064                .fields
14065                .iter()
14066                .find(|field| field.name == *name)
14067                .is_some_and(|field| matches!(field.ty, TypeRef::Seq(_))),
14068            Expr::Binding(name) => binding_types
14069                .get(name)
14070                .is_some_and(|ty| matches!(ty, TypeRef::Seq(_))),
14071            Expr::SeqLiteral(_) => true,
14072            _ => false,
14073        }
14074    }
14075}
14076
14077#[derive(Copy, Clone)]
14078enum CollectionKind {
14079    Sequence,
14080    Set,
14081}
14082
14083fn infer_collection_kind(
14084    expr: &Expr,
14085    schema: &MachineSchema,
14086    binding_types: &BTreeMap<String, TypeRef>,
14087) -> CollectionKind {
14088    match expr {
14089        Expr::Field(name) => schema
14090            .state
14091            .fields
14092            .iter()
14093            .find(|field| field.name == *name)
14094            .map(|field| match field.ty {
14095                TypeRef::Set(_) => CollectionKind::Set,
14096                _ => CollectionKind::Sequence,
14097            })
14098            .unwrap_or(CollectionKind::Sequence),
14099        Expr::Binding(name) => binding_types
14100            .get(name)
14101            .map(|ty| match ty {
14102                TypeRef::Set(_) => CollectionKind::Set,
14103                _ => CollectionKind::Sequence,
14104            })
14105            .unwrap_or(CollectionKind::Sequence),
14106        Expr::MapKeys(_) | Expr::EmptySet | Expr::EnumStringSetPayload { .. } => {
14107            CollectionKind::Set
14108        }
14109        _ => CollectionKind::Sequence,
14110    }
14111}
14112
14113fn render_sequence_foreach_helper(
14114    name: &str,
14115    binding: &str,
14116    extra_params: &[String],
14117    body_expr: &str,
14118) -> String {
14119    let mut params = vec!["acc".to_owned(), "items".to_owned()];
14120    params.extend(extra_params.iter().cloned());
14121    let params_str = params.join(", ");
14122    let recurse_args = std::iter::once("next_acc".to_owned())
14123        .chain(std::iter::once("Tail(items)".to_owned()))
14124        .chain(extra_params.iter().cloned())
14125        .collect::<Vec<_>>()
14126        .join(", ");
14127    let recursive_args = std::iter::repeat_n("_", params.len())
14128        .collect::<Vec<_>>()
14129        .join(", ");
14130
14131    format!(
14132        "RECURSIVE {name}({recursive_args})\n{name}({params_str}) == IF Len(items) = 0 THEN acc ELSE LET {binding} == Head(items) IN LET next_acc == {body_expr} IN {name}({recurse_args})"
14133    )
14134}
14135
14136fn render_set_foreach_helper(
14137    name: &str,
14138    binding: &str,
14139    extra_params: &[String],
14140    body_expr: &str,
14141) -> String {
14142    let mut params = vec!["acc".to_owned(), "remaining".to_owned()];
14143    params.extend(extra_params.iter().cloned());
14144    let params_str = params.join(", ");
14145    let recurse_args = std::iter::once("next_acc".to_owned())
14146        .chain(std::iter::once("remaining \\ {item}".to_owned()))
14147        .chain(extra_params.iter().cloned())
14148        .collect::<Vec<_>>()
14149        .join(", ");
14150    let recursive_args = std::iter::repeat_n("_", params.len())
14151        .collect::<Vec<_>>()
14152        .join(", ");
14153
14154    format!(
14155        "RECURSIVE {name}({recursive_args})\n{name}({params_str}) == IF remaining = {{}} THEN acc ELSE LET item == CHOOSE x \\in remaining : TRUE IN LET {binding} == item IN LET next_acc == {body_expr} IN {name}({recurse_args})"
14156    )
14157}
14158
14159fn collect_update_fields(updates: &[Update]) -> BTreeSet<String> {
14160    let mut fields = BTreeSet::new();
14161    for update in updates {
14162        match update {
14163            Update::Assign { field, .. }
14164            | Update::Increment { field, .. }
14165            | Update::Decrement { field, .. }
14166            | Update::MapInsert { field, .. }
14167            | Update::MapIncrement { field, .. }
14168            | Update::MapDecrement { field, .. }
14169            | Update::MapRemove { field, .. }
14170            | Update::SetInsert { field, .. }
14171            | Update::SetRemove { field, .. }
14172            | Update::SeqAppend { field, .. }
14173            | Update::SeqPrepend { field, .. }
14174            | Update::SeqPopFront { field }
14175            | Update::SeqRemoveValue { field, .. }
14176            | Update::SeqRemoveAll { field, .. } => {
14177                fields.insert(field.as_str().to_owned());
14178            }
14179            Update::Conditional {
14180                then_updates,
14181                else_updates,
14182                ..
14183            } => {
14184                fields.extend(collect_update_fields(then_updates));
14185                fields.extend(collect_update_fields(else_updates));
14186            }
14187            Update::ForEach { updates, .. } => {
14188                fields.extend(collect_update_fields(updates));
14189            }
14190        }
14191    }
14192    fields
14193}
14194
14195fn collect_update_bindings(updates: &[Update]) -> BTreeSet<String> {
14196    let mut bindings = BTreeSet::new();
14197    for update in updates {
14198        match update {
14199            Update::Assign { expr, .. } => collect_expr_bindings(expr, &mut bindings),
14200            Update::MapInsert { key, value, .. } => {
14201                collect_expr_bindings(key, &mut bindings);
14202                collect_expr_bindings(value, &mut bindings);
14203            }
14204            Update::MapRemove { key, .. } => {
14205                collect_expr_bindings(key, &mut bindings);
14206            }
14207            Update::MapIncrement { key, .. } | Update::MapDecrement { key, .. } => {
14208                collect_expr_bindings(key, &mut bindings);
14209            }
14210            Update::SetInsert { value, .. }
14211            | Update::SetRemove { value, .. }
14212            | Update::SeqAppend { value, .. }
14213            | Update::SeqRemoveValue { value, .. }
14214            | Update::SeqPrepend { values: value, .. }
14215            | Update::SeqRemoveAll { values: value, .. } => {
14216                collect_expr_bindings(value, &mut bindings);
14217            }
14218            Update::Conditional {
14219                condition,
14220                then_updates,
14221                else_updates,
14222            } => {
14223                collect_expr_bindings(condition, &mut bindings);
14224                bindings.extend(collect_update_bindings(then_updates));
14225                bindings.extend(collect_update_bindings(else_updates));
14226            }
14227            Update::ForEach {
14228                binding,
14229                over,
14230                updates,
14231            } => {
14232                bindings.insert(binding.clone());
14233                collect_expr_bindings(over, &mut bindings);
14234                bindings.extend(collect_update_bindings(updates));
14235            }
14236            Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
14237        }
14238    }
14239    bindings
14240}
14241
14242fn collect_update_fields_exprs(updates: &[Update]) -> BTreeSet<String> {
14243    let mut fields = BTreeSet::new();
14244    for update in updates {
14245        match update {
14246            Update::Assign { expr, .. } => collect_expr_fields(expr, &mut fields),
14247            Update::MapInsert { key, value, .. } => {
14248                collect_expr_fields(key, &mut fields);
14249                collect_expr_fields(value, &mut fields);
14250            }
14251            Update::MapRemove { key, .. } => {
14252                collect_expr_fields(key, &mut fields);
14253            }
14254            Update::MapIncrement { key, .. } | Update::MapDecrement { key, .. } => {
14255                collect_expr_fields(key, &mut fields);
14256            }
14257            Update::SetInsert { value, .. }
14258            | Update::SetRemove { value, .. }
14259            | Update::SeqAppend { value, .. }
14260            | Update::SeqRemoveValue { value, .. }
14261            | Update::SeqPrepend { values: value, .. }
14262            | Update::SeqRemoveAll { values: value, .. } => {
14263                collect_expr_fields(value, &mut fields);
14264            }
14265            Update::Conditional {
14266                condition,
14267                then_updates,
14268                else_updates,
14269            } => {
14270                collect_expr_fields(condition, &mut fields);
14271                fields.extend(collect_update_fields_exprs(then_updates));
14272                fields.extend(collect_update_fields_exprs(else_updates));
14273            }
14274            Update::ForEach { over, updates, .. } => {
14275                collect_expr_fields(over, &mut fields);
14276                fields.extend(collect_update_fields_exprs(updates));
14277            }
14278            Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
14279        }
14280    }
14281    fields
14282}
14283
14284fn collect_expr_bindings(expr: &Expr, bindings: &mut BTreeSet<String>) {
14285    match expr {
14286        Expr::Binding(name) => {
14287            bindings.insert(name.clone());
14288        }
14289        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
14290            for item in items {
14291                collect_expr_bindings(item, bindings);
14292            }
14293        }
14294        Expr::IfElse {
14295            condition,
14296            then_expr,
14297            else_expr,
14298        } => {
14299            collect_expr_bindings(condition, bindings);
14300            collect_expr_bindings(then_expr, bindings);
14301            collect_expr_bindings(else_expr, bindings);
14302        }
14303        Expr::Not(inner)
14304        | Expr::SeqElements(inner)
14305        | Expr::Len(inner)
14306        | Expr::Head(inner)
14307        | Expr::MapKeys(inner)
14308        | Expr::Some(inner)
14309        | Expr::FieldAccess { base: inner, .. }
14310        | Expr::EnumVariantIs { value: inner, .. }
14311        | Expr::EnumStringSetPayload { value: inner, .. } => collect_expr_bindings(inner, bindings),
14312        Expr::Eq(left, right)
14313        | Expr::Neq(left, right)
14314        | Expr::Add(left, right)
14315        | Expr::Sub(left, right)
14316        | Expr::Gt(left, right)
14317        | Expr::Gte(left, right)
14318        | Expr::Lt(left, right)
14319        | Expr::Lte(left, right) => {
14320            collect_expr_bindings(left, bindings);
14321            collect_expr_bindings(right, bindings);
14322        }
14323        Expr::Contains { collection, value } => {
14324            collect_expr_bindings(collection, bindings);
14325            collect_expr_bindings(value, bindings);
14326        }
14327        Expr::Count { collection, value } => {
14328            collect_expr_bindings(collection, bindings);
14329            collect_expr_bindings(value, bindings);
14330        }
14331        Expr::MapContainsKey { map, key } => {
14332            collect_expr_bindings(map, bindings);
14333            collect_expr_bindings(key, bindings);
14334        }
14335        Expr::SeqStartsWith { seq, prefix } => {
14336            collect_expr_bindings(seq, bindings);
14337            collect_expr_bindings(prefix, bindings);
14338        }
14339        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
14340            collect_expr_bindings(map, bindings);
14341            collect_expr_bindings(key, bindings);
14342        }
14343        Expr::MapLiteral(entries) => {
14344            for (key, value) in entries {
14345                collect_expr_bindings(key, bindings);
14346                collect_expr_bindings(value, bindings);
14347            }
14348        }
14349        Expr::Call { args, .. } => {
14350            for arg in args {
14351                collect_expr_bindings(arg, bindings);
14352            }
14353        }
14354        Expr::Quantified {
14355            binding,
14356            over,
14357            body,
14358            ..
14359        } => {
14360            bindings.insert(binding.clone());
14361            collect_expr_bindings(over, bindings);
14362            collect_expr_bindings(body, bindings);
14363        }
14364        Expr::Bool(_)
14365        | Expr::U64(_)
14366        | Expr::U64Max
14367        | Expr::String(_)
14368        | Expr::NamedVariant { .. }
14369        | Expr::EmptySet
14370        | Expr::EmptyMap
14371        | Expr::CurrentPhase
14372        | Expr::Phase(_)
14373        | Expr::Field(_)
14374        | Expr::Variant(_)
14375        | Expr::None => {}
14376    }
14377}
14378
14379fn collect_expr_fields(expr: &Expr, fields: &mut BTreeSet<String>) {
14380    match expr {
14381        Expr::Field(name) => {
14382            fields.insert(name.as_str().to_owned());
14383        }
14384        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
14385            for item in items {
14386                collect_expr_fields(item, fields);
14387            }
14388        }
14389        Expr::IfElse {
14390            condition,
14391            then_expr,
14392            else_expr,
14393        } => {
14394            collect_expr_fields(condition, fields);
14395            collect_expr_fields(then_expr, fields);
14396            collect_expr_fields(else_expr, fields);
14397        }
14398        Expr::Not(inner)
14399        | Expr::SeqElements(inner)
14400        | Expr::Len(inner)
14401        | Expr::Head(inner)
14402        | Expr::MapKeys(inner)
14403        | Expr::Some(inner)
14404        | Expr::FieldAccess { base: inner, .. }
14405        | Expr::EnumVariantIs { value: inner, .. }
14406        | Expr::EnumStringSetPayload { value: inner, .. } => collect_expr_fields(inner, fields),
14407        Expr::Eq(left, right)
14408        | Expr::Neq(left, right)
14409        | Expr::Add(left, right)
14410        | Expr::Sub(left, right)
14411        | Expr::Gt(left, right)
14412        | Expr::Gte(left, right)
14413        | Expr::Lt(left, right)
14414        | Expr::Lte(left, right) => {
14415            collect_expr_fields(left, fields);
14416            collect_expr_fields(right, fields);
14417        }
14418        Expr::Contains { collection, value } => {
14419            collect_expr_fields(collection, fields);
14420            collect_expr_fields(value, fields);
14421        }
14422        Expr::Count { collection, value } => {
14423            collect_expr_fields(collection, fields);
14424            collect_expr_fields(value, fields);
14425        }
14426        Expr::MapContainsKey { map, key } => {
14427            collect_expr_fields(map, fields);
14428            collect_expr_fields(key, fields);
14429        }
14430        Expr::SeqStartsWith { seq, prefix } => {
14431            collect_expr_fields(seq, fields);
14432            collect_expr_fields(prefix, fields);
14433        }
14434        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
14435            collect_expr_fields(map, fields);
14436            collect_expr_fields(key, fields);
14437        }
14438        Expr::MapLiteral(entries) => {
14439            for (key, value) in entries {
14440                collect_expr_fields(key, fields);
14441                collect_expr_fields(value, fields);
14442            }
14443        }
14444        Expr::Call { args, .. } => {
14445            for arg in args {
14446                collect_expr_fields(arg, fields);
14447            }
14448        }
14449        Expr::Quantified { over, body, .. } => {
14450            collect_expr_fields(over, fields);
14451            collect_expr_fields(body, fields);
14452        }
14453        Expr::Bool(_)
14454        | Expr::U64(_)
14455        | Expr::U64Max
14456        | Expr::String(_)
14457        | Expr::NamedVariant { .. }
14458        | Expr::EmptySet
14459        | Expr::EmptyMap
14460        | Expr::CurrentPhase
14461        | Expr::Phase(_)
14462        | Expr::Binding(_)
14463        | Expr::Variant(_)
14464        | Expr::None => {}
14465    }
14466}
14467
14468fn union_touched_fields(
14469    base: &BTreeMap<String, String>,
14470    then_env: &BTreeMap<String, String>,
14471    else_env: &BTreeMap<String, String>,
14472) -> BTreeSet<String> {
14473    base.keys()
14474        .filter(|field| {
14475            then_env.get(*field) != base.get(*field) || else_env.get(*field) != base.get(*field)
14476        })
14477        .cloned()
14478        .collect()
14479}
14480
14481fn join_exprs(items: &[String], separator: &str) -> String {
14482    if items.is_empty() {
14483        return "TRUE".into();
14484    }
14485    if items.len() == 1 {
14486        items[0].clone()
14487    } else {
14488        format!("({})", items.join(separator))
14489    }
14490}
14491
14492/// Render a boolean disjunction as a short-circuiting `IF a THEN TRUE ELSE …`
14493/// chain instead of `a \/ b`.
14494///
14495/// TLC expands an action-level `\/` into a tableau and evaluates *every*
14496/// disjunct independently to enumerate successor states. That breaks the
14497/// idiomatic optional guard `opt = None \/ opt.value > now`: the second
14498/// disjunct's `opt.value > now` is evaluated even when `opt = None`
14499/// (`None` still has a `"value"` field equal to the string `"none"`), so TLC
14500/// raises `first argument of > should be an integer, but instead it is "none"`.
14501/// `IF a THEN TRUE ELSE b` is boolean-equivalent to `a \/ b` but is evaluated
14502/// as a single function: the `ELSE` branch is only evaluated when `a` is false,
14503/// matching the short-circuit that `/\` already gives conjunctive guards. State
14504/// space and enabledness are unchanged. Empty/single disjunctions preserve the
14505/// prior `join_exprs` behavior.
14506fn render_or_short_circuit(items: &[String]) -> String {
14507    match items {
14508        [] => "TRUE".into(),
14509        [single] => single.clone(),
14510        [first, rest @ ..] => {
14511            format!(
14512                "(IF {first} THEN TRUE ELSE {})",
14513                render_or_short_circuit(rest)
14514            )
14515        }
14516    }
14517}
14518
14519fn default_state_init_expr(ty: &TypeRef) -> String {
14520    match ty {
14521        TypeRef::Bool => "FALSE".into(),
14522        TypeRef::U32 | TypeRef::U64 => "0".into(),
14523        TypeRef::String => tla_string(""),
14524        TypeRef::Named(name) => tla_string(format!("{}_default", tla_ident(name).to_lowercase())),
14525        TypeRef::Enum(name) => tla_string(format!("{}_default", tla_ident(name).to_lowercase())),
14526        TypeRef::Option(_) => "None".into(),
14527        TypeRef::Set(_) => "{}".into(),
14528        TypeRef::Seq(_) => "<<>>".into(),
14529        TypeRef::Map(_, _) => "[x \\in {} |-> None]".into(),
14530    }
14531}
14532
14533fn default_absent_map_value_expr(ty: &TypeRef) -> String {
14534    match ty {
14535        TypeRef::Bool => "FALSE".into(),
14536        TypeRef::U32 | TypeRef::U64 => "0".into(),
14537        TypeRef::String | TypeRef::Named(_) | TypeRef::Enum(_) => tla_string("None"),
14538        TypeRef::Option(_) => "None".into(),
14539        TypeRef::Set(_) => "{}".into(),
14540        TypeRef::Seq(_) => "<<>>".into(),
14541        TypeRef::Map(_, _) => "[x \\in {} |-> None]".into(),
14542    }
14543}
14544
14545fn render_type_ref(ty: &TypeRef) -> String {
14546    match ty {
14547        TypeRef::Bool => "Bool".into(),
14548        TypeRef::U32 => "u32".into(),
14549        TypeRef::U64 => "u64".into(),
14550        TypeRef::String => "String".into(),
14551        TypeRef::Named(name) => name.as_str().to_owned(),
14552        TypeRef::Enum(name) => name.as_str().to_owned(),
14553        TypeRef::Option(inner) => format!("Option<{}>", render_type_ref(inner)),
14554        TypeRef::Set(inner) => format!("Set<{}>", render_type_ref(inner)),
14555        TypeRef::Seq(inner) => format!("Seq<{}>", render_type_ref(inner)),
14556        TypeRef::Map(key, value) => {
14557            format!("Map<{}, {}>", render_type_ref(key), render_type_ref(value))
14558        }
14559    }
14560}
14561
14562fn render_route_delivery(route: &meerkat_machine_schema::Route) -> &'static str {
14563    match route.delivery {
14564        RouteDelivery::Immediate => "Immediate",
14565        RouteDelivery::Enqueue => "Enqueue",
14566    }
14567}
14568
14569fn render_scheduler_rule(rule: &SchedulerRule) -> String {
14570    match rule {
14571        SchedulerRule::PreemptWhenReady { higher, lower } => {
14572            format!("PreemptWhenReady({higher}, {lower})")
14573        }
14574    }
14575}
14576
14577fn render_scheduler_rule_tuple(rule: &SchedulerRule) -> String {
14578    match rule {
14579        SchedulerRule::PreemptWhenReady { higher, lower } => {
14580            format!(
14581                "<<{}, {}, {}>>",
14582                tla_string("PreemptWhenReady"),
14583                tla_string(higher),
14584                tla_string(lower)
14585            )
14586        }
14587    }
14588}
14589
14590fn render_scheduler_trigger_formula(rule: &SchedulerRule) -> String {
14591    match rule {
14592        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
14593            "/\\ {} \\in PendingActors /\\ {} \\in PendingActors",
14594            tla_string(higher),
14595            tla_string(lower)
14596        ),
14597    }
14598}
14599
14600fn render_composition_invariant_formula(
14601    schema: &CompositionSchema,
14602    kind: &CompositionInvariantKind,
14603) -> String {
14604    match kind {
14605        CompositionInvariantKind::RoutePresent {
14606            from_machine,
14607            effect_variant,
14608            to_machine,
14609            input_variant,
14610        } => format!(
14611            "\\E route_name \\in RouteNames : /\\ RouteSource(route_name) = {} /\\ RouteEffect(route_name) = {} /\\ RouteTargetMachine(route_name) = {} /\\ RouteTargetInput(route_name) = {}",
14612            tla_string(from_machine),
14613            tla_string(effect_variant),
14614            tla_string(to_machine),
14615            tla_string(input_variant)
14616        ),
14617        CompositionInvariantKind::ObservedInputOriginatesFromEffect {
14618            to_machine,
14619            input_variant,
14620            from_machine,
14621            effect_variant,
14622        } => format!(
14623            "\\A input_packet \\in observed_inputs : ((input_packet.machine = {} /\\ input_packet.variant = {}) => (/\\ input_packet.source_kind = \"route\" /\\ input_packet.source_machine = {} /\\ input_packet.source_effect = {} /\\ \\E effect_packet \\in emitted_effects : /\\ effect_packet.machine = {} /\\ effect_packet.variant = {} /\\ effect_packet.effect_id = input_packet.effect_id /\\ \\E route_packet \\in RoutePackets : /\\ route_packet.route = input_packet.source_route /\\ route_packet.source_machine = {} /\\ route_packet.effect = {} /\\ route_packet.target_machine = {} /\\ route_packet.target_input = {} /\\ route_packet.effect_id = input_packet.effect_id /\\ route_packet.payload = input_packet.payload))",
14624            tla_string(to_machine),
14625            tla_string(input_variant),
14626            tla_string(from_machine),
14627            tla_string(effect_variant),
14628            tla_string(from_machine),
14629            tla_string(effect_variant),
14630            tla_string(from_machine),
14631            tla_string(effect_variant),
14632            tla_string(to_machine),
14633            tla_string(input_variant)
14634        ),
14635        CompositionInvariantKind::ObservedRouteInputOriginatesFromEffect {
14636            route_name,
14637            to_machine,
14638            input_variant,
14639            from_machine,
14640            effect_variant,
14641        } => format!(
14642            "\\A input_packet \\in observed_inputs : ((input_packet.machine = {} /\\ input_packet.variant = {} /\\ input_packet.source_route = {}) => (/\\ input_packet.source_kind = \"route\" /\\ input_packet.source_machine = {} /\\ input_packet.source_effect = {} /\\ \\E effect_packet \\in emitted_effects : /\\ effect_packet.machine = {} /\\ effect_packet.variant = {} /\\ effect_packet.effect_id = input_packet.effect_id /\\ \\E route_packet \\in RoutePackets : /\\ route_packet.route = {} /\\ route_packet.source_machine = {} /\\ route_packet.effect = {} /\\ route_packet.target_machine = {} /\\ route_packet.target_input = {} /\\ route_packet.effect_id = input_packet.effect_id /\\ route_packet.payload = input_packet.payload))",
14643            tla_string(to_machine),
14644            tla_string(input_variant),
14645            tla_string(route_name),
14646            tla_string(from_machine),
14647            tla_string(effect_variant),
14648            tla_string(from_machine),
14649            tla_string(effect_variant),
14650            tla_string(route_name),
14651            tla_string(from_machine),
14652            tla_string(effect_variant),
14653            tla_string(to_machine),
14654            tla_string(input_variant)
14655        ),
14656        CompositionInvariantKind::ActorPriorityPresent { higher, lower } => format!(
14657            "<<{}, {}>> \\in ActorPriorities",
14658            tla_string(higher),
14659            tla_string(lower)
14660        ),
14661        CompositionInvariantKind::SchedulerRulePresent { rule } => {
14662            format!("{} \\in SchedulerRules", render_scheduler_rule_tuple(rule))
14663        }
14664        CompositionInvariantKind::OutcomeHandled {
14665            from_machine,
14666            effect_variant,
14667            required_targets,
14668        } => {
14669            let required = required_targets
14670                .iter()
14671                .enumerate()
14672                .map(|(idx, target)| {
14673                    let binding = format!("route_packet_{idx}");
14674                    let input_binding = format!("input_packet_{idx}");
14675                    format!(
14676                        "\\E {binding} \\in RoutePackets : /\\ {binding}.source_machine = {} /\\ {binding}.effect = {} /\\ {binding}.target_machine = {} /\\ {binding}.target_input = {} /\\ {binding}.effect_id = effect_packet.effect_id /\\ IF RouteDeliveryKind({binding}.route) = \"Immediate\" THEN \\E {input_binding} \\in observed_inputs : /\\ {input_binding}.machine = {} /\\ {input_binding}.variant = {} /\\ {input_binding}.source_kind = \"route\" /\\ {input_binding}.source_route = {binding}.route /\\ {input_binding}.source_machine = {} /\\ {input_binding}.source_effect = {} /\\ {input_binding}.effect_id = effect_packet.effect_id /\\ {input_binding}.payload = {binding}.payload ELSE TRUE",
14677                        tla_string(from_machine),
14678                        tla_string(effect_variant),
14679                        tla_string(&target.machine),
14680                        tla_string(&target.input_variant)
14681                        ,
14682                        tla_string(&target.machine),
14683                        tla_string(&target.input_variant),
14684                        tla_string(from_machine),
14685                        tla_string(effect_variant)
14686                    )
14687                })
14688                .collect::<Vec<_>>()
14689                .join(" /\\ ");
14690            let fallback = schema
14691                .routes
14692                .iter()
14693                .filter(|route| {
14694                    route.from_machine == *from_machine && route.effect_variant == *effect_variant
14695                })
14696                .count();
14697            if fallback == 0 {
14698                "FALSE".into()
14699            } else {
14700                format!(
14701                    "\\A effect_packet \\in emitted_effects : ((effect_packet.machine = {} /\\ effect_packet.variant = {}) => ({}))",
14702                    tla_string(from_machine),
14703                    tla_string(effect_variant),
14704                    required
14705                )
14706            }
14707        }
14708        CompositionInvariantKind::HandoffProtocolCovered { .. } => {
14709            // Structural invariant — validated at schema level, always TRUE in TLA+.
14710            "TRUE".into()
14711        }
14712    }
14713}
14714
14715fn render_composition_state_constraint(
14716    schema: &CompositionSchema,
14717    limits: &CompositionStateLimits,
14718    compiler: &CompositionTlaCompiler<'_>,
14719) -> String {
14720    let limits = effective_composition_state_limits(limits, None);
14721    let mut clauses = vec![
14722        format!("model_step_count <= {}", limits.step_limit),
14723        format!("Len(pending_inputs) <= {}", limits.pending_input_limit),
14724        format!(
14725            "Cardinality(observed_inputs) <= {}",
14726            limits.pending_input_limit + limits.delivered_route_limit + 2
14727        ),
14728        format!("Len(pending_routes) <= {}", limits.pending_route_limit),
14729        format!(
14730            "Cardinality(delivered_routes) <= {}",
14731            limits.delivered_route_limit
14732        ),
14733        format!(
14734            "Cardinality(emitted_effects) <= {}",
14735            limits.emitted_effect_limit
14736        ),
14737        format!("Cardinality(observed_transitions) <= {}", limits.step_limit),
14738    ];
14739
14740    for instance in &schema.machines {
14741        let machine = compiler.machine(instance.instance_id.as_str());
14742        for field in &machine.state.fields {
14743            let field_var = compiler.field_var(instance.instance_id.as_str(), field.name.as_str());
14744            match &field.ty {
14745                TypeRef::Seq(_) => {
14746                    clauses.push(format!("Len({field_var}) <= {}", limits.seq_limit))
14747                }
14748                TypeRef::Set(_) => {
14749                    clauses.push(format!("Cardinality({field_var}) <= {}", limits.set_limit))
14750                }
14751                TypeRef::Map(_, _) => clauses.push(format!(
14752                    "Cardinality(DOMAIN {field_var}) <= {}",
14753                    limits.map_limit
14754                )),
14755                _ => {}
14756            }
14757        }
14758    }
14759
14760    format!("/\\ {}", clauses.join(" /\\ "))
14761}
14762
14763fn effective_composition_state_limits(
14764    limits: &CompositionStateLimits,
14765    witness: Option<&CompositionWitness>,
14766) -> CompositionStateLimits {
14767    let mut effective = limits.clone();
14768    if let Some(witness) = witness {
14769        let minimum_step_limit =
14770            (witness.preload_inputs.len() + witness.expected_transitions.len()) as u32;
14771        effective.step_limit = effective.step_limit.max(minimum_step_limit);
14772        effective.delivered_route_limit = effective
14773            .delivered_route_limit
14774            .max(witness.expected_routes.len() as u32);
14775        effective.emitted_effect_limit = effective
14776            .emitted_effect_limit
14777            .max(witness.expected_transitions.len() as u32);
14778        effective.pending_input_limit = effective.pending_input_limit.max(1);
14779    }
14780    effective
14781}
14782
14783fn composition_deep_state_limits(schema: &CompositionSchema) -> CompositionStateLimits {
14784    let mut deep = CompositionStateLimits::deep_defaults();
14785    if let Some(ci) = &schema.ci_limits {
14786        deep.step_limit = deep.step_limit.max(ci.step_limit);
14787        deep.pending_input_limit = deep.pending_input_limit.max(ci.pending_input_limit);
14788        deep.pending_route_limit = deep.pending_route_limit.max(ci.pending_route_limit);
14789        deep.delivered_route_limit = deep.delivered_route_limit.max(ci.delivered_route_limit);
14790        deep.emitted_effect_limit = deep.emitted_effect_limit.max(ci.emitted_effect_limit);
14791        deep.seq_limit = deep.seq_limit.max(ci.seq_limit);
14792        deep.set_limit = deep.set_limit.max(ci.set_limit);
14793        deep.map_limit = deep.map_limit.max(ci.map_limit);
14794    }
14795    deep
14796}
14797
14798fn render_machine_state_constraint(schema: &MachineSchema, deep: bool) -> String {
14799    let step_limit = if deep {
14800        8
14801    } else {
14802        schema.ci_step_limit.unwrap_or(6) as usize
14803    };
14804    let seq_limit = if deep { 2 } else { 1 };
14805    let set_limit = if deep { 2 } else { 1 };
14806    let map_limit = if deep { 2 } else { 1 };
14807    let (step_limit, seq_limit, set_limit, map_limit) =
14808        if !deep && let Some(model) = &schema.tlc_model {
14809            let limits = &model.ci_limits;
14810            (
14811                limits.step_limit as usize,
14812                limits.seq_limit as usize,
14813                limits.set_limit as usize,
14814                limits.map_limit as usize,
14815            )
14816        } else {
14817            (step_limit, seq_limit, set_limit, map_limit)
14818        };
14819    let mut clauses = vec![format!("model_step_count <= {step_limit}")];
14820
14821    for field in &schema.state.fields {
14822        match &field.ty {
14823            TypeRef::Seq(_) => {
14824                clauses.push(format!("Len({}) <= {seq_limit}", tla_ident(&field.name)))
14825            }
14826            TypeRef::Set(_) => clauses.push(format!(
14827                "Cardinality({}) <= {set_limit}",
14828                tla_ident(&field.name)
14829            )),
14830            TypeRef::Map(_, _) => clauses.push(format!(
14831                "Cardinality(DOMAIN {}) <= {map_limit}",
14832                tla_ident(&field.name)
14833            )),
14834            _ => {}
14835        }
14836    }
14837
14838    if clauses.is_empty() {
14839        "TRUE".into()
14840    } else {
14841        format!("/\\ {}", clauses.join(" /\\ "))
14842    }
14843}
14844
14845/// Default arm for a generated composition `CASE` operator.
14846///
14847/// Route-component lookups (`RouteSource`, `RouteEffect`, …) are validated
14848/// up-front by [`CompositionTlaCompiler::validate_routes`], so the historical
14849/// `OTHER -> "unknown_*"` arm is provably unreachable for any real route name.
14850/// Emitting that sentinel was a silent catch-all that could launder an
14851/// undeclared route component into a passing model. Such lookups now use
14852/// [`CaseDefault::FailClosed`]: the `OTHER` arm is dropped entirely so an
14853/// unmatched route name surfaces as a TLC error instead of a fabricated value,
14854/// and the renderer fails closed at codegen time if a route component cannot
14855/// be resolved.
14856///
14857/// Genuinely closed enumerations (`RouteTargetKind`, `RouteDeliveryKind`) keep
14858/// a total literal fallback via [`CaseDefault::ClosedEnum`]; every input maps
14859/// to a finite, exhaustive enum, so the literal is a sound total default rather
14860/// than a sentinel standing in for an undeclared component.
14861enum CaseDefault {
14862    /// Total literal fallback over a closed enumeration domain.
14863    ClosedEnum(String),
14864    /// Fail-closed route-component lookup: no `OTHER` sentinel is emitted.
14865    ///
14866    /// `require_mapping` is `true` for operators whose domain must be
14867    /// non-empty for a well-formed composition (e.g. `ActorOfMachine`, which
14868    /// maps over declared machine instances): an empty mapping is then a hard
14869    /// codegen error. It is `false` for operators keyed on routes, since a
14870    /// protocol-only composition legitimately declares zero routes — the
14871    /// operator is structurally defined but never evaluated.
14872    FailClosed {
14873        component: &'static str,
14874        require_mapping: bool,
14875    },
14876}
14877
14878fn render_composition_case_fn(
14879    out: &mut String,
14880    composition: &str,
14881    fn_name: &str,
14882    param: &str,
14883    mappings: Vec<(&str, String)>,
14884    default: CaseDefault,
14885) -> std::result::Result<(), CompositionTlaError> {
14886    writeln!(out, "{fn_name}({param}) ==");
14887    if mappings.is_empty() {
14888        // No keys to map. For a closed-enum operator the literal fallback is
14889        // the operator body. For a fail-closed route-component operator the
14890        // composition declares no routes, so the operator is structurally
14891        // defined but unreachable; emitting the bare error label as a string
14892        // makes any accidental evaluation explode in TLC rather than yield a
14893        // plausible-looking value.
14894        let body = match &default {
14895            CaseDefault::ClosedEnum(expr) => expr.clone(),
14896            CaseDefault::FailClosed {
14897                component,
14898                require_mapping,
14899            } => {
14900                if *require_mapping {
14901                    return Err(CompositionTlaError::UnknownRouteComponent {
14902                        composition: composition.to_owned(),
14903                        component,
14904                    });
14905                }
14906                tla_string(format!("unresolved_{component}"))
14907            }
14908        };
14909        pushln!(out, "    {}", body);
14910        pushln!(out);
14911        return Ok(());
14912    }
14913
14914    let mut first = true;
14915    for (key, value) in mappings {
14916        if first {
14917            pushln!(out, "    CASE {} = {} -> {}", param, tla_string(key), value);
14918            first = false;
14919        } else {
14920            writeln!(out, "      [] {} = {} -> {}", param, tla_string(key), value);
14921        }
14922    }
14923    match default {
14924        CaseDefault::ClosedEnum(expr) => {
14925            writeln!(out, "      [] OTHER -> {}", expr);
14926        }
14927        CaseDefault::FailClosed { .. } => {
14928            // validate_routes() guarantees the CASE arms cover every declared
14929            // route, so an OTHER arm here would be a silent catch-all over an
14930            // undeclared route component. Drop it: an unmatched route name now
14931            // becomes a TLC evaluation error (fail closed) instead of a
14932            // fabricated sentinel.
14933        }
14934    }
14935    pushln!(out);
14936    Ok(())
14937}
14938
14939fn tla_ident(value: impl AsRef<str>) -> String {
14940    value
14941        .as_ref()
14942        .chars()
14943        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
14944        .collect()
14945}
14946
14947fn tla_string(value: impl AsRef<str>) -> String {
14948    format!("\"{}\"", value.as_ref().replace('"', "\\\""))
14949}
14950
14951/// Wrap a rendered TLA+ expression in parentheses unless it is already an
14952/// atom (an identifier, field path, number or string, optionally applied with balanced
14953/// `(...)`/`[...]` suffixes, or one parenthesized group), so it can be spliced
14954/// as an operand without TLA+ operator precedence reaching into it.
14955fn tla_delimited(expr: &str) -> String {
14956    if tla_is_atom(expr) {
14957        expr.to_owned()
14958    } else {
14959        format!("({expr})")
14960    }
14961}
14962
14963fn tla_is_atom(expr: &str) -> bool {
14964    let bytes = expr.as_bytes();
14965    let mut index = 0;
14966    match bytes.first() {
14967        Some(b'(') => {}
14968        Some(b'"') => {
14969            index = 1;
14970            while index < bytes.len() && bytes[index] != b'"' {
14971                index += 1;
14972            }
14973            if index >= bytes.len() {
14974                return false;
14975            }
14976            index += 1;
14977        }
14978        Some(byte) if byte.is_ascii_alphanumeric() || *byte == b'_' => {
14979            // Identifiers and record field paths (`packet.payload.run_id`):
14980            // field access binds tighter than every operator.
14981            while index < bytes.len()
14982                && (bytes[index].is_ascii_alphanumeric()
14983                    || bytes[index] == b'_'
14984                    || bytes[index] == b'.')
14985            {
14986                index += 1;
14987            }
14988        }
14989        _ => return false,
14990    }
14991    // Zero or more balanced `(...)` / `[...]` groups, with nothing between.
14992    while index < bytes.len() {
14993        let (open, close) = match bytes[index] {
14994            b'(' => (b'(', b')'),
14995            b'[' => (b'[', b']'),
14996            _ => return false,
14997        };
14998        let mut depth = 0usize;
14999        let mut in_string = false;
15000        let mut end = None;
15001        for (offset, byte) in bytes[index..].iter().enumerate() {
15002            match *byte {
15003                b'"' => in_string = !in_string,
15004                b if b == open && !in_string => depth += 1,
15005                b if b == close && !in_string => {
15006                    depth -= 1;
15007                    if depth == 0 {
15008                        end = Some(index + offset);
15009                        break;
15010                    }
15011                }
15012                _ => {}
15013            }
15014        }
15015        match end {
15016            Some(end) => index = end + 1,
15017            None => return false,
15018        }
15019    }
15020    true
15021}
15022
15023/// The input variant a transition is triggered by, if it is input-triggered.
15024fn trigger_input_variant(transition: &TransitionSchema) -> Option<&str> {
15025    match &transition.on {
15026        TriggerMatch::Input { variant, .. } => Some(variant.as_str()),
15027        _ => None,
15028    }
15029}
15030
15031/// The default unsigned domain extended with declared additional values.
15032fn additional_values_domain(default: &str, values: &BTreeSet<u64>) -> String {
15033    let values = values
15034        .iter()
15035        .map(u64::to_string)
15036        .collect::<Vec<_>>()
15037        .join(", ");
15038    format!("({default} \\cup {{{values}}})")
15039}
15040
15041/// The model constant that a `CiValues` or `CiSamples` input field ranges
15042/// over in the generated model; each profile's config assigns it.
15043fn input_samples_constant_name(input: &str, field: &str) -> String {
15044    format!("InputSamples_{}_{}", tla_ident(input), tla_ident(field))
15045}
15046
15047/// The samples a `CiValues` input field keeps outside the CI profile (the
15048/// Deep profile and every composition): the declared values together with the
15049/// default unsigned domain (`0..2`).
15050fn broad_input_samples(ci_values: &BTreeSet<u64>) -> BTreeSet<u64> {
15051    (0..=2).chain(ci_values.iter().copied()).collect()
15052}
15053
15054fn render_u64_set(values: &BTreeSet<u64>) -> String {
15055    let values = values
15056        .iter()
15057        .map(u64::to_string)
15058        .collect::<Vec<_>>()
15059        .join(", ");
15060    format!("{{{values}}}")
15061}
15062
15063/// Every `CiValues` input field of a machine, in declaration order: the model
15064/// constant the field ranges over and the values the CI profile assigns it.
15065fn machine_input_sample_constants(schema: &MachineSchema) -> Vec<(String, &BTreeSet<u64>)> {
15066    schema
15067        .input_field_domains
15068        .iter()
15069        .filter_map(|declaration| match &declaration.domain {
15070            meerkat_machine_schema::InputFieldDomainKind::CiValues(values) => Some((
15071                input_samples_constant_name(declaration.input.as_str(), declaration.field.as_str()),
15072                values,
15073            )),
15074            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
15075            | meerkat_machine_schema::InputFieldDomainKind::StateField(_)
15076            | meerkat_machine_schema::InputFieldDomainKind::CiSamples(_) => None,
15077        })
15078        .collect()
15079}
15080
15081/// Every `CiSamples` input field of a machine, in declaration order: the
15082/// model constant the field ranges over, the values the CI profile assigns
15083/// it, and the field's type, whose whole domain the Deep profile assigns it.
15084/// The schema's validation resolves every declared field.
15085fn machine_input_typed_sample_constants(
15086    schema: &MachineSchema,
15087) -> Vec<(String, &[meerkat_machine_schema::TlcValue], TypeRef)> {
15088    schema
15089        .input_field_domains
15090        .iter()
15091        .filter_map(|declaration| match &declaration.domain {
15092            meerkat_machine_schema::InputFieldDomainKind::CiSamples(samples) => {
15093                let field = schema
15094                    .inputs
15095                    .variant_named(declaration.input.as_str())
15096                    .ok()?
15097                    .fields
15098                    .iter()
15099                    .find(|field| field.name == declaration.field)?;
15100                Some((
15101                    input_samples_constant_name(
15102                        declaration.input.as_str(),
15103                        declaration.field.as_str(),
15104                    ),
15105                    samples.as_slice(),
15106                    field.ty.clone(),
15107                ))
15108            }
15109            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
15110            | meerkat_machine_schema::InputFieldDomainKind::StateField(_)
15111            | meerkat_machine_schema::InputFieldDomainKind::CiValues(_) => None,
15112        })
15113        .collect()
15114}