Skip to main content

meerkat_machine_codegen/
render.rs

1use std::fmt::Write;
2
3fn push_fmt(out: &mut String, args: std::fmt::Arguments<'_>) {
4    let _ignored = out.write_fmt(args);
5}
6
7fn push_line(out: &mut String, args: std::fmt::Arguments<'_>) {
8    push_fmt(out, args);
9    out.push('\n');
10}
11
12macro_rules! pushln {
13    ($out:expr) => {{
14        $out.push('\n');
15    }};
16    ($out:expr, $($arg:tt)*) => {{
17        push_line($out, format_args!($($arg)*));
18    }};
19}
20
21#[cfg(not(test))]
22use meerkat_machine_schema::{
23    CompositionCoverageManifest, CompositionInvariantKind, CompositionSchema, CoverageAnchor,
24    CoverageSchemaTarget, MachineCoverageManifest, RouteDelivery, RouteTargetKind, SchedulerRule,
25    SemanticCoverageEntry,
26};
27use meerkat_machine_schema::{
28    EffectEmit, EnumSchema, Expr, FieldInit, FieldSchema, Guard, HelperSchema, MachineSchema,
29    Quantifier, TransitionSchema, TypeRef, Update, VariantSchema,
30};
31
32#[cfg(not(test))]
33pub const GENERATED_COVERAGE_START: &str = "<!-- GENERATED_COVERAGE_START -->";
34#[cfg(not(test))]
35pub const GENERATED_COVERAGE_END: &str = "<!-- GENERATED_COVERAGE_END -->";
36
37pub fn render_machine_module(schema: &MachineSchema) -> String {
38    let mut out = String::new();
39    let module_name = format!("Machine_{}", tla_ident(&schema.machine));
40
41    pushln!(&mut out, "---- MODULE {module_name} ----");
42    pushln!(
43        &mut out,
44        "(* machine = {} ; version = {} *)",
45        schema.machine,
46        schema.version
47    );
48    pushln!(
49        &mut out,
50        "(* rust = {}::{} *)",
51        schema.rust.crate_name,
52        schema.rust.module
53    );
54    out.push('\n');
55
56    pushln!(&mut out, "STATE");
57    pushln!(
58        &mut out,
59        "  phase : {}",
60        render_enum_variants_inline(&schema.state.phase)
61    );
62    for field in &schema.state.fields {
63        pushln!(
64            &mut out,
65            "  {} : {}",
66            field.name,
67            render_type_ref(&field.ty)
68        );
69    }
70    out.push('\n');
71
72    pushln!(&mut out, "INIT");
73    pushln!(
74        &mut out,
75        "  phase = {}",
76        tla_string(&schema.state.init.phase)
77    );
78    for field in &schema.state.init.fields {
79        render_field_init(&mut out, field);
80    }
81    if !schema.state.terminal_phases.is_empty() {
82        pushln!(
83            &mut out,
84            "  terminal_phases = {}",
85            render_string_list(&schema.state.terminal_phases)
86        );
87    }
88    out.push('\n');
89
90    render_enum_section(&mut out, "INPUTS", &schema.inputs);
91    render_enum_section(&mut out, "SIGNALS", &schema.signals);
92    render_enum_section(&mut out, "EFFECTS", &schema.effects);
93
94    render_helpers_section(&mut out, "HELPERS", &schema.helpers);
95    render_helpers_section(&mut out, "DERIVED", &schema.derived);
96    render_invariants_section(&mut out, schema);
97    render_transitions_section(&mut out, schema);
98
99    pushln!(&mut out, "====");
100    out
101}
102
103#[cfg(not(test))]
104pub fn render_composition_module(schema: &CompositionSchema) -> String {
105    let mut out = String::new();
106    let module_name = format!("Composition_{}", tla_ident(&schema.name));
107
108    pushln!(&mut out, "---- MODULE {module_name} ----");
109    pushln!(&mut out, "(* composition = {} *)", schema.name);
110    out.push('\n');
111
112    pushln!(&mut out, "MACHINES");
113    for machine in &schema.machines {
114        pushln!(
115            &mut out,
116            "  {} : {} @ actor {}",
117            machine.instance_id,
118            machine.machine_name,
119            machine.actor
120        );
121    }
122    out.push('\n');
123
124    pushln!(&mut out, "ROUTES");
125    for route in &schema.routes {
126        pushln!(
127            &mut out,
128            "  {} == {}.{} -> {}.{} ({}) [{}]",
129            route.name,
130            route.from_machine,
131            route.effect_variant,
132            route.to.machine,
133            route.to.input_variant,
134            match route.to.kind {
135                RouteTargetKind::Input => "Input",
136                RouteTargetKind::Signal => "Signal",
137            },
138            render_route_delivery(&route.delivery)
139        );
140        if !route.bindings.is_empty() {
141            pushln!(&mut out, "    bindings = {}", render_route_bindings(route));
142        }
143    }
144    out.push('\n');
145
146    pushln!(&mut out, "TARGET_SELECTORS");
147    for selector in &schema.route_target_selectors {
148        pushln!(
149            &mut out,
150            "  {} selects {} from {:?}",
151            selector.route_name,
152            selector.selector_field,
153            selector.source
154        );
155    }
156    out.push('\n');
157
158    pushln!(&mut out, "DRIVER");
159    match &schema.driver {
160        Some(driver) => {
161            pushln!(
162                &mut out,
163                "  {} ({} @ {})",
164                driver.name,
165                driver.rust.driver_type,
166                driver.rust.module_path
167            );
168            for watched in &driver.watched_effects {
169                pushln!(
170                    &mut out,
171                    "    watches {}::{}",
172                    watched.producer_instance,
173                    watched.effect_variant
174                );
175            }
176            for dispatch in &driver.dispatch_routes {
177                pushln!(
178                    &mut out,
179                    "    dispatches {} -> {}::{} ({:?})",
180                    dispatch.name,
181                    dispatch.target_instance,
182                    dispatch.input_variant,
183                    dispatch.target_kind
184                );
185            }
186            for closure in &driver.refusal_closures {
187                pushln!(
188                    &mut out,
189                    "    closes refusal {} -> {}::{}",
190                    closure.dispatch_route,
191                    closure.feedback_instance,
192                    closure.feedback_input
193                );
194            }
195        }
196        None => pushln!(&mut out, "  (none)"),
197    }
198    out.push('\n');
199
200    pushln!(&mut out, "TRANSACTION_PLANS");
201    for plan in &schema.transaction_plans {
202        pushln!(
203            &mut out,
204            "  {} == {} via {}",
205            plan.name,
206            plan.trigger,
207            plan.store_primitive
208        );
209    }
210    out.push('\n');
211
212    pushln!(&mut out, "ACTOR_PRIORITIES");
213    for priority in &schema.actor_priorities {
214        pushln!(
215            &mut out,
216            "  {} > {} ; {}",
217            priority.higher,
218            priority.lower,
219            priority.reason
220        );
221    }
222    out.push('\n');
223
224    pushln!(&mut out, "SCHEDULER_RULES");
225    for rule in &schema.scheduler_rules {
226        pushln!(&mut out, "  {}", render_scheduler_rule(rule));
227    }
228    out.push('\n');
229
230    pushln!(&mut out, "INVARIANTS");
231    for invariant in &schema.invariants {
232        pushln!(
233            &mut out,
234            "  {} == {}",
235            invariant.name,
236            render_composition_invariant_kind(&invariant.kind)
237        );
238        pushln!(
239            &mut out,
240            "    statement = {}",
241            tla_string(&invariant.statement)
242        );
243    }
244
245    pushln!(&mut out, "====");
246    out
247}
248
249/// Render one coverage anchor as a generated-docs bullet, surfacing its typed
250/// schema target so artifact drift is visible to the rerun-and-diff gate.
251#[cfg(not(test))]
252fn render_coverage_anchor_bullet(anchor: &CoverageAnchor) -> String {
253    let target = match &anchor.target {
254        CoverageSchemaTarget::Machine(machine) => format!("machine `{machine}`"),
255        CoverageSchemaTarget::Route(route) => format!("route `{route}`"),
256    };
257    format!(
258        "- `{}` ({}): `{}` — {}",
259        anchor.id,
260        target,
261        anchor.symbol.as_str(),
262        anchor.note
263    )
264}
265
266#[cfg(not(test))]
267pub fn render_machine_mapping_coverage(
268    schema: &MachineSchema,
269    coverage: &MachineCoverageManifest,
270) -> String {
271    let mut out = String::new();
272
273    pushln!(&mut out, "## Generated Coverage");
274    pushln!(
275        &mut out,
276        "This section is generated from the Rust machine catalog. Do not edit it by hand."
277    );
278    out.push('\n');
279
280    pushln!(&mut out, "### Machine");
281    pushln!(&mut out, "- `{}`", schema.machine);
282    out.push('\n');
283
284    pushln!(&mut out, "### Code Anchors");
285    for anchor in &coverage.code_anchors {
286        pushln!(&mut out, "{}", render_coverage_anchor_bullet(anchor));
287    }
288    out.push('\n');
289
290    pushln!(&mut out, "### Scenarios");
291    for scenario in &coverage.scenarios {
292        pushln!(&mut out, "- `{}` — {}", scenario.id, scenario.summary);
293    }
294    out.push('\n');
295
296    render_semantic_mapping_section(&mut out, "Transitions", &coverage.transition_coverage);
297    render_semantic_mapping_section(&mut out, "Effects", &coverage.effect_coverage);
298    render_semantic_mapping_section(&mut out, "Invariants", &coverage.invariant_coverage);
299
300    out
301}
302
303#[cfg(not(test))]
304pub fn render_composition_mapping_coverage(
305    schema: &CompositionSchema,
306    coverage: &CompositionCoverageManifest,
307) -> String {
308    let mut out = String::new();
309
310    pushln!(&mut out, "## Generated Coverage");
311    pushln!(
312        &mut out,
313        "This section is generated from the Rust composition catalog. Do not edit it by hand."
314    );
315    out.push('\n');
316
317    pushln!(&mut out, "### Composition");
318    pushln!(&mut out, "- `{}`", schema.name);
319    out.push('\n');
320
321    pushln!(&mut out, "### Code Anchors");
322    for anchor in &coverage.code_anchors {
323        pushln!(&mut out, "{}", render_coverage_anchor_bullet(anchor));
324    }
325    out.push('\n');
326
327    pushln!(&mut out, "### Scenarios");
328    for scenario in &coverage.scenarios {
329        pushln!(&mut out, "- `{}` — {}", scenario.id, scenario.summary);
330    }
331    out.push('\n');
332
333    render_semantic_mapping_section(&mut out, "Routes", &coverage.route_coverage);
334    render_semantic_mapping_section(
335        &mut out,
336        "Scheduler Rules",
337        &coverage.scheduler_rule_coverage,
338    );
339    render_semantic_mapping_section(&mut out, "Invariants", &coverage.invariant_coverage);
340
341    out
342}
343
344#[cfg(not(test))]
345pub fn render_machine_kernel_module(
346    schema: &MachineSchema,
347) -> Result<String, MachineKernelRenderError> {
348    render_canonical_stub_modeled_module(schema)
349}
350
351#[cfg(not(test))]
352#[derive(Debug, thiserror::Error)]
353pub enum MachineKernelRenderError {
354    #[error(
355        "MeerkatMachine public TransitionId tail names missing schema transition `{transition}`"
356    )]
357    MissingPublicTransitionTail { transition: String },
358    #[error(
359        "MeerkatMachine public TransitionId tail must name unique schema transitions: rendered {rendered}, schema has {schema}"
360    )]
361    NonUniquePublicTransitionTail { rendered: usize, schema: usize },
362    #[error("MeerkatMachine appended-input section names missing schema input `{input}`")]
363    MissingAppendedInputSectionLast { input: String },
364    #[error(
365        "MeerkatMachine transition `{transition}` belongs to an input declared after the appended-input section; list it in MEERKAT_TRANSITION_ENUM_LATE_TAIL"
366    )]
367    UnlistedLateTransition { transition: String },
368}
369
370// Rust enum order is a public compatibility surface, while transition schema
371// order is a runtime semantic surface: the production proc-macro dispatcher
372// preserves declaration order when it builds same-trigger first-match chains.
373// Keep additions that landed inside the MeerkatMachine transition catalog in
374// this append-only emission tail instead of moving their transition bodies.
375#[cfg(not(test))]
376const MEERKAT_TRANSITION_ENUM_TAIL: &[&str] = &[
377    "RegisterSessionRefusedUnregisterDrainingIdle",
378    "RegisterSessionRefusedUnregisterDrainingAttached",
379    "RegisterSessionRefusedUnregisterDrainingRunning",
380    "RegisterSessionRefusedUnregisterDrainingRetired",
381    "RegisterSessionRefusedUnregisterDrainingStopped",
382    "ClassifyRecoveredTerminalCompletionBatchRecoverInitializing",
383    "ClassifyRecoveredTerminalCompletionBatchRecoverIdle",
384    "ClassifyRecoveredTerminalCompletionBatchRecoverAttached",
385    "ClassifyRecoveredTerminalCompletionBatchRecoverRunning",
386    "ClassifyRecoveredTerminalCompletionBatchRecoverRetired",
387    "ClassifyRecoveredTerminalCompletionBatchRecoverStopped",
388    "ClassifyRecoveredTerminalCompletionBatchDiscardUnrecoverableInitializing",
389    "ClassifyRecoveredTerminalCompletionBatchDiscardUnrecoverableIdle",
390    "ClassifyRecoveredTerminalCompletionBatchDiscardUnrecoverableAttached",
391    "ClassifyRecoveredTerminalCompletionBatchDiscardUnrecoverableRunning",
392    "ClassifyRecoveredTerminalCompletionBatchDiscardUnrecoverableRetired",
393    "ClassifyRecoveredTerminalCompletionBatchDiscardUnrecoverableStopped",
394    "ClassifyRecoveredTerminalCompletionBatchBlockedInitializing",
395    "ClassifyRecoveredTerminalCompletionBatchBlockedIdle",
396    "ClassifyRecoveredTerminalCompletionBatchBlockedAttached",
397    "ClassifyRecoveredTerminalCompletionBatchBlockedRunning",
398    "ClassifyRecoveredTerminalCompletionBatchBlockedRetired",
399    "ClassifyRecoveredTerminalCompletionBatchBlockedStopped",
400    "DeclareRecoveredTerminalCompletionUnrecoverableInitializing",
401    "DeclareRecoveredTerminalCompletionUnrecoverableIdle",
402    "DeclareRecoveredTerminalCompletionUnrecoverableAttached",
403    "DeclareRecoveredTerminalCompletionUnrecoverableRunning",
404    "DeclareRecoveredTerminalCompletionUnrecoverableRetired",
405    "DeclareRecoveredTerminalCompletionUnrecoverableStopped",
406    "PrepareIdleRetainingUnsettledCompletion",
407    "PrepareAttachedRetainingUnsettledCompletion",
408    "DrainQueuedRunRetiredRetainingUnsettledCompletion",
409];
410
411// The last input whose transitions the appended-input section emits in
412// declaration order. The section already carries published variants, so a
413// transition added to the tail above would move them; see the late tail.
414#[cfg(not(test))]
415const MEERKAT_APPENDED_INPUT_SECTION_LAST: &str = "ClassifyStopInputDisposition";
416
417// Append-only emission tail after every other transition: new arms of inputs
418// declared up to MEERKAT_APPENDED_INPUT_SECTION_LAST (in place in the catalog,
419// they would land mid-enum), and every transition of an input declared after
420// it. Rendering refuses a transition of such a later input that is not listed.
421#[cfg(not(test))]
422const MEERKAT_TRANSITION_ENUM_LATE_TAIL: &[&str] = &[
423    "ResolveRuntimeCompletionWaitFailureRequeuedAcrossStopInitializing",
424    "ResolveRuntimeCompletionWaitFailureRequeuedAcrossStopIdle",
425    "ResolveRuntimeCompletionWaitFailureRequeuedAcrossStopAttached",
426    "ResolveRuntimeCompletionWaitFailureRequeuedAcrossStopRunning",
427    "ResolveRuntimeCompletionWaitFailureRequeuedAcrossStopRetired",
428    "ResolveRuntimeCompletionWaitFailureRequeuedAcrossStopStopped",
429    "AuthorizeDurableTailRecoveryContinueIdle",
430    "AuthorizeDurableTailRecoveryRepairContinuableRetiredIdle",
431    "AuthorizeDurableTailRecoveryRepairContinuableRetiredRetired",
432    "AuthorizeDurableTailRecoveryHoldContinuableRetiredIdle",
433    "AuthorizeDurableTailRecoveryHoldContinuableRetiredRetired",
434    "MarkRunResumableInitializing",
435    "MarkRunResumableIdle",
436    "MarkRunResumableAttached",
437    "ResumeRunRunning",
438    "ReleaseResumableRunInitializing",
439    "ReleaseResumableRunIdle",
440    "ReleaseResumableRunAttached",
441    "ReleaseResumableRunRetired",
442    "ReleaseResumableRunStopped",
443    "SettleResumableRunInitializing",
444    "SettleResumableRunIdle",
445    "SettleResumableRunAttached",
446    "SettleResumableRunRetired",
447    "SettleResumableRunStopped",
448    "NormalizeRecoveredInputStagedResumableInitializing",
449    "NormalizeRecoveredInputStagedResumableIdle",
450    "NormalizeRecoveredInputStagedResumableAttached",
451    "NormalizeRecoveredInputStagedResumableRunning",
452    "NormalizeRecoveredInputStagedResumableRetired",
453    "NormalizeRecoveredInputStagedResumableStopped",
454    "NormalizeRecoveredInputAppliedResumableInitializing",
455    "NormalizeRecoveredInputAppliedResumableIdle",
456    "NormalizeRecoveredInputAppliedResumableAttached",
457    "NormalizeRecoveredInputAppliedResumableRunning",
458    "NormalizeRecoveredInputAppliedResumableRetired",
459    "NormalizeRecoveredInputAppliedResumableStopped",
460    "SuspendRunForStopRunningToIdle",
461    "SuspendRunForStopRunningToAttached",
462    "ReplayAppliedRunContributorIdle",
463    "ReplayAppliedRunContributorAttached",
464    "ReplayAppliedRunContributorRunning",
465    "ReplayAppliedRunContributorRetired",
466    "ReplayAppliedRunContributorStopped",
467    "ClassifyStopInputDispositionRetainResumableInitializing",
468    "ClassifyStopInputDispositionRetainResumableIdle",
469    "ClassifyStopInputDispositionRetainResumableAttached",
470    "ClassifyStopInputDispositionRetainResumableRunning",
471    "ClassifyStopInputDispositionRetainResumableRetired",
472    "ClassifyStopInputDispositionRetainResumableStopped",
473    "AuthorizeOperatorDurableTailRepairIdle",
474    "AuthorizeOperatorDurableTailRepairRetired",
475    "AuthorizeOperatorDurableTailRepairRefuseIdle",
476    "AuthorizeOperatorDurableTailRepairRefuseRetired",
477    "AuthorizeOperatorDurableTailRepairRefuseNonQuiescentInitializing",
478    "AuthorizeOperatorDurableTailRepairRefuseNonQuiescentAttached",
479    "AuthorizeOperatorDurableTailRepairRefuseNonQuiescentRunning",
480    "AuthorizeOperatorDurableTailRepairRefuseNonQuiescentStopped",
481    "AuthorizeOperatorDurableTailRepairRefuseNonQuiescentDestroyed",
482    "ResolveRuntimeCompletionResultOutcomeUnknownInitializing",
483    "ResolveRuntimeCompletionResultOutcomeUnknownIdle",
484    "ResolveRuntimeCompletionResultOutcomeUnknownAttached",
485    "ResolveRuntimeCompletionResultOutcomeUnknownRunning",
486    "ResolveRuntimeCompletionResultOutcomeUnknownRetired",
487    "ResolveRuntimeCompletionResultOutcomeUnknownStopped",
488    "ResolveEmptyResumeRetirementRetireIdle",
489    "ResolveEmptyResumeRetirementRetireAttached",
490    "ResolveEmptyResumeRetirementRetireRunning",
491    "ResolveEmptyResumeRetirementRetireRetired",
492    "ResolveEmptyResumeRetirementRetireStopped",
493    "ResolveEmptyResumeRetirementKeepServingIdle",
494    "ResolveEmptyResumeRetirementKeepServingAttached",
495    "ResolveEmptyResumeRetirementKeepServingRunning",
496    "ResolveEmptyResumeRetirementKeepServingRetired",
497    "ResolveEmptyResumeRetirementKeepServingStopped",
498    "ClaimCompositionResidencyIdle",
499    "ClaimCompositionResidencyAttached",
500    "ClaimCompositionResidencyRunning",
501    "ClaimCompositionResidencyRetired",
502    "ClaimCompositionResidencyStopped",
503    "HoldInputControllerIdle",
504    "HoldInputControllerAttached",
505    "HoldInputControllerRunning",
506    "HoldInputControllerRetired",
507    "HoldInputControllerStopped",
508    "ReleaseInputControllerIdle",
509    "ReleaseInputControllerAttached",
510    "ReleaseInputControllerRunning",
511    "ReleaseInputControllerRetired",
512    "ReleaseInputControllerStopped",
513    "ReplaceToolGrantGateIdle",
514    "ReplaceToolGrantGateAttached",
515    "ReplaceToolGrantGateRunning",
516    "ReplaceToolGrantGateRetired",
517    "ReplaceToolGrantGateStopped",
518    "ApplyToolGrantOpenSetChangedIdle",
519    "ApplyToolGrantOpenSetChangedAttached",
520    "ApplyToolGrantOpenSetChangedRunning",
521    "ApplyToolGrantOpenSetChangedRetired",
522    "ApplyToolGrantOpenSetChangedStopped",
523    "ApplyToolGrantOpenSetUnchangedIdle",
524    "ApplyToolGrantOpenSetUnchangedAttached",
525    "ApplyToolGrantOpenSetUnchangedRunning",
526    "ApplyToolGrantOpenSetUnchangedRetired",
527    "ApplyToolGrantOpenSetUnchangedStopped",
528    // The routing denial of a switch onto a target that cannot carry the
529    // session's transcript (0.9.9): declared ahead of its siblings in the
530    // catalog for first-match dispatch, emitted here after every published
531    // variant.
532    "RequestFiniteSwitchTurnTranscriptUnsupportedIdle",
533    "RequestFiniteSwitchTurnTranscriptUnsupportedAttached",
534    "RequestFiniteSwitchTurnTranscriptUnsupportedRunning",
535    "RequestUntilChangedSwitchTurnTranscriptUnsupportedIdle",
536    "RequestUntilChangedSwitchTurnTranscriptUnsupportedAttached",
537    "RequestUntilChangedSwitchTurnTranscriptUnsupportedRunning",
538    "SuspendRunForStopFenceGapRunningToIdle",
539    "SuspendRunForStopFenceGapRunningToAttached",
540    "StopCurrentRunForRunResumableIdle",
541    "StopCurrentRunForRunResumableAttached",
542    // A failed until-changed switch-turn reconfigure withdraws the request
543    // it staged (0.9.10); its input is declared after every published one.
544    "AbortUntilChangedSwitchTurnReconfigureIdle",
545    "AbortUntilChangedSwitchTurnReconfigureAttached",
546    "AbortUntilChangedSwitchTurnReconfigureRunning",
547    "AbortUntilChangedSwitchTurnReconfigureRetired",
548    "AbortUntilChangedSwitchTurnReconfigureStopped",
549    // An until-changed switch-turn refused while another switch is pending
550    // (0.9.10): declared beside its siblings in the catalog for first-match
551    // dispatch, emitted here after every published variant.
552    "RequestUntilChangedSwitchTurnPendingConflictIdle",
553    "RequestUntilChangedSwitchTurnPendingConflictAttached",
554    "RequestUntilChangedSwitchTurnPendingConflictRunning",
555    // A reconfigured until-changed switch-turn completes after a retirement
556    // or a stop (0.9.10).
557    "CompleteUntilChangedSwitchTurnReconfigureRetired",
558    "CompleteUntilChangedSwitchTurnReconfigureStopped",
559    // A host's settle of the run its session retained (0.9.11).
560    "SettleRetainedRunAcceptedIdle",
561    "SettleRetainedRunAcceptedAttached",
562    "SettleRetainedRunBusyRunCurrentInitializing",
563    "SettleRetainedRunBusyRunCurrentIdle",
564    "SettleRetainedRunBusyRunCurrentAttached",
565    "SettleRetainedRunBusyRunCurrentRunning",
566    "SettleRetainedRunBusyRunCurrentRetired",
567    "SettleRetainedRunBusyRunCurrentStopped",
568    "SettleRetainedRunBusyDrainingIdle",
569    "SettleRetainedRunBusyDrainingAttached",
570    "SettleRetainedRunBusyStaleRunIdle",
571    "SettleRetainedRunBusyStaleRunAttached",
572    "SettleRetainedRunBusyNotServingInitializing",
573    "SettleRetainedRunBusyNotServingRunning",
574    "SettleRetainedRunBusyNotServingRetired",
575    "SettleRetainedRunBusyNotServingStopped",
576    "SettleRetainedRunNotRetainedInitializing",
577    "SettleRetainedRunNotRetainedIdle",
578    "SettleRetainedRunNotRetainedAttached",
579    "SettleRetainedRunNotRetainedRunning",
580    "SettleRetainedRunNotRetainedRetired",
581    "SettleRetainedRunNotRetainedStopped",
582    "SettleRetainedRunInertDestroyed",
583    // The run marked resumable whose resumed-run admission could not decide
584    // is held until a later answer releases it.
585    "HoldResumedRunForAdmissionIdle",
586    "HoldResumedRunForAdmissionAttached",
587    "HoldResumedRunForAdmissionRunning",
588    "HoldResumedRunForAdmissionRetired",
589    "HoldResumedRunForAdmissionStopped",
590    "ReleaseResumedRunAdmissionIdle",
591    "ReleaseResumedRunAdmissionAttached",
592    "ReleaseResumedRunAdmissionRunning",
593    "ReleaseResumedRunAdmissionRetired",
594    "ReleaseResumedRunAdmissionStopped",
595    // The scoped tool grant gate's server gate (0.9.11): a model-request
596    // boundary's extension of the gate by a gated server's names, and the
597    // grant path's stage of a gated server. Both inputs are declared after
598    // every published one.
599    "ExtendToolGrantGateChangedIdle",
600    "ExtendToolGrantGateChangedAttached",
601    "ExtendToolGrantGateChangedRunning",
602    "ExtendToolGrantGateChangedRetired",
603    "ExtendToolGrantGateChangedStopped",
604    "ExtendToolGrantGateUnchangedIdle",
605    "ExtendToolGrantGateUnchangedAttached",
606    "ExtendToolGrantGateUnchangedRunning",
607    "ExtendToolGrantGateUnchangedRetired",
608    "ExtendToolGrantGateUnchangedStopped",
609    "SurfaceStageGatedAddIdle",
610    "SurfaceStageGatedAddAttached",
611    "SurfaceStageGatedAddRunning",
612    // A channel's close sweep closes its delegation intake (0.9.11).
613    "CloseLiveDelegationIntakeIdle",
614    "CloseLiveDelegationIntakeAttached",
615    "CloseLiveDelegationIntakeRunning",
616    "CloseLiveDelegationIntakeRetired",
617    "CloseLiveDelegationIntakeStopped",
618    // The recovered ungoverned row's requester batch key (0.9.11), declared
619    // beside BindInputAuthority in the catalog.
620    "BindInputRequesterBatchKeyIdle",
621    "BindInputRequesterBatchKeyAttached",
622    "BindInputRequesterBatchKeyRunning",
623    "BindInputRequesterBatchKeyRetired",
624    "BindInputRequesterBatchKeyStopped",
625    // A host's compaction request and its consumption by the agent's
626    // compaction check (0.9.11).
627    "RequestCompactionRecordedIdle",
628    "RequestCompactionRecordedAttached",
629    "RequestCompactionRecordedRunning",
630    "RequestCompactionAlreadyRecordedIdle",
631    "RequestCompactionAlreadyRecordedAttached",
632    "RequestCompactionAlreadyRecordedRunning",
633    "RequestCompactionNotServingInitializing",
634    "RequestCompactionNotServingRetired",
635    "RequestCompactionNotServingStopped",
636    "RequestCompactionNotServingDestroyed",
637    "ConsumeCompactionRequestTakenRunning",
638    "ConsumeCompactionRequestTakenRetired",
639    "ConsumeCompactionRequestNoneRunning",
640    "ConsumeCompactionRequestNoneRetired",
641    "ConsumeCompactionRequestStaleRunRunning",
642    "ConsumeCompactionRequestStaleRunRetired",
643    "ConsumeCompactionRequestOutsideCheckRunning",
644    "ConsumeCompactionRequestOutsideCheckRetired",
645    "ConsumeCompactionRequestInertInitializing",
646    "ConsumeCompactionRequestInertIdle",
647    "ConsumeCompactionRequestInertAttached",
648    "ConsumeCompactionRequestInertStopped",
649    "ConsumeCompactionRequestInertDestroyed",
650];
651
652// Append-only emission tails for the other machines, whose public
653// TransitionId otherwise follows catalog declaration order. A new arm sits
654// beside its siblings in the catalog, where its first-match chain needs it;
655// listing it here emits it after every published variant instead of moving
656// them. Listed transitions are emitted last, in this order. Append only.
657#[cfg(not(test))]
658const MACHINE_TRANSITION_ENUM_LATE_TAILS: &[(&str, &[&str])] = &[
659    // The durable-tail classification arm 0.9.8 published last, then the
660    // operator-instruction arms (0.9.9) in catalog order, so 0.9.8's public
661    // TransitionId order stays a prefix. Every SessionDocumentMachine arm
662    // added after them is appended here too.
663    (
664        "SessionDocumentMachine",
665        &[
666            "ClassifyDurableTailContinuable",
667            "RecoverSessionInstructionState",
668            "RecoverSessionInstructionTarget",
669            "RecoverSessionInstructionEffective",
670            "RecordInstructionTargetAdvance",
671            "RecordInstructionTargetActiveBudgetExceeded",
672            "RecordInstructionTargetSlotLimitExceeded",
673            "RecordInstructionTargetAlreadyRecorded",
674            "RecordInstructionTargetOwnedBySession",
675            "RecordInstructionTargetAdopt",
676            "RecordInstructionTargetAdoptActiveBudgetExceeded",
677            "RecordInstructionTargetAdoptSlotLimitExceeded",
678            "RecordInstructionTargetOwnedByOtherMob",
679            "SetSessionInstructionNew",
680            "SetSessionInstructionAdvance",
681            "SetSessionInstructionActiveBudgetExceeded",
682            "SetSessionInstructionDuplicate",
683            "SetSessionInstructionConflict",
684            "SetSessionInstructionStale",
685            "SetSessionInstructionOwnedByMob",
686            "SetSessionInstructionMemberSession",
687            "SetSessionInstructionSlotLimitExceeded",
688            "SetSessionInstructionUnknownSlot",
689            "RebindInstructionOwner",
690            "RebindInstructionOwnerUnowned",
691            "RebindInstructionOwnerMemberSession",
692            "ReleaseInstructionTarget",
693            "ReleaseInstructionTargetAlreadyUnowned",
694            "ReleaseInstructionTargetOwnedByOtherMob",
695            "ReleaseInstructionTargetOwnedBySession",
696            "ResolveRunStartInstructionsApply",
697            "ResolveRunStartInstructionsNoChange",
698            "ResolveRunStartInstructionsDeferredLeadingPrefix",
699            "ResolveRunStartInstructionsDeferredUnavailable",
700            "AuthorizeInstructionFoldAtRunStart",
701            "AuthorizeInstructionFoldEffective",
702            "RecoverSessionActivationBodies",
703            "AuthorizeActivationBodyRetirement",
704        ],
705    ),
706    (
707        "SessionTurnAdmissionMachine",
708        &["ResolveDispositionResumeRun"],
709    ),
710    (
711        "OccurrenceLifecycleMachine",
712        &[
713            "ClassifyDuePendingReclaimExhausted",
714            "ClaimPendingAfterAdmission",
715            "ClaimPendingAfterUnprovenDispatch",
716            "TargetProbeBusyExistingRedelivery",
717            "ReclaimExhaustedAfterAdmission",
718            "ReclaimExhaustedAfterUnprovenDispatch",
719            "UnprovenLateNotAdmittedFromClaimed",
720            "UnprovenLateNotAdmittedFromDispatching",
721        ],
722    ),
723    // The member residency twins (archive-only retirements, a Dormant
724    // member's external wiring) sit beside their siblings in the catalog.
725    // Every MobMachine arm added after them is appended here too: an
726    // unlisted arm would be emitted ahead of this tail and move it.
727    (
728        "MobMachine",
729        &[
730            "RetireMemberArchiveOnly",
731            "AdmitDestroyMemberRetireArchiveOnlyRunning",
732            "AdmitDestroyMemberRetireArchiveOnlyStopped",
733            "WireExternalPeerDormantRunning",
734            "WireExternalPeerAlreadyWiredDormant",
735            "UnwireExternalPeerDormantRunning",
736            "RetireRunningReleasingArchiveOnly",
737            "RetireRunningPreservingBindingArchiveOnly",
738            "RetireStoppedReleasingArchiveOnly",
739            "RetireStoppedPreservingBindingArchiveOnly",
740            "ResolveMemberRevivalSessionCreatedRunning",
741            "ResolveMemberRevivalSessionCreatedStaleRunning",
742            "ResolveMemberRevivalSessionCreatedStaleStopped",
743            "ResolveMemberRevivalSessionCreatedStaleCompleted",
744            "ResolveMemberRevivalSessionCreatedStaleDestroyed",
745            "RecoverMemberSeatSessionUnbornRunning",
746            "RecoverMemberSeatSessionBornRunning",
747            "AuthorizeSpawnProfileSeatedRunning",
748            "ExemptMemberFromDefinitionWiringSeatedRunning",
749            "ExemptMemberFromDefinitionWiringSeatedStopped",
750            // Identity entries (0.9.9): the admission probe's entry arm, the
751            // replay of an entry's row, the legacy adoption and the agent
752            // lane's member admission.
753            "ProbeMemberAdmissionIdentityMemberRunning",
754            "ProbeMemberAdmissionIdentityMemberStopped",
755            "ProbeMemberAdmissionIdentityMemberCompleted",
756            "ProbeMemberAdmissionIdentityMemberDestroyed",
757            "RecoverIdentityEntrySeatedRunning",
758            "RecoverIdentityEntrySeatedStopped",
759            "AdoptLegacyIdentityEntryAdopted",
760            "AdoptLegacyIdentityEntryNameHeldByWorker",
761            "AdoptLegacyIdentityEntryNotAdoptable",
762            "AdoptLegacyIdentityEntryStaleObservation",
763            "AdoptLegacyIdentityEntryNotSeated",
764            "AdoptLegacyIdentityEntryAlreadyAnEntry",
765            "AdoptLegacyIdentityEntryNonAuthoritative",
766            "AdoptLegacyIdentityEntryMobNotRunningStopped",
767            "AdoptLegacyIdentityEntryMobNotRunningCompleted",
768            "AdoptLegacyIdentityEntryMobNotRunningDestroyed",
769            "ResolveAgentLaneMemberAdmissionAdmittedRunning",
770            "ResolveAgentLaneMemberAdmissionAdmittedStopped",
771            "ResolveAgentLaneMemberAdmissionAdmittedCompleted",
772            "ResolveAgentLaneMemberAdmissionAdmittedDestroyed",
773            "ResolveAgentLaneMemberAdmissionIdentityMemberRunning",
774            "ResolveAgentLaneMemberAdmissionIdentityMemberStopped",
775            "ResolveAgentLaneMemberAdmissionIdentityMemberCompleted",
776            "ResolveAgentLaneMemberAdmissionIdentityMemberDestroyed",
777            // Rotation targets (0.9.8): the same-session rotation's start and
778            // terminal, the replay of a rotation's intent, and the scoped
779            // release's stale verdict.
780            "BeginMemberRotationSameSessionRunning",
781            "CommitMemberRotationSameSessionRunning",
782            "CommitMemberRotationSameSessionStopped",
783            "CommitMemberRotationSameSessionKickoffRunning",
784            "CommitMemberRotationSameSessionKickoffStopped",
785            "RecoverMemberRotationIntentFreshSessionRunning",
786            "RecoverMemberRotationIntentSameSessionRunning",
787            "RecoverMemberRotationIntentDestroyingRunning",
788            "ClassifyMemberReleaseStaleRunning",
789            "ClassifyMemberReleaseStaleStopped",
790            "ClassifyMemberReleaseStaleCompleted",
791            "ClassifyMemberReleaseStaleDestroyed",
792            // The legacy respawn's refusal of an identity entry (0.9.8), in
793            // every phase an entry lives in.
794            "RespawnIdentityEntryRefusedRunning",
795            "RespawnIdentityEntryRefusedStopped",
796            "RespawnIdentityEntryRefusedCompleted",
797            // The declared apply (0.9.9): one arm per verdict of a declared
798            // identity, the seal of a complete roster, the replay of an
799            // unlisted retirement and the release of an archived session
800            // record.
801            "DeclareIdentityEntryKept",
802            "DeclareIdentityEntrySeatOwed",
803            "DeclareIdentityEntryHostedOnFirstUse",
804            "DeclareIdentityEntryAwaitHeldCreation",
805            "DeclareIdentityEntryRuntimeModeRestamp",
806            "DeclareIdentityEntryRoleMigrate",
807            "DeclareIdentityEntryRoleRotate",
808            "DeclareIdentityEntryRoleMigrationHeld",
809            "DeclareIdentityEntryLifecycleInFlight",
810            "DeclareIdentityEntryRefusedNameHeldByWorker",
811            "DeclareIdentityEntryRefusedHostAdopted",
812            "DeclareIdentityEntryRefusedNonAuthoritative",
813            "DeclareIdentityEntryMobNotRunningStopped",
814            "DeclareIdentityEntryMobNotRunningCompleted",
815            "DeclareIdentityEntryMobNotRunningDestroyed",
816            "SealDeclaredRosterSealed",
817            "SealDeclaredRosterNonAuthoritative",
818            "SealDeclaredRosterMobNotRunningStopped",
819            "SealDeclaredRosterMobNotRunningCompleted",
820            "SealDeclaredRosterMobNotRunningDestroyed",
821            "RecoverIdentityEntryRetiringMarkedRunning",
822            "ForgetArchivedSession",
823            // The explicit resume's refusal to rebuild a member whose host
824            // preparation is owed (0.9.9).
825            "AuthorizeExplicitResumeMemberHeldRunning",
826            // The total replay of an unlisted retirement's start row, and the
827            // declared apply's open fact (0.9.9).
828            "RecoverIdentityEntryRetiringStaleRunning",
829            "OpenDeclaredApplyOpened",
830            "OpenDeclaredApplyBusy",
831            "OpenDeclaredApplyMobNotRunningStopped",
832            "OpenDeclaredApplyMobNotRunningCompleted",
833            "OpenDeclaredApplyMobNotRunningDestroyed",
834            "CloseDeclaredApplyRunning",
835            "CloseDeclaredApplyStopped",
836            "CloseDeclaredApplyCompleted",
837            "CloseDeclaredApplyDestroyed",
838            // The reset's preflight admission (0.9.9).
839            "AdmitResetRunning",
840            "AdmitResetStopped",
841            "AdmitResetCompleted",
842            // The explicit resume's held answer while the mob is still
843            // Stopped, before its preparation (0.9.9).
844            "AuthorizeExplicitResumeMemberHeldStopped",
845            // Created identity entries (0.9.9): the admission probe of a
846            // custody of another origin and of a reserved name, the declared
847            // apply's refusals of a created, removed or unreadable name, the
848            // adoption's refusal of either, the agent lane's unreadable
849            // member, and the recovery of the identity store's created entry
850            // rows.
851            "ProbeMemberAdmissionIdentityMemberOfAnotherOriginRunning",
852            "ProbeMemberAdmissionIdentityMemberOfAnotherOriginStopped",
853            "ProbeMemberAdmissionIdentityMemberOfAnotherOriginCompleted",
854            "ProbeMemberAdmissionIdentityMemberOfAnotherOriginDestroyed",
855            "ProbeMemberAdmissionIdentityNameReservedRunning",
856            "ProbeMemberAdmissionIdentityNameReservedStopped",
857            "ProbeMemberAdmissionIdentityNameReservedCompleted",
858            "ProbeMemberAdmissionIdentityNameReservedDestroyed",
859            "DeclareIdentityEntryRefusedNameOwnedByCreated",
860            "DeclareIdentityEntryRefusedNameTombstoned",
861            "DeclareIdentityEntryRefusedNameUnreadable",
862            "AdoptLegacyIdentityEntryOtherCustody",
863            "ResolveAgentLaneMemberAdmissionUnreadableNameRunning",
864            "ResolveAgentLaneMemberAdmissionUnreadableNameStopped",
865            "ResolveAgentLaneMemberAdmissionUnreadableNameCompleted",
866            "ResolveAgentLaneMemberAdmissionUnreadableNameDestroyed",
867            "RecoverCreatedIdentityEntrySeatedRunning",
868            "RecoverCreatedIdentityEntrySeatedStopped",
869            "RecoverCreatedIdentityEntryRetiredRunning",
870            "RecoverCreatedIdentityEntryRetiredStopped",
871            "RecoverCreatedIdentityEntryPendingRunning",
872            "RecoverCreatedIdentityEntryPendingStopped",
873            "RecoverCreatedIdentityEntryTombstoneRunning",
874            "RecoverCreatedIdentityEntryTombstoneStopped",
875            "RecoverCreatedIdentityEntryUnreadableRunning",
876            "RecoverCreatedIdentityEntryUnreadableStopped",
877            // The retire of an absent identity in a completed and a
878            // destroyed mob (0.9.9), which MobMachine now answers in every
879            // phase.
880            "RetireAbsentCompleted",
881            "RetireAbsentDestroyed",
882            // The operator-instruction region (0.9.9), in catalog order.
883            "SetOperatorInstructionBodyTooLargeRunning",
884            "SetOperatorInstructionBodyTooLargeStopped",
885            "SetOperatorInstructionSlotLimitExceededRunning",
886            "SetOperatorInstructionSlotLimitExceededStopped",
887            "SetOperatorInstructionNewOverBudgetRunning",
888            "SetOperatorInstructionNewOverBudgetStopped",
889            "SetOperatorInstructionNewRunning",
890            "SetOperatorInstructionNewStopped",
891            "SetOperatorInstructionStaleRunning",
892            "SetOperatorInstructionStaleStopped",
893            "SetOperatorInstructionDuplicateRunning",
894            "SetOperatorInstructionDuplicateStopped",
895            "SetOperatorInstructionConflictRunning",
896            "SetOperatorInstructionConflictStopped",
897            "SetOperatorInstructionAdvanceOverBudgetRunning",
898            "SetOperatorInstructionAdvanceOverBudgetStopped",
899            "SetOperatorInstructionAdvanceRunning",
900            "SetOperatorInstructionAdvanceStopped",
901            "SetOperatorInstructionTerminalCompleted",
902            "SetOperatorInstructionTerminalDestroyed",
903            "RevokeOperatorInstructionUnknownSlotRunning",
904            "RevokeOperatorInstructionUnknownSlotStopped",
905            "RevokeOperatorInstructionStaleRunning",
906            "RevokeOperatorInstructionStaleStopped",
907            "RevokeOperatorInstructionDuplicateRunning",
908            "RevokeOperatorInstructionDuplicateStopped",
909            "RevokeOperatorInstructionConflictRunning",
910            "RevokeOperatorInstructionConflictStopped",
911            "RevokeOperatorInstructionAdvanceRunning",
912            "RevokeOperatorInstructionAdvanceStopped",
913            "RevokeOperatorInstructionTerminalCompleted",
914            "RevokeOperatorInstructionTerminalDestroyed",
915            "RecoverOperatorInstructionAppliedRunning",
916            "RecoverOperatorInstructionAppliedStopped",
917            "RecoverOperatorInstructionAppliedCompleted",
918            "RecoverOperatorInstructionStaleRunning",
919            "RecoverOperatorInstructionStaleStopped",
920            "RecoverOperatorInstructionStaleCompleted",
921            "RecoverOperatorInstructionGenerationHighwaterRaised",
922            "RecoverOperatorInstructionGenerationHighwaterKept",
923            "PrepareMemberInstructionDeliveryNotOwedRunning",
924            "PrepareMemberInstructionDeliveryNotOwedStopped",
925            "PrepareMemberInstructionDeliveryUnbornRunning",
926            "PrepareMemberInstructionDeliveryUnbornStopped",
927            "PrepareMemberInstructionDeliveryUnboundRunning",
928            "PrepareMemberInstructionDeliveryUnboundStopped",
929            "PrepareMemberInstructionDeliveryRetiringRunning",
930            "PrepareMemberInstructionDeliveryRetiringStopped",
931            "PrepareMemberInstructionDeliveryDeliverRunning",
932            "PrepareMemberInstructionDeliveryDeliverStopped",
933            "PrepareMemberInstructionDeliveryMobNotRunningCompleted",
934            "PrepareMemberInstructionDeliveryMobNotRunningDestroyed",
935            "RecordMemberInstructionTargetNotOwedRunning",
936            "RecordMemberInstructionTargetNotOwedStopped",
937            "RecordMemberInstructionTargetNotOwedCompleted",
938            "RecordMemberInstructionTargetNotOwedDestroyed",
939            "RecordMemberInstructionTargetStaleSessionRunning",
940            "RecordMemberInstructionTargetStaleSessionStopped",
941            "RecordMemberInstructionTargetStaleSessionCompleted",
942            "RecordMemberInstructionTargetStaleSessionDestroyed",
943            "RecordMemberInstructionTargetSupersededRunning",
944            "RecordMemberInstructionTargetSupersededStopped",
945            "RecordMemberInstructionTargetSupersededCompleted",
946            "RecordMemberInstructionTargetSupersededDestroyed",
947            "RecordMemberInstructionTargetCurrentRunning",
948            "RecordMemberInstructionTargetCurrentStopped",
949            "RecordMemberInstructionTargetCurrentCompleted",
950            "RecordMemberInstructionTargetCurrentDestroyed",
951            "RecordMemberInstructionTargetUnmintedRunning",
952            "RecordMemberInstructionTargetUnmintedStopped",
953            "RecordMemberInstructionTargetUnmintedCompleted",
954            "RecordMemberInstructionTargetUnmintedDestroyed",
955            "RefuseMemberInstructionTargetNotOwedRunning",
956            "RefuseMemberInstructionTargetNotOwedStopped",
957            "RefuseMemberInstructionTargetNotOwedCompleted",
958            "RefuseMemberInstructionTargetNotOwedDestroyed",
959            "RefuseMemberInstructionTargetStaleSessionRunning",
960            "RefuseMemberInstructionTargetStaleSessionStopped",
961            "RefuseMemberInstructionTargetStaleSessionCompleted",
962            "RefuseMemberInstructionTargetStaleSessionDestroyed",
963            "RefuseMemberInstructionTargetSupersededRunning",
964            "RefuseMemberInstructionTargetSupersededStopped",
965            "RefuseMemberInstructionTargetSupersededCompleted",
966            "RefuseMemberInstructionTargetSupersededDestroyed",
967            "RefuseMemberInstructionTargetBlockedRunning",
968            "RefuseMemberInstructionTargetBlockedStopped",
969            "RefuseMemberInstructionTargetBlockedCompleted",
970            "RefuseMemberInstructionTargetBlockedDestroyed",
971            "ResolveMemberInstructionReleaseAuthorizedRunning",
972            "ResolveMemberInstructionReleaseAuthorizedStopped",
973            "ResolveMemberInstructionReleaseAuthorizedCompleted",
974            "ResolveMemberInstructionReleaseAuthorizedDestroyed",
975            "ResolveMemberInstructionReleaseNotNeededRunning",
976            "ResolveMemberInstructionReleaseNotNeededStopped",
977            "ResolveMemberInstructionReleaseNotNeededCompleted",
978            "ResolveMemberInstructionReleaseNotNeededDestroyed",
979            "PrepareMemberInstructionDeliverySpawningRunning",
980            "PrepareMemberInstructionDeliverySpawningStopped",
981            // Identity changes (0.9.9): a change's admission, the record of a
982            // new store-owned entry and the host's changes hold.
983            "AdmitIdentityChangeAdmitted",
984            "AdmitIdentityChangeReplayed",
985            "AdmitIdentityChangeOperationReused",
986            "AdmitIdentityChangeNonAuthoritative",
987            "AdmitIdentityChangeChangesHeld",
988            "AdmitIdentityChangeDecisionUnbound",
989            "AdmitIdentityChangeDecisionExpired",
990            "AdmitIdentityChangeImportedNotHostOperator",
991            "AdmitIdentityChangeGrantRevoked",
992            "AdmitIdentityChangeMobNotRunningStopped",
993            "AdmitIdentityChangeMobNotRunningCompleted",
994            "AdmitIdentityChangeMobNotRunningDestroyed",
995            "RecordCreatedIdentityEntryRecorded",
996            "RecordCreatedIdentityEntryNameHeldByIdentity",
997            "RecordCreatedIdentityEntryNameHeldByWorker",
998            "RecordCreatedIdentityEntryNameTombstoned",
999            "RecordCreatedIdentityEntryNameUnreadable",
1000            "RecordCreatedIdentityEntryNonAuthoritative",
1001            "RecordCreatedIdentityEntryChangesHeld",
1002            "RecordCreatedIdentityEntryMobNotRunningStopped",
1003            "RecordCreatedIdentityEntryMobNotRunningCompleted",
1004            "RecordCreatedIdentityEntryMobNotRunningDestroyed",
1005            "SetIdentityChangesHeldRunning",
1006            "SetIdentityChangesHeldStopped",
1007            "SetIdentityChangesHeldCompleted",
1008            "SetIdentityChangesHeldDestroyed",
1009            // Identity changes (0.9.9): one identity's removal, archive and
1010            // unarchive, and the recovery of a removal or an archive in
1011            // flight and of an archived identity.
1012            "RemoveIdentityEntryRetiring",
1013            "RemoveIdentityEntryRemoved",
1014            "RemoveIdentityEntryAlreadyRemoved",
1015            "RemoveIdentityEntryUnknown",
1016            "RemoveIdentityEntryInFlight",
1017            "RemoveIdentityEntryNameUnreadable",
1018            "RemoveIdentityEntryNonAuthoritative",
1019            "RemoveIdentityEntryChangesHeld",
1020            "RemoveIdentityEntryMobNotRunningStopped",
1021            "RemoveIdentityEntryMobNotRunningCompleted",
1022            "RemoveIdentityEntryMobNotRunningDestroyed",
1023            "ArchiveIdentityEntryArchiving",
1024            "ArchiveIdentityEntryArchived",
1025            "ArchiveIdentityEntryAlreadyArchived",
1026            "ArchiveIdentityEntryOwnedByRoster",
1027            "ArchiveIdentityEntryUnknown",
1028            "ArchiveIdentityEntryInFlight",
1029            "ArchiveIdentityEntryNameUnreadable",
1030            "ArchiveIdentityEntryNonAuthoritative",
1031            "ArchiveIdentityEntryChangesHeld",
1032            "ArchiveIdentityEntryMobNotRunningStopped",
1033            "ArchiveIdentityEntryMobNotRunningCompleted",
1034            "ArchiveIdentityEntryMobNotRunningDestroyed",
1035            "UnarchiveIdentityEntryRestored",
1036            "UnarchiveIdentityEntryNotArchived",
1037            "UnarchiveIdentityEntryOwnedByRoster",
1038            "UnarchiveIdentityEntryUnknown",
1039            "UnarchiveIdentityEntryInFlight",
1040            "UnarchiveIdentityEntryNameUnreadable",
1041            "UnarchiveIdentityEntryNonAuthoritative",
1042            "UnarchiveIdentityEntryChangesHeld",
1043            "UnarchiveIdentityEntryMobNotRunningStopped",
1044            "UnarchiveIdentityEntryMobNotRunningCompleted",
1045            "UnarchiveIdentityEntryMobNotRunningDestroyed",
1046            "RecoverCreatedIdentityEntryRemovingRunning",
1047            "RecoverCreatedIdentityEntryRemovingStopped",
1048            "RecoverCreatedIdentityEntryArchivingRunning",
1049            "RecoverCreatedIdentityEntryArchivingStopped",
1050            "RecoverCreatedIdentityEntryArchivedRunning",
1051            "RecoverCreatedIdentityEntryArchivedStopped",
1052            // Identity changes (0.9.9): a store-owned update decided against
1053            // a spec that is no longer its identity's.
1054            "AdmitIdentityChangeStaleSpec",
1055            // Host preparation and held constructions (0.9.9): the declared
1056            // apply's verdict for an identity awaiting its preparation, a
1057            // held construction's start, a settle, and an attempt's end.
1058            "DeclareIdentityEntryPreparationPending",
1059            "BeginPreparationConstructionHeld",
1060            "BeginPreparationConstructionNotPending",
1061            "BeginPreparationConstructionNotConstructed",
1062            "BeginPreparationConstructionConstructionOpen",
1063            "BeginPreparationConstructionNonAuthoritative",
1064            "BeginPreparationConstructionMobNotRunningStopped",
1065            "BeginPreparationConstructionMobNotRunningCompleted",
1066            "BeginPreparationConstructionMobNotRunningDestroyed",
1067            "SettleHostPreparationSeat",
1068            "SettleHostPreparationActivationAccepted",
1069            "SettleHostPreparationNotPending",
1070            "SettleHostPreparationConstructionRequired",
1071            "SettleHostPreparationConstructionOpen",
1072            "SettleHostPreparationStaleAttempt",
1073            "SettleHostPreparationExpired",
1074            "SettleHostPreparationMismatch",
1075            "SettleHostPreparationActivationPending",
1076            "SettleHostPreparationNonAuthoritative",
1077            "SettleHostPreparationMobNotRunningStopped",
1078            "SettleHostPreparationMobNotRunningCompleted",
1079            "SettleHostPreparationMobNotRunningDestroyed",
1080            "EndPreparationConstructionEndedRunning",
1081            "EndPreparationConstructionEndedStopped",
1082            "EndPreparationConstructionEndedCompleted",
1083            "EndPreparationConstructionEndedDestroyed",
1084            "EndPreparationConstructionNotOpenRunning",
1085            "EndPreparationConstructionNotOpenStopped",
1086            "EndPreparationConstructionNotOpenCompleted",
1087            "EndPreparationConstructionNotOpenDestroyed",
1088            "EndPreparationConstructionActivationPendingRunning",
1089            "EndPreparationConstructionActivationPendingStopped",
1090            "EndPreparationConstructionActivationPendingCompleted",
1091            "EndPreparationConstructionActivationPendingDestroyed",
1092            // Identity changes (0.9.9): the archive of an identity awaiting
1093            // its host's preparation, a store-owned update of an archived or
1094            // pending identity, and the one-entry unlist of a roster-owned
1095            // identity.
1096            "ArchiveIdentityEntryPreparationPending",
1097            "DeclareIdentityEntryRecordOnly",
1098            "UnlistIdentityEntryRetiring",
1099            "UnlistIdentityEntryRemoved",
1100            "UnlistIdentityEntryDeferred",
1101            "UnlistIdentityEntryNotADeclaredEntry",
1102            "UnlistIdentityEntryNonAuthoritative",
1103            "UnlistIdentityEntryMobNotRunningStopped",
1104            "UnlistIdentityEntryMobNotRunningCompleted",
1105            "UnlistIdentityEntryMobNotRunningDestroyed",
1106            // The legacy adoption of an unlisted member and the retirement
1107            // of one placed or bound to no session, without its adoption
1108            // (0.9.11).
1109            "AdoptLegacyIdentityEntryAdoptedUnlisted",
1110            "AdoptLegacyIdentityEntryRetireUnadopted",
1111            // A host's adoption over a declared identity entry (0.9.11): its
1112            // archive terminals, the takeover's verdicts and the replay of
1113            // its mark.
1114            "ObserveMemberRetirementArchivedLiveHostAdopted",
1115            "ObserveMemberRetirementArchivedRetiredHostAdopted",
1116            "TakeOverIdentityEntryAdopting",
1117            "TakeOverIdentityEntryEnded",
1118            "TakeOverIdentityEntryDeferred",
1119            "TakeOverIdentityEntryNotADeclaredEntry",
1120            "TakeOverIdentityEntryNonAuthoritative",
1121            "TakeOverIdentityEntryMobNotRunningStopped",
1122            "TakeOverIdentityEntryMobNotRunningCompleted",
1123            "TakeOverIdentityEntryMobNotRunningDestroyed",
1124            "RecoverIdentityEntryAdoptingMarkedRunning",
1125            "RecoverIdentityEntryAdoptingStaleRunning",
1126            // A build preparation the host asked to retry (0.9.11): the wake
1127            // feedback arm that records it, and its resolution.
1128            "ResolveMemberRevivalRetryableBuildPreparationRunning",
1129            "ResolveMemberBuildPreparationRunning",
1130            "ResolveMemberBuildPreparationStopped",
1131            "ResolveMemberBuildPreparationCompleted",
1132            // Owned edges (0.9.11): an owned edge's declaration and end, a
1133            // plain unwire's admission, and an owned edge's recovery at a
1134            // start.
1135            "DeclareOwnedIdentityEdgeDeclared",
1136            "DeclareOwnedIdentityEdgeAlreadyOwned",
1137            "DeclareOwnedIdentityEdgePeerUnknown",
1138            "DeclareOwnedIdentityEdgeOwnerInvalid",
1139            "DeclareOwnedIdentityEdgeMobNotRunningStopped",
1140            "DeclareOwnedIdentityEdgeMobNotRunningCompleted",
1141            "DeclareOwnedIdentityEdgeMobNotRunningDestroyed",
1142            "EndOwnedIdentityEdgeEnded",
1143            "EndOwnedIdentityEdgeNotOwner",
1144            "EndOwnedIdentityEdgeAbsent",
1145            "EndOwnedIdentityEdgeNonAuthoritative",
1146            "EndOwnedIdentityEdgeChangesHeld",
1147            "EndOwnedIdentityEdgeMobNotRunningStopped",
1148            "EndOwnedIdentityEdgeMobNotRunningCompleted",
1149            "EndOwnedIdentityEdgeMobNotRunningDestroyed",
1150            "AdmitMemberUnwireAdmittedRunning",
1151            "AdmitMemberUnwireAdmittedStopped",
1152            "AdmitMemberUnwireAdmittedCompleted",
1153            "AdmitMemberUnwireAdmittedDestroyed",
1154            "AdmitMemberUnwireOwnedEdgeRunning",
1155            "AdmitMemberUnwireOwnedEdgeStopped",
1156            "AdmitMemberUnwireOwnedEdgeCompleted",
1157            "AdmitMemberUnwireOwnedEdgeDestroyed",
1158            "RecoverOwnedIdentityEdgeRecoveredRunning",
1159            "RecoverOwnedIdentityEdgeRecoveredStopped",
1160            "RecoverOwnedIdentityEdgeSkippedRunning",
1161            "RecoverOwnedIdentityEdgeSkippedStopped",
1162            // Adoption into store custody (0.9.11), one arm per verdict.
1163            "AdoptIdentityIntoStoreAdopted",
1164            "AdoptIdentityIntoStoreNotAdoptable",
1165            "AdoptIdentityIntoStorePredecessorMismatch",
1166            "AdoptIdentityIntoStoreAdmissionUnsettled",
1167            "AdoptIdentityIntoStoreDeclaredApplyOpen",
1168            "AdoptIdentityIntoStoreNameUnreadable",
1169            "AdoptIdentityIntoStoreNameTombstoned",
1170            "AdoptIdentityIntoStoreNonAuthoritative",
1171            "AdoptIdentityIntoStoreChangesHeld",
1172            "AdoptIdentityIntoStoreMobNotRunningStopped",
1173            "AdoptIdentityIntoStoreMobNotRunningCompleted",
1174            "AdoptIdentityIntoStoreMobNotRunningDestroyed",
1175            // The downgrade cycle (0.9.11): the admission after a purge, the
1176            // purge, the boot's rowless reservation and the import, one arm
1177            // per verdict.
1178            "AdmitIdentityChangeRowsPurged",
1179            "PurgeIdentityRowsPurged",
1180            "PurgeIdentityRowsNonAuthoritative",
1181            "PurgeIdentityRowsReplayed",
1182            "PurgeIdentityRowsOperationReused",
1183            "PurgeIdentityRowsRowsPurged",
1184            "PurgeIdentityRowsNotHostOperator",
1185            "PurgeIdentityRowsChangesNotHeld",
1186            "PurgeIdentityRowsMobNotRunningStopped",
1187            "PurgeIdentityRowsMobNotRunningCompleted",
1188            "PurgeIdentityRowsMobNotRunningDestroyed",
1189            "RecoverRowlessCreatedEntryReservedRunning",
1190            "RecoverRowlessCreatedEntryReservedStopped",
1191            "RecoverRowlessCreatedEntryKeptRunning",
1192            "RecoverRowlessCreatedEntryKeptStopped",
1193            "ImportIdentityRecordRestoredInPlace",
1194            "ImportIdentityRecordRestoredOwedSeat",
1195            "ImportIdentityRecordRestoredPending",
1196            "ImportIdentityRecordRestoredArchived",
1197            "ImportIdentityRecordRestoredTombstone",
1198            "ImportIdentityRecordRestoredByAdoption",
1199            "ImportIdentityRecordUnchanged",
1200            "ImportIdentityRecordNameTakenMeanwhile",
1201            "ImportIdentityRecordUnsettled",
1202            "ImportIdentityRecordNonAuthoritative",
1203            "ImportIdentityRecordChangesHeld",
1204            "ImportIdentityRecordRowsPurged",
1205            "ImportIdentityRecordMobNotRunningStopped",
1206            "ImportIdentityRecordMobNotRunningCompleted",
1207            "ImportIdentityRecordMobNotRunningDestroyed",
1208            // Owned edges and the downgrade cycle (0.9.11): an owned edge's
1209            // realization, an import's restoration of one, and the purge
1210            // with no row to purge.
1211            "AdmitOwnedEdgeRealizationRealizeRunning",
1212            "AdmitOwnedEdgeRealizationRealizeStopped",
1213            "AdmitOwnedEdgeRealizationRealizeCompleted",
1214            "AdmitOwnedEdgeRealizationRealizeDestroyed",
1215            "AdmitOwnedEdgeRealizationNotOwnedRunning",
1216            "AdmitOwnedEdgeRealizationNotOwnedStopped",
1217            "AdmitOwnedEdgeRealizationNotOwnedCompleted",
1218            "AdmitOwnedEdgeRealizationNotOwnedDestroyed",
1219            "AdmitOwnedEdgeRealizationEndNotAnIdentityRunning",
1220            "AdmitOwnedEdgeRealizationEndNotAnIdentityStopped",
1221            "AdmitOwnedEdgeRealizationEndNotAnIdentityCompleted",
1222            "AdmitOwnedEdgeRealizationEndNotAnIdentityDestroyed",
1223            "RestoreOwnedIdentityEdgeRestored",
1224            "RestoreOwnedIdentityEdgeSkipped",
1225            "RestoreOwnedIdentityEdgeMobNotRunningStopped",
1226            "RestoreOwnedIdentityEdgeMobNotRunningCompleted",
1227            "RestoreOwnedIdentityEdgeMobNotRunningDestroyed",
1228            "PurgeIdentityRowsNothingToPurge",
1229            // The seal refused while an unseated entry it does not list
1230            // remains, which the one-entry unlist ends first (0.9.11).
1231            "SealDeclaredRosterRefused",
1232            // A respawn's abandonment replayed after a later life of its
1233            // name ended, a no-op (0.9.11).
1234            "ObserveRespawnTopologyAbandonedStaleEndedSuccessor",
1235            // A member build's tool dispatch admission (0.9.11), in every
1236            // phase.
1237            "ResolveMemberDispatchAdmissionAskHostRunning",
1238            "ResolveMemberDispatchAdmissionAskHostStopped",
1239            "ResolveMemberDispatchAdmissionAskHostCompleted",
1240            "ResolveMemberDispatchAdmissionAskHostDestroyed",
1241            "ResolveMemberDispatchAdmissionInheritRunning",
1242            "ResolveMemberDispatchAdmissionInheritStopped",
1243            "ResolveMemberDispatchAdmissionInheritCompleted",
1244            "ResolveMemberDispatchAdmissionInheritDestroyed",
1245            "ResolveMemberDispatchAdmissionRefusedRunning",
1246            "ResolveMemberDispatchAdmissionRefusedStopped",
1247            "ResolveMemberDispatchAdmissionRefusedCompleted",
1248            "ResolveMemberDispatchAdmissionRefusedDestroyed",
1249            "ResolveMemberDispatchAdmissionNoneRequiredRunning",
1250            "ResolveMemberDispatchAdmissionNoneRequiredStopped",
1251            "ResolveMemberDispatchAdmissionNoneRequiredCompleted",
1252            "ResolveMemberDispatchAdmissionNoneRequiredDestroyed",
1253            // The record of a member incarnation whose lineage runs under a
1254            // tool dispatch admission (0.9.11).
1255            "RecordMemberDispatchAdmissionLineageRunning",
1256            "RecordMemberDispatchAdmissionLineageStopped",
1257            // An identity's life marker (0.9.11): the end of a retirement
1258            // that ends the identity, and the resets recovered at resume.
1259            "EndIdentityLifeRunning",
1260            "EndIdentityLifeStopped",
1261            "EndIdentityLifeCompleted",
1262            "EndIdentityLifeDestroyed",
1263            "RecoverIdentityLifeResetsRunning",
1264            "RecoverIdentityLifeResetsStopped",
1265            "RecoverIdentityLifeResetsCompleted",
1266            "RecoverIdentityLifeResetsDestroyed",
1267            // External work refused for an identity entry and for a name
1268            // reserved unreadable (0.9.11).
1269            "ResolveSubmitWorkRejectionIdentityMember",
1270            "ResolveSubmitWorkRejectionIdentityMemberUnreadableName",
1271        ],
1272    ),
1273    // The end of a grant with its subject (0.9.11), after every arm 0.9.10
1274    // published and the run-scope arms (0.9.11), which follow them in
1275    // catalog order; then the end with its subject of a run-ended grant.
1276    // Every ToolGrantLifecycleMachine arm added after them is appended here
1277    // too, so none of them moves.
1278    (
1279        "ToolGrantLifecycleMachine",
1280        &[
1281            "EndWithSubjectActive",
1282            "EndWithSubjectAfterDeadline",
1283            "EndWithSubjectSettledExpired",
1284            "EndWithSubjectSettledRevoked",
1285            "AdmitEndedWithSubject",
1286            "EndWithSubjectSettledRunEnded",
1287        ],
1288    ),
1289    // The entered-step arms of the review attempt lifecycle (0.9.7), after
1290    // every arm 0.9.6 published. Every ApprovalLifecycleMachine arm added
1291    // after them is appended here too, so none of them moves.
1292    (
1293        "ApprovalLifecycleMachine",
1294        &[
1295            "AdmitEnteredStepRejectedMissing",
1296            "AdmitEnteredStepRejectedConsentLinked",
1297            "AdmitEnteredStepRejectedRetired",
1298            "AdmitEnteredStepRejectedNotEntered",
1299            "AdmitEnteredStep",
1300            "AdmitEnteredStepRejectedClosing",
1301            "ReleaseReviewUsedClosing",
1302            "ReleaseReviewRejectedClosing",
1303            "FinishEnteredStepRejectedMissing",
1304            "FinishEnteredStepRejectedNotInFlight",
1305            "FinishEnteredStepOpen",
1306            "FinishEnteredStepClosing",
1307            "FinishEnteredStepReleases",
1308        ],
1309    ),
1310];
1311
1312#[cfg(not(test))]
1313fn transitions_in_public_enum_order(
1314    schema: &MachineSchema,
1315) -> Result<Vec<&TransitionSchema>, MachineKernelRenderError> {
1316    if schema.machine.as_ref() != "MeerkatMachine" {
1317        let late_names = MACHINE_TRANSITION_ENUM_LATE_TAILS
1318            .iter()
1319            .find(|(machine, _)| *machine == schema.machine.as_ref())
1320            .map_or(&[][..], |(_, names)| *names);
1321        let mut ordered: Vec<&TransitionSchema> = schema
1322            .transitions
1323            .iter()
1324            .filter(|transition| !late_names.contains(&transition.name.as_ref()))
1325            .collect();
1326        for expected_name in late_names {
1327            let transition = schema
1328                .transitions
1329                .iter()
1330                .find(|transition| transition.name.as_ref() == *expected_name)
1331                .ok_or_else(|| MachineKernelRenderError::MissingPublicTransitionTail {
1332                    transition: (*expected_name).to_owned(),
1333                })?;
1334            ordered.push(transition);
1335        }
1336        return Ok(ordered);
1337    }
1338
1339    let named_transitions = |names: &[&str]| {
1340        names
1341            .iter()
1342            .map(|expected_name| {
1343                schema
1344                    .transitions
1345                    .iter()
1346                    .find(|transition| transition.name.as_ref() == *expected_name)
1347                    .ok_or_else(|| MachineKernelRenderError::MissingPublicTransitionTail {
1348                        transition: (*expected_name).to_owned(),
1349                    })
1350            })
1351            .collect::<Result<Vec<_>, _>>()
1352    };
1353    let compatibility_tail = named_transitions(MEERKAT_TRANSITION_ENUM_TAIL)?;
1354    let late_tail = named_transitions(MEERKAT_TRANSITION_ENUM_LATE_TAIL)?;
1355    let listed_in_a_tail = |transition: &TransitionSchema| {
1356        MEERKAT_TRANSITION_ENUM_TAIL.contains(&transition.name.as_ref())
1357            || MEERKAT_TRANSITION_ENUM_LATE_TAIL.contains(&transition.name.as_ref())
1358    };
1359    let input_position = |transition: &TransitionSchema| match &transition.on {
1360        meerkat_machine_schema::TriggerMatch::Input { variant, .. } => schema
1361            .inputs
1362            .variants
1363            .iter()
1364            .position(|input| input.name.as_str() == variant.as_str()),
1365        meerkat_machine_schema::TriggerMatch::Signal { .. } => None,
1366    };
1367    // Inputs appended after the historical compatibility tail must append
1368    // their transitions after it too. Derive this boundary from the existing
1369    // tail and input declaration order, not a second list of new family names.
1370    let compatibility_input_end = compatibility_tail
1371        .iter()
1372        .filter_map(|transition| input_position(transition))
1373        .max();
1374    let appended_section_last = schema
1375        .inputs
1376        .variants
1377        .iter()
1378        .position(|input| input.name.as_str() == MEERKAT_APPENDED_INPUT_SECTION_LAST)
1379        .ok_or_else(
1380            || MachineKernelRenderError::MissingAppendedInputSectionLast {
1381                input: MEERKAT_APPENDED_INPUT_SECTION_LAST.to_owned(),
1382            },
1383        )?;
1384    let appended_input_transition = |transition: &TransitionSchema| {
1385        compatibility_input_end
1386            .zip(input_position(transition))
1387            .is_some_and(|(end, position)| position > end)
1388    };
1389    if let Some(unlisted) = schema.transitions.iter().find(|transition| {
1390        input_position(transition).is_some_and(|position| position > appended_section_last)
1391            && !MEERKAT_TRANSITION_ENUM_LATE_TAIL.contains(&transition.name.as_ref())
1392    }) {
1393        return Err(MachineKernelRenderError::UnlistedLateTransition {
1394            transition: unlisted.name.as_ref().to_owned(),
1395        });
1396    }
1397    let mut ordered = Vec::with_capacity(schema.transitions.len());
1398    ordered.extend(schema.transitions.iter().filter(|transition| {
1399        !listed_in_a_tail(transition) && !appended_input_transition(transition)
1400    }));
1401    ordered.extend(compatibility_tail);
1402    ordered.extend(schema.transitions.iter().filter(|transition| {
1403        !listed_in_a_tail(transition) && appended_input_transition(transition)
1404    }));
1405    ordered.extend(late_tail);
1406    if ordered.len() != schema.transitions.len() {
1407        return Err(MachineKernelRenderError::NonUniquePublicTransitionTail {
1408            rendered: ordered.len(),
1409            schema: schema.transitions.len(),
1410        });
1411    }
1412    Ok(ordered)
1413}
1414
1415#[cfg(not(test))]
1416fn render_canonical_stub_modeled_module(
1417    schema: &MachineSchema,
1418) -> Result<String, MachineKernelRenderError> {
1419    let mut out = String::new();
1420    let module_name = machine_slug(&schema.machine);
1421    let catalog_fn = format!("catalog::dsl::dsl_{module_name}_machine");
1422    let has_signals = !schema.signals.variants.is_empty();
1423
1424    pushln!(
1425        &mut out,
1426        "// @generated — Generated by `cargo xtask machine-codegen --all`."
1427    );
1428    pushln!(
1429        &mut out,
1430        "#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::implicit_clone, clippy::unnecessary_cast, clippy::redundant_clone, clippy::zero_sized_map_values)]"
1431    );
1432    pushln!(&mut out);
1433    pushln!(
1434        &mut out,
1435        "pub fn schema() -> meerkat_machine_schema::MachineSchema {{"
1436    );
1437    pushln!(&mut out, "    meerkat_machine_schema::{catalog_fn}()");
1438    pushln!(&mut out, "}}");
1439    pushln!(&mut out);
1440
1441    let named_type_aliases = collect_machine_named_types(schema);
1442    if !named_type_aliases.is_empty() {
1443        for alias in named_type_aliases {
1444            if let Some(atom) = lookup_named_type_atom(schema, &alias) {
1445                render_named_type_definition(&mut out, &alias, atom);
1446            }
1447        }
1448        pushln!(&mut out);
1449    }
1450
1451    pushln!(&mut out, "pub trait Context {{}}");
1452    pushln!(&mut out, "pub struct EmptyContext;");
1453    pushln!(&mut out, "impl Context for EmptyContext {{}}");
1454    pushln!(&mut out);
1455
1456    pushln!(&mut out, "#[allow(non_camel_case_types)]");
1457    pushln!(
1458        &mut out,
1459        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1460    );
1461    pushln!(&mut out, "pub enum Phase {{");
1462    for variant in &schema.state.phase.variants {
1463        pushln!(&mut out, "    {},", rust_ident(&variant.name));
1464    }
1465    pushln!(&mut out, "}}");
1466    pushln!(&mut out);
1467
1468    render_value_derive(&mut out, "", &schema.state.fields);
1469    pushln!(&mut out, "pub struct State {{");
1470    pushln!(&mut out, "    pub phase: Phase,");
1471    for field in &schema.state.fields {
1472        pushln!(
1473            &mut out,
1474            "    pub {}: {},",
1475            rust_field_ident(&field.name),
1476            render_rust_type_ref(&field.ty)
1477        );
1478    }
1479    pushln!(&mut out, "}}");
1480    render_redacted_debug_impl(&mut out, "", "State", &["phase"], &schema.state.fields);
1481    pushln!(&mut out, "impl Default for State {{");
1482    pushln!(&mut out, "    fn default() -> Self {{");
1483    pushln!(&mut out, "        initial_state()");
1484    pushln!(&mut out, "    }}");
1485    pushln!(&mut out, "}}");
1486    pushln!(&mut out);
1487
1488    pushln!(&mut out, "pub mod inputs {{");
1489    pushln!(&mut out, "    #[allow(unused_imports)]");
1490    pushln!(&mut out, "    use super::*;");
1491    for variant in &schema.inputs.variants {
1492        render_value_derive(&mut out, "    ", &variant.fields);
1493        pushln!(&mut out, "    pub struct {} {{", rust_ident(&variant.name));
1494        for field in &variant.fields {
1495            pushln!(
1496                &mut out,
1497                "        pub {}: {},",
1498                rust_field_ident(&field.name),
1499                render_rust_type_ref(&field.ty)
1500            );
1501        }
1502        pushln!(&mut out, "    }}");
1503        render_redacted_debug_impl(
1504            &mut out,
1505            "    ",
1506            &rust_ident(&variant.name),
1507            &[],
1508            &variant.fields,
1509        );
1510    }
1511    pushln!(&mut out, "}}");
1512    pushln!(&mut out);
1513    pushln!(
1514        &mut out,
1515        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1516    );
1517    pushln!(&mut out, "pub enum Input {{");
1518    for variant in &schema.inputs.variants {
1519        pushln!(
1520            &mut out,
1521            "    {}(inputs::{}),",
1522            rust_ident(&variant.name),
1523            rust_ident(&variant.name)
1524        );
1525    }
1526    pushln!(&mut out, "}}");
1527    pushln!(&mut out, "impl Input {{");
1528    pushln!(&mut out, "    pub fn kind(&self) -> InputKind {{");
1529    pushln!(&mut out, "        match self {{");
1530    for variant in &schema.inputs.variants {
1531        pushln!(
1532            &mut out,
1533            "            Self::{}(_) => InputKind::{},",
1534            rust_ident(&variant.name),
1535            rust_ident(&variant.name)
1536        );
1537    }
1538    pushln!(&mut out, "        }}");
1539    pushln!(&mut out, "    }}");
1540    pushln!(&mut out, "}}");
1541    pushln!(
1542        &mut out,
1543        "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1544    );
1545    pushln!(&mut out, "pub enum InputKind {{");
1546    for variant in &schema.inputs.variants {
1547        pushln!(&mut out, "    {},", rust_ident(&variant.name));
1548    }
1549    pushln!(&mut out, "}}");
1550    pushln!(&mut out);
1551
1552    if has_signals {
1553        pushln!(&mut out, "pub mod signals {{");
1554        pushln!(&mut out, "    #[allow(unused_imports)]");
1555        pushln!(&mut out, "    use super::*;");
1556        for variant in &schema.signals.variants {
1557            render_value_derive(&mut out, "    ", &variant.fields);
1558            pushln!(&mut out, "    pub struct {} {{", rust_ident(&variant.name));
1559            for field in &variant.fields {
1560                pushln!(
1561                    &mut out,
1562                    "        pub {}: {},",
1563                    rust_field_ident(&field.name),
1564                    render_rust_type_ref(&field.ty)
1565                );
1566            }
1567            pushln!(&mut out, "    }}");
1568            render_redacted_debug_impl(
1569                &mut out,
1570                "    ",
1571                &rust_ident(&variant.name),
1572                &[],
1573                &variant.fields,
1574            );
1575        }
1576        pushln!(&mut out, "}}");
1577        pushln!(&mut out);
1578        pushln!(
1579            &mut out,
1580            "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1581        );
1582        pushln!(&mut out, "pub enum Signal {{");
1583        for variant in &schema.signals.variants {
1584            pushln!(
1585                &mut out,
1586                "    {}(signals::{}),",
1587                rust_ident(&variant.name),
1588                rust_ident(&variant.name)
1589            );
1590        }
1591        pushln!(&mut out, "}}");
1592        pushln!(&mut out, "impl Signal {{");
1593        pushln!(&mut out, "    pub fn kind(&self) -> SignalKind {{");
1594        pushln!(&mut out, "        match self {{");
1595        for variant in &schema.signals.variants {
1596            pushln!(
1597                &mut out,
1598                "            Self::{}(_) => SignalKind::{},",
1599                rust_ident(&variant.name),
1600                rust_ident(&variant.name)
1601            );
1602        }
1603        pushln!(&mut out, "        }}");
1604        pushln!(&mut out, "    }}");
1605        pushln!(&mut out, "}}");
1606        pushln!(
1607            &mut out,
1608            "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1609        );
1610        pushln!(&mut out, "pub enum SignalKind {{");
1611        for variant in &schema.signals.variants {
1612            pushln!(&mut out, "    {},", rust_ident(&variant.name));
1613        }
1614        pushln!(&mut out, "}}");
1615        pushln!(&mut out);
1616    }
1617
1618    pushln!(&mut out, "pub mod effects {{");
1619    pushln!(&mut out, "    #[allow(unused_imports)]");
1620    pushln!(&mut out, "    use super::*;");
1621    for variant in &schema.effects.variants {
1622        render_value_derive(&mut out, "    ", &variant.fields);
1623        pushln!(&mut out, "    pub struct {} {{", rust_ident(&variant.name));
1624        for field in &variant.fields {
1625            pushln!(
1626                &mut out,
1627                "        pub {}: {},",
1628                rust_field_ident(&field.name),
1629                render_rust_type_ref(&field.ty)
1630            );
1631        }
1632        pushln!(&mut out, "    }}");
1633        render_redacted_debug_impl(
1634            &mut out,
1635            "    ",
1636            &rust_ident(&variant.name),
1637            &[],
1638            &variant.fields,
1639        );
1640    }
1641    pushln!(&mut out, "}}");
1642    pushln!(&mut out);
1643    pushln!(
1644        &mut out,
1645        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1646    );
1647    pushln!(&mut out, "pub enum Effect {{");
1648    for variant in &schema.effects.variants {
1649        pushln!(
1650            &mut out,
1651            "    {}(effects::{}),",
1652            rust_ident(&variant.name),
1653            rust_ident(&variant.name)
1654        );
1655    }
1656    pushln!(&mut out, "}}");
1657    pushln!(
1658        &mut out,
1659        "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1660    );
1661    pushln!(&mut out, "pub enum EffectKind {{");
1662    for variant in &schema.effects.variants {
1663        pushln!(&mut out, "    {},", rust_ident(&variant.name));
1664    }
1665    pushln!(&mut out, "}}");
1666    pushln!(&mut out);
1667
1668    render_command_capability_section(&mut out, schema);
1669
1670    pushln!(&mut out, "#[allow(non_camel_case_types)]");
1671    pushln!(
1672        &mut out,
1673        "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1674    );
1675    pushln!(&mut out, "pub enum TransitionId {{");
1676    for transition in transitions_in_public_enum_order(schema)? {
1677        pushln!(&mut out, "    {},", rust_ident(&transition.name));
1678    }
1679    pushln!(&mut out, "}}");
1680    pushln!(&mut out, "#[allow(non_camel_case_types)]");
1681    pushln!(
1682        &mut out,
1683        "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1684    );
1685    pushln!(&mut out, "pub enum GuardId {{");
1686    pushln!(&mut out, "    None,");
1687    pushln!(&mut out, "}}");
1688    pushln!(&mut out, "#[allow(non_camel_case_types)]");
1689    pushln!(
1690        &mut out,
1691        "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1692    );
1693    pushln!(&mut out, "pub enum HelperId {{");
1694    pushln!(&mut out, "    None,");
1695    pushln!(&mut out, "}}");
1696    pushln!(&mut out);
1697    pushln!(
1698        &mut out,
1699        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1700    );
1701    pushln!(&mut out, "pub struct GuardRejection {{");
1702    pushln!(&mut out, "    pub transition_id: TransitionId,");
1703    pushln!(&mut out, "    pub guard_id: GuardId,");
1704    pushln!(&mut out, "}}");
1705    pushln!(
1706        &mut out,
1707        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1708    );
1709    pushln!(&mut out, "pub enum TriggerDiscriminant {{");
1710    pushln!(&mut out, "    Input(InputKind),");
1711    if has_signals {
1712        pushln!(&mut out, "    Signal(SignalKind),");
1713    }
1714    pushln!(&mut out, "}}");
1715    pushln!(
1716        &mut out,
1717        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1718    );
1719    pushln!(&mut out, "pub enum TransitionRefusal {{");
1720    pushln!(
1721        &mut out,
1722        "    NoMatchingTransition {{ phase: Phase, trigger: TriggerDiscriminant }},"
1723    );
1724    pushln!(
1725        &mut out,
1726        "    GuardRejected {{ rejections: Vec<GuardRejection> }},"
1727    );
1728    pushln!(
1729        &mut out,
1730        "    AmbiguousTransition {{ transitions: Vec<TransitionId> }},"
1731    );
1732    pushln!(&mut out, "}}");
1733    pushln!(
1734        &mut out,
1735        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1736    );
1737    pushln!(&mut out, "pub enum KernelError {{");
1738    pushln!(
1739        &mut out,
1740        "    ContextViolation {{ transition_id: TransitionId, detail: String }},"
1741    );
1742    pushln!(
1743        &mut out,
1744        "    HelperEvaluation {{ helper_id: HelperId, detail: String }},"
1745    );
1746    pushln!(&mut out, "    CodegenInvariant {{ detail: String }},");
1747    pushln!(&mut out, "}}");
1748    pushln!(
1749        &mut out,
1750        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1751    );
1752    pushln!(&mut out, "pub enum TransitionError {{");
1753    pushln!(&mut out, "    Refusal(TransitionRefusal),");
1754    pushln!(&mut out, "    Kernel(KernelError),");
1755    pushln!(&mut out, "}}");
1756    pushln!(
1757        &mut out,
1758        "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
1759    );
1760    pushln!(&mut out, "pub struct Outcome {{");
1761    pushln!(&mut out, "    pub transition_id: TransitionId,");
1762    pushln!(&mut out, "    pub next_state: State,");
1763    pushln!(&mut out, "    pub effects: Vec<Effect>,");
1764    pushln!(&mut out, "}}");
1765    pushln!(&mut out);
1766    pushln!(&mut out, "pub mod helpers {{");
1767    pushln!(&mut out, "    #[allow(unused_imports)]");
1768    pushln!(&mut out, "    use super::*;");
1769    pushln!(
1770        &mut out,
1771        "    pub fn none<C: Context>(_: &State, context: &C) -> Result<(), KernelError> {{"
1772    );
1773    pushln!(&mut out, "        let _ = context;");
1774    pushln!(&mut out, "        Ok(())");
1775    pushln!(&mut out, "    }}");
1776    pushln!(&mut out, "}}");
1777    pushln!(&mut out);
1778
1779    let init_phase = rust_ident(schema.state.init.phase.as_str());
1780    pushln!(&mut out, "pub fn initial_state() -> State {{");
1781    pushln!(&mut out, "    State {{");
1782    pushln!(&mut out, "        phase: Phase::{init_phase},");
1783    for field in &schema.state.fields {
1784        let init_expr = schema
1785            .state
1786            .init
1787            .fields
1788            .iter()
1789            .find(|item| item.field == field.name)
1790            .map(|item| rust_initial_value_expr(&item.expr, &field.ty))
1791            .unwrap_or_else(|| direct_default_value_expr(&field.ty));
1792        pushln!(
1793            &mut out,
1794            "        {}: {},",
1795            rust_field_ident(&field.name),
1796            init_expr
1797        );
1798    }
1799    pushln!(&mut out, "    }}");
1800    pushln!(&mut out, "}}");
1801    Ok(out)
1802}
1803
1804#[cfg(not(test))]
1805fn render_command_capability_section(out: &mut String, schema: &MachineSchema) {
1806    if schema.command_plans.is_empty() {
1807        return;
1808    }
1809
1810    pushln!(out, "pub mod command_capabilities {{");
1811    pushln!(out, "    mod private {{");
1812    pushln!(out, "        #[derive(Debug, PartialEq, Eq)]");
1813    pushln!(out, "        pub struct Sealed;");
1814    pushln!(out, "    }}");
1815    pushln!(out);
1816
1817    pushln!(out, "    #[derive(Debug, Clone, Copy, PartialEq, Eq)]");
1818    pushln!(out, "    pub enum CommandPlanKind {{");
1819    for plan in &schema.command_plans {
1820        pushln!(out, "        {},", rust_ident(&plan.name));
1821    }
1822    pushln!(out, "    }}");
1823    pushln!(out);
1824    pushln!(out, "    impl CommandPlanKind {{");
1825    pushln!(out, "        #[must_use]");
1826    pushln!(out, "        pub const fn as_str(self) -> &'static str {{");
1827    pushln!(out, "            match self {{");
1828    for plan in &schema.command_plans {
1829        pushln!(
1830            out,
1831            "                Self::{} => {:?},",
1832            rust_ident(&plan.name),
1833            plan.name
1834        );
1835    }
1836    pushln!(out, "            }}");
1837    pushln!(out, "        }}");
1838    pushln!(out, "    }}");
1839    pushln!(out);
1840
1841    if schema
1842        .command_plans
1843        .iter()
1844        .any(|plan| plan.authority_type == "AuthorizedRuntimeLoopBatch")
1845    {
1846        pushln!(out, "    #[derive(Debug, Clone, Copy, PartialEq, Eq)]");
1847        pushln!(out, "    pub enum RuntimeLoopBatchSource {{");
1848        pushln!(out, "        Queue,");
1849        pushln!(out, "        Steer,");
1850        pushln!(out, "    }}");
1851        pushln!(out);
1852        pushln!(
1853            out,
1854            "    /// The most inputs one runtime-loop batch stages into a run: the bound of"
1855        );
1856        pushln!(
1857            out,
1858            "    /// the one terminal-completion batch a run's commit names."
1859        );
1860        pushln!(
1861            out,
1862            "    pub const RUNTIME_LOOP_BATCH_MAX_INPUTS: usize = {};",
1863            meerkat_machine_schema::catalog::dsl::meerkat_machine::command_capabilities::RUNTIME_LOOP_BATCH_MAX_INPUTS
1864        );
1865        pushln!(out);
1866        pushln!(
1867            out,
1868            "    #[must_use = \"generated runtime-loop batch plan must be consumed by exact dequeue/stage realization\"]"
1869        );
1870        pushln!(out, "    #[derive(Debug, PartialEq, Eq)]");
1871        pushln!(out, "    pub struct RuntimeLoopBatchPlan {{");
1872        pushln!(out, "        batch_capability: AuthorizedRuntimeLoopBatch,");
1873        pushln!(out, "        input_ids: Vec<String>,");
1874        pushln!(out, "        source: RuntimeLoopBatchSource,");
1875        pushln!(out, "    }}");
1876        pushln!(out);
1877        pushln!(
1878            out,
1879            "    #[must_use = \"generated stage-for-run plan must be consumed by exact stage realization\"]"
1880        );
1881        pushln!(out, "    #[derive(Debug, PartialEq, Eq)]");
1882        pushln!(out, "    pub struct StageForRunPlan {{");
1883        pushln!(out, "        stage_capability: AuthorizedStageForRun,");
1884        pushln!(out, "        input_ids: Vec<String>,");
1885        pushln!(out, "        source: RuntimeLoopBatchSource,");
1886        pushln!(out, "    }}");
1887        pushln!(out);
1888        pushln!(out, "    impl RuntimeLoopBatchPlan {{");
1889        pushln!(out, "        #[must_use]");
1890        pushln!(out, "        pub fn input_ids(&self) -> &[String] {{");
1891        pushln!(out, "            &self.input_ids");
1892        pushln!(out, "        }}");
1893        pushln!(out);
1894        pushln!(out, "        #[must_use]");
1895        pushln!(
1896            out,
1897            "        pub const fn source(&self) -> RuntimeLoopBatchSource {{"
1898        );
1899        pushln!(out, "            self.source");
1900        pushln!(out, "        }}");
1901        pushln!(out);
1902        pushln!(
1903            out,
1904            "        pub fn into_parts(self) -> (AuthorizedRuntimeLoopBatch, Vec<String>, RuntimeLoopBatchSource) {{"
1905        );
1906        pushln!(
1907            out,
1908            "            (self.batch_capability, self.input_ids, self.source)"
1909        );
1910        pushln!(out, "        }}");
1911        pushln!(out, "    }}");
1912        pushln!(out);
1913        pushln!(out, "    impl StageForRunPlan {{");
1914        pushln!(out, "        #[must_use]");
1915        pushln!(out, "        pub fn input_ids(&self) -> &[String] {{");
1916        pushln!(out, "            &self.input_ids");
1917        pushln!(out, "        }}");
1918        pushln!(out);
1919        pushln!(out, "        #[must_use]");
1920        pushln!(
1921            out,
1922            "        pub const fn source(&self) -> RuntimeLoopBatchSource {{"
1923        );
1924        pushln!(out, "            self.source");
1925        pushln!(out, "        }}");
1926        pushln!(out);
1927        pushln!(
1928            out,
1929            "        pub fn into_parts(self) -> (AuthorizedStageForRun, Vec<String>, RuntimeLoopBatchSource) {{"
1930        );
1931        pushln!(
1932            out,
1933            "            (self.stage_capability, self.input_ids, self.source)"
1934        );
1935        pushln!(out, "        }}");
1936        pushln!(out, "    }}");
1937        pushln!(out);
1938    }
1939
1940    for plan in &schema.command_plans {
1941        let type_name = rust_ident(&plan.authority_type);
1942        let kind_name = rust_ident(&plan.name);
1943        pushln!(
1944            out,
1945            "    #[must_use = {:?}]",
1946            format!(
1947                "generated command capability `{}` must be consumed by the shell action it authorizes",
1948                plan.authority_type
1949            )
1950        );
1951        pushln!(out, "    #[derive(Debug, PartialEq, Eq)]");
1952        pushln!(out, "    pub struct {type_name} {{");
1953        pushln!(out, "        _sealed: private::Sealed,");
1954        pushln!(out, "    }}");
1955        pushln!(out);
1956        pushln!(out, "    impl {type_name} {{");
1957        pushln!(out, "        #[doc(hidden)]");
1958        pushln!(out, "        #[allow(dead_code)]");
1959        pushln!(
1960            out,
1961            "        pub(crate) fn mint_from_generated_command_plan() -> Self {{"
1962        );
1963        pushln!(out, "            Self {{ _sealed: private::Sealed }}");
1964        pushln!(out, "        }}");
1965        pushln!(out);
1966        pushln!(out, "        #[must_use]");
1967        pushln!(
1968            out,
1969            "        pub const fn plan(&self) -> CommandPlanKind {{"
1970        );
1971        pushln!(out, "            CommandPlanKind::{kind_name}");
1972        pushln!(out, "        }}");
1973        pushln!(out, "    }}");
1974        pushln!(out);
1975    }
1976
1977    if schema
1978        .command_plans
1979        .iter()
1980        .any(|plan| plan.authority_type == "AuthorizedRuntimeLoopBatch")
1981    {
1982        pushln!(out, "    impl AuthorizedRuntimeLoopBatch {{");
1983        pushln!(out, "        #[must_use]");
1984        pushln!(
1985            out,
1986            "        pub fn authorize_runtime_loop_batch_from_state(state: &super::State) -> Option<RuntimeLoopBatchPlan> {{"
1987        );
1988        pushln!(
1989            out,
1990            "            runtime_loop_batch_from_state(state, super::InputLane::Steer, RuntimeLoopBatchSource::Steer)"
1991        );
1992        pushln!(
1993            out,
1994            "                .or_else(|| runtime_loop_batch_from_state(state, super::InputLane::Queue, RuntimeLoopBatchSource::Queue))"
1995        );
1996        pushln!(out, "        }}");
1997        pushln!(out, "    }}");
1998        pushln!(out);
1999        pushln!(out, "    impl AuthorizedStageForRun {{");
2000        pushln!(out, "        #[must_use]");
2001        pushln!(
2002            out,
2003            "        pub fn authorize_stage_for_run_from_state(state: &super::State, input_ids: &[String], run_id: &super::RunId, source: RuntimeLoopBatchSource) -> Option<StageForRunPlan> {{"
2004        );
2005        pushln!(
2006            out,
2007            "            runtime_stage_for_run_from_state(state, input_ids, run_id, source)"
2008        );
2009        pushln!(out, "        }}");
2010        pushln!(out, "    }}");
2011        pushln!(out);
2012        pushln!(out, "    fn runtime_loop_batch_from_state(");
2013        pushln!(out, "        state: &super::State,");
2014        pushln!(out, "        lane: super::InputLane,");
2015        pushln!(out, "        source: RuntimeLoopBatchSource,");
2016        pushln!(out, "    ) -> Option<RuntimeLoopBatchPlan> {{");
2017        pushln!(
2018            out,
2019            "        // A kept governed input held for its controller is never selected: later work of its lane goes first."
2020        );
2021        pushln!(
2022            out,
2023            "        let ordered: Vec<String> = ordered_queued_lane_inputs(state, lane)?.into_iter().filter(|input_id| !state.input_controller_holds.contains(input_id)).collect();"
2024        );
2025        pushln!(out, "        let first = ordered.first()?;");
2026        pushln!(
2027            out,
2028            "        // AppendContentAndRun owns exactly one SystemNotice per run."
2029        );
2030        pushln!(
2031            out,
2032            "        let selected = if state.input_runtime_peer_response_terminal_apply_intent.get(first) == Some(&super::RecoveredPeerResponseTerminalApplyIntent::AppendContentAndRun) {{"
2033        );
2034        pushln!(out, "            vec![first.clone()]");
2035        pushln!(out, "        }} else {{");
2036        pushln!(out, "            match source {{");
2037        pushln!(
2038            out,
2039            "                RuntimeLoopBatchSource::Steer => select_steer_batch(state, &ordered, first),"
2040        );
2041        pushln!(
2042            out,
2043            "                RuntimeLoopBatchSource::Queue => select_queue_batch(state, &ordered, first),"
2044        );
2045        pushln!(out, "            }}");
2046        pushln!(out, "        }};");
2047        pushln!(out, "        if selected.is_empty() {{");
2048        pushln!(out, "            None");
2049        pushln!(out, "        }} else {{");
2050        pushln!(out, "            Some(RuntimeLoopBatchPlan {{");
2051        pushln!(
2052            out,
2053            "                batch_capability: AuthorizedRuntimeLoopBatch::mint_from_generated_command_plan(),"
2054        );
2055        pushln!(out, "                input_ids: selected,");
2056        pushln!(out, "                source,");
2057        pushln!(out, "            }})");
2058        pushln!(out, "        }}");
2059        pushln!(out, "    }}");
2060        pushln!(out);
2061        pushln!(out, "    fn runtime_stage_for_run_from_state(");
2062        pushln!(out, "        state: &super::State,");
2063        pushln!(out, "        input_ids: &[String],");
2064        pushln!(out, "        run_id: &super::RunId,");
2065        pushln!(out, "        source: RuntimeLoopBatchSource,");
2066        pushln!(out, "    ) -> Option<StageForRunPlan> {{");
2067        pushln!(out, "        if input_ids.is_empty() {{");
2068        pushln!(out, "            return None;");
2069        pushln!(out, "        }}");
2070        pushln!(
2071            out,
2072            "        // A separately requested stage must preserve terminal-response cardinality."
2073        );
2074        pushln!(
2075            out,
2076            "        if input_ids.len() > 1 && input_ids.iter().any(|input_id| state.input_runtime_peer_response_terminal_apply_intent.get(input_id) == Some(&super::RecoveredPeerResponseTerminalApplyIntent::AppendContentAndRun)) {{"
2077        );
2078        pushln!(out, "            return None;");
2079        pushln!(out, "        }}");
2080        pushln!(
2081            out,
2082            "        if state.current_run_id.as_ref() != Some(run_id) {{"
2083        );
2084        pushln!(out, "            return None;");
2085        pushln!(out, "        }}");
2086        pushln!(out, "        let expected_lane = match source {{");
2087        pushln!(
2088            out,
2089            "            RuntimeLoopBatchSource::Queue => super::InputLane::Queue,"
2090        );
2091        pushln!(
2092            out,
2093            "            RuntimeLoopBatchSource::Steer => super::InputLane::Steer,"
2094        );
2095        pushln!(out, "        }};");
2096        pushln!(out, "        for input_id in input_ids {{");
2097        pushln!(
2098            out,
2099            "            if state.input_phases.get(input_id) != Some(&super::InputPhase::Queued) {{"
2100        );
2101        pushln!(out, "                return None;");
2102        pushln!(out, "            }}");
2103        pushln!(
2104            out,
2105            "            if state.input_lane.get(input_id) != Some(&expected_lane) {{"
2106        );
2107        pushln!(out, "                return None;");
2108        pushln!(out, "            }}");
2109        pushln!(
2110            out,
2111            "            if !state.input_admission_seq.contains_key(input_id) {{"
2112        );
2113        pushln!(out, "                return None;");
2114        pushln!(out, "            }}");
2115        pushln!(
2116            out,
2117            "            if !state.input_recovery_lanes.contains_key(input_id) {{"
2118        );
2119        pushln!(out, "                return None;");
2120        pushln!(out, "            }}");
2121        pushln!(
2122            out,
2123            "            if state.input_run_associations.contains_key(input_id) {{"
2124        );
2125        pushln!(out, "                return None;");
2126        pushln!(out, "            }}");
2127        pushln!(
2128            out,
2129            "            // Mirrors the StageForRun `input_controller_not_held` guard."
2130        );
2131        pushln!(
2132            out,
2133            "            if state.input_controller_holds.contains(input_id) {{"
2134        );
2135        pushln!(out, "                return None;");
2136        pushln!(out, "            }}");
2137        pushln!(out, "        }}");
2138        pushln!(out, "        Some(StageForRunPlan {{");
2139        pushln!(
2140            out,
2141            "            stage_capability: AuthorizedStageForRun::mint_from_generated_command_plan(),"
2142        );
2143        pushln!(out, "            input_ids: input_ids.to_vec(),");
2144        pushln!(out, "            source,");
2145        pushln!(out, "        }})");
2146        pushln!(out, "    }}");
2147        pushln!(out);
2148        pushln!(out, "    fn ordered_queued_lane_inputs(");
2149        pushln!(out, "        state: &super::State,");
2150        pushln!(out, "        lane: super::InputLane,");
2151        pushln!(out, "    ) -> Option<Vec<String>> {{");
2152        pushln!(out, "        let mut ordered = Vec::new();");
2153        pushln!(
2154            out,
2155            "        for (input_id, input_lane) in &state.input_lane {{"
2156        );
2157        pushln!(out, "            if *input_lane != lane {{");
2158        pushln!(out, "                continue;");
2159        pushln!(out, "            }}");
2160        pushln!(
2161            out,
2162            "            if state.input_phases.get(input_id) != Some(&super::InputPhase::Queued) {{"
2163        );
2164        pushln!(out, "                return None;");
2165        pushln!(out, "            }}");
2166        pushln!(
2167            out,
2168            "            let sequence = *state.input_admission_seq.get(input_id)?;"
2169        );
2170        pushln!(
2171            out,
2172            "            ordered.push((sequence, input_id.clone()));"
2173        );
2174        pushln!(out, "        }}");
2175        pushln!(
2176            out,
2177            "        ordered.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));"
2178        );
2179        pushln!(
2180            out,
2181            "        Some(ordered.into_iter().map(|(_, input_id)| input_id).collect())"
2182        );
2183        pushln!(out, "    }}");
2184        pushln!(out);
2185        pushln!(out, "    fn select_steer_batch(");
2186        pushln!(out, "        state: &super::State,");
2187        pushln!(out, "        ordered: &[String],");
2188        pushln!(out, "        first: &String,");
2189        pushln!(out, "    ) -> Vec<String> {{");
2190        pushln!(
2191            out,
2192            "        let Some(target_boundary) = state.input_runtime_boundary.get(first).copied() else {{"
2193        );
2194        pushln!(out, "            return vec![first.clone()];");
2195        pushln!(out, "        }};");
2196        pushln!(
2197            out,
2198            "        let Some(target_execution_kind) = state.input_runtime_execution_kind.get(first).copied() else {{"
2199        );
2200        pushln!(out, "            return vec![first.clone()];");
2201        pushln!(out, "        }};");
2202        pushln!(out, "        let target_terminal_intent = state");
2203        pushln!(
2204            out,
2205            "            .input_runtime_peer_response_terminal_apply_intent"
2206        );
2207        pushln!(out, "            .get(first)");
2208        pushln!(out, "            .copied();");
2209        pushln!(out, "        ordered");
2210        pushln!(out, "            .iter()");
2211        pushln!(out, "            .take_while(|input_id| {{");
2212        pushln!(
2213            out,
2214            "                state.input_runtime_boundary.get(*input_id).copied() == Some(target_boundary)"
2215        );
2216        pushln!(
2217            out,
2218            "                    && state.input_runtime_execution_kind.get(*input_id).copied()"
2219        );
2220        pushln!(
2221            out,
2222            "                        == Some(target_execution_kind)"
2223        );
2224        pushln!(out, "                    && state");
2225        pushln!(
2226            out,
2227            "                        .input_runtime_peer_response_terminal_apply_intent"
2228        );
2229        pushln!(out, "                        .get(*input_id)");
2230        pushln!(out, "                        .copied()");
2231        pushln!(out, "                        == target_terminal_intent");
2232        pushln!(out, "            }})");
2233        pushln!(out, "            .take(RUNTIME_LOOP_BATCH_MAX_INPUTS)");
2234        pushln!(out, "            .cloned()");
2235        pushln!(out, "            .collect()");
2236        pushln!(out, "    }}");
2237        pushln!(out);
2238        pushln!(out, "    fn select_queue_batch(");
2239        pushln!(out, "        state: &super::State,");
2240        pushln!(out, "        ordered: &[String],");
2241        pushln!(out, "        first: &String,");
2242        pushln!(out, "    ) -> Vec<String> {{");
2243        pushln!(
2244            out,
2245            "        let Some(target_execution_kind) = state.input_runtime_execution_kind.get(first).copied() else {{"
2246        );
2247        pushln!(out, "            return vec![first.clone()];");
2248        pushln!(out, "        }};");
2249        pushln!(out, "        let target_terminal_intent = state");
2250        pushln!(
2251            out,
2252            "            .input_runtime_peer_response_terminal_apply_intent"
2253        );
2254        pushln!(out, "            .get(first)");
2255        pushln!(out, "            .copied();");
2256        pushln!(
2257            out,
2258            "        let Some(driver_is_prompt) = state.input_is_prompt.get(first).copied() else {{"
2259        );
2260        pushln!(out, "            return vec![first.clone()];");
2261        pushln!(out, "        }};");
2262        pushln!(out, "        let mut selected = Vec::new();");
2263        pushln!(out, "        for input_id in ordered {{");
2264        pushln!(
2265            out,
2266            "            if selected.len() == RUNTIME_LOOP_BATCH_MAX_INPUTS {{"
2267        );
2268        pushln!(out, "                break;");
2269        pushln!(out, "            }}");
2270        pushln!(
2271            out,
2272            "            if state.input_runtime_execution_kind.get(input_id).copied()"
2273        );
2274        pushln!(out, "                != Some(target_execution_kind)");
2275        pushln!(out, "                || state");
2276        pushln!(
2277            out,
2278            "                    .input_runtime_peer_response_terminal_apply_intent"
2279        );
2280        pushln!(out, "                    .get(input_id)");
2281        pushln!(out, "                    .copied()");
2282        pushln!(out, "                    != target_terminal_intent");
2283        pushln!(out, "            {{");
2284        pushln!(out, "                break;");
2285        pushln!(out, "            }}");
2286        pushln!(
2287            out,
2288            "            let Some(is_prompt) = state.input_is_prompt.get(input_id).copied() else {{"
2289        );
2290        pushln!(out, "                break;");
2291        pushln!(out, "            }};");
2292        pushln!(out, "            if !driver_is_prompt && is_prompt {{");
2293        pushln!(out, "                break;");
2294        pushln!(out, "            }}");
2295        pushln!(out, "            selected.push(input_id.clone());");
2296        pushln!(out, "            if is_prompt || driver_is_prompt {{");
2297        pushln!(out, "                break;");
2298        pushln!(out, "            }}");
2299        pushln!(out, "        }}");
2300        pushln!(out, "        selected");
2301        pushln!(out, "    }}");
2302        pushln!(out);
2303    }
2304    pushln!(out, "}}");
2305    pushln!(out);
2306}
2307
2308#[cfg(not(test))]
2309fn direct_default_value_expr(ty: &TypeRef) -> String {
2310    match ty {
2311        TypeRef::Bool => "false".to_string(),
2312        TypeRef::U32 | TypeRef::U64 => "0".to_string(),
2313        TypeRef::String => "String::new()".to_string(),
2314        TypeRef::Named(name) => format!("{}::default()", rust_ident(name.as_str())),
2315        TypeRef::Enum(name) => format!("{}::default()", rust_ident(name.as_str())),
2316        TypeRef::Option(_) => "None".to_string(),
2317        TypeRef::Set(_) => "Default::default()".to_string(),
2318        TypeRef::Seq(_) => "Vec::new()".to_string(),
2319        TypeRef::Map(_, _) => "Default::default()".to_string(),
2320    }
2321}
2322
2323#[cfg(not(test))]
2324fn rust_initial_value_expr(expr: &Expr, ty: &TypeRef) -> String {
2325    match expr {
2326        Expr::Bool(value) => value.to_string(),
2327        Expr::U64(value) => value.to_string(),
2328        Expr::U64Max => "u64::MAX".to_string(),
2329        Expr::String(value) => match ty {
2330            TypeRef::Named(name) => {
2331                format!("{}({value:?}.to_string())", rust_ident(name.as_str()))
2332            }
2333            _ => format!("{value:?}.to_string()"),
2334        },
2335        Expr::NamedVariant { enum_name, variant } => {
2336            format!(
2337                "{}::{}",
2338                rust_ident(enum_name.as_str()),
2339                rust_ident(variant.as_str())
2340            )
2341        }
2342        Expr::EmptySet | Expr::EmptyMap => direct_default_value_expr(ty),
2343        Expr::SeqLiteral(items) => {
2344            let inner = match ty {
2345                TypeRef::Seq(inner) => inner.as_ref(),
2346                other => other,
2347            };
2348            format!(
2349                "vec![{}]",
2350                items
2351                    .iter()
2352                    .map(|item| rust_initial_value_expr(item, inner))
2353                    .collect::<Vec<_>>()
2354                    .join(", ")
2355            )
2356        }
2357        Expr::None => "None".to_string(),
2358        Expr::Some(inner) => {
2359            let inner_ty = match ty {
2360                TypeRef::Option(inner_ty) => inner_ty.as_ref(),
2361                other => other,
2362            };
2363            format!("Some({})", rust_initial_value_expr(inner, inner_ty))
2364        }
2365        Expr::Phase(value) => format!("Phase::{}", rust_ident(value.as_str())),
2366        other => {
2367            let message =
2368                format!("unsupported generated kernel state initializer expression: {other:?}");
2369            format!("{{ compile_error!({message:?}); Default::default() }}")
2370        }
2371    }
2372}
2373
2374#[cfg(not(test))]
2375pub fn render_generated_kernel_mod(schemas: &[MachineSchema]) -> String {
2376    let mut out = String::new();
2377    pushln!(
2378        &mut out,
2379        "// @generated — Generated by `cargo xtask machine-codegen --all`."
2380    );
2381    let mut module_slugs: Vec<_> = schemas
2382        .iter()
2383        .map(|schema| machine_slug(&schema.machine))
2384        .collect();
2385    module_slugs.sort();
2386    for slug in module_slugs {
2387        pushln!(&mut out, "pub mod {slug};");
2388    }
2389    out
2390}
2391
2392#[cfg(not(test))]
2393fn render_semantic_mapping_section(
2394    out: &mut String,
2395    heading: &str,
2396    entries: &[SemanticCoverageEntry],
2397) {
2398    pushln!(out, "### {heading}");
2399    if entries.is_empty() {
2400        pushln!(out, "- `(none)`");
2401        out.push('\n');
2402        return;
2403    }
2404
2405    for entry in entries {
2406        pushln!(out, "- `{}`", entry.name);
2407        pushln!(
2408            out,
2409            "  - anchors: {}",
2410            render_semantic_id_list(&entry.anchor_ids)
2411        );
2412        pushln!(
2413            out,
2414            "  - scenarios: {}",
2415            render_semantic_id_list(&entry.scenario_ids)
2416        );
2417    }
2418    out.push('\n');
2419}
2420
2421/// Render a semantic id list; an empty list is an honest UNCLAIMED verdict
2422/// under full-containment matching, not a rendering omission.
2423#[cfg(not(test))]
2424fn render_semantic_id_list(ids: &[String]) -> String {
2425    if ids.is_empty() {
2426        return "(unclaimed)".to_owned();
2427    }
2428    ids.iter()
2429        .map(|id| format!("`{id}`"))
2430        .collect::<Vec<_>>()
2431        .join(", ")
2432}
2433
2434#[cfg(not(test))]
2435fn machine_slug(machine_name: impl AsRef<str>) -> String {
2436    let machine_name = machine_name.as_ref();
2437    let trimmed = machine_name.strip_suffix("Machine").unwrap_or(machine_name);
2438    to_snake_case(trimmed)
2439}
2440
2441#[cfg(not(test))]
2442fn to_snake_case(value: &str) -> String {
2443    let mut out = String::new();
2444    let mut previous_is_sep = true;
2445
2446    for ch in value.chars() {
2447        if ch == '_' || ch == '-' || ch == ' ' {
2448            if !previous_is_sep {
2449                out.push('_');
2450                previous_is_sep = true;
2451            }
2452            continue;
2453        }
2454
2455        if ch.is_ascii_uppercase() {
2456            if !out.is_empty() && !previous_is_sep {
2457                out.push('_');
2458            }
2459            out.push(ch.to_ascii_lowercase());
2460            previous_is_sep = false;
2461        } else {
2462            out.push(ch.to_ascii_lowercase());
2463            previous_is_sep = false;
2464        }
2465    }
2466
2467    out.trim_matches('_').to_owned()
2468}
2469
2470#[cfg(not(test))]
2471pub fn merge_mapping_document(existing: Option<&str>, title: &str, generated: &str) -> String {
2472    let generated_block =
2473        format!("{GENERATED_COVERAGE_START}\n{generated}\n{GENERATED_COVERAGE_END}\n");
2474
2475    if let Some(existing) = existing {
2476        if let Some(start) = existing.find(GENERATED_COVERAGE_START) {
2477            if let Some(end) = existing.find(GENERATED_COVERAGE_END) {
2478                let end_idx = end + GENERATED_COVERAGE_END.len();
2479                let before = existing[..start].trim_end();
2480                let after = existing[end_idx..].trim_start();
2481                return if after.is_empty() {
2482                    format!("{before}\n\n{generated_block}")
2483                } else {
2484                    format!("{before}\n\n{generated_block}\n{after}")
2485                };
2486            }
2487        }
2488
2489        let trimmed = existing.trim_end();
2490        if trimmed.is_empty() {
2491            return generated_block;
2492        }
2493        return format!("{trimmed}\n\n{generated_block}");
2494    }
2495
2496    format!("# {title} Mapping Note\n\n{generated_block}")
2497}
2498
2499fn render_enum_section(out: &mut String, label: &str, schema: &EnumSchema) {
2500    pushln!(out, "{label}");
2501    pushln!(
2502        out,
2503        "  {} = {}",
2504        schema.name,
2505        render_enum_variants_inline(schema)
2506    );
2507    for variant in &schema.variants {
2508        pushln!(
2509            out,
2510            "  {} == {}",
2511            variant.name,
2512            render_variant_fields(variant)
2513        );
2514    }
2515    out.push('\n');
2516}
2517
2518fn render_helpers_section(out: &mut String, label: &str, helpers: &[HelperSchema]) {
2519    if helpers.is_empty() {
2520        return;
2521    }
2522    pushln!(out, "{label}");
2523    for helper in helpers {
2524        pushln!(
2525            out,
2526            "  {}({}) : {}",
2527            helper.name,
2528            render_fields(&helper.params),
2529            render_type_ref(&helper.returns)
2530        );
2531        pushln!(out, "    == {}", render_expr(&helper.body));
2532    }
2533    out.push('\n');
2534}
2535
2536fn render_invariants_section(out: &mut String, schema: &MachineSchema) {
2537    pushln!(out, "INVARIANTS");
2538    for invariant in &schema.invariants {
2539        pushln!(
2540            out,
2541            "  {} == {}",
2542            invariant.name,
2543            render_expr(&invariant.expr)
2544        );
2545    }
2546    out.push('\n');
2547}
2548
2549fn render_transitions_section(out: &mut String, schema: &MachineSchema) {
2550    pushln!(out, "TRANSITIONS");
2551    for transition in &schema.transitions {
2552        render_transition(out, transition);
2553    }
2554    out.push('\n');
2555}
2556
2557fn render_transition(out: &mut String, transition: &TransitionSchema) {
2558    pushln!(out, "  {}", transition.name);
2559    pushln!(out, "    from = {}", render_string_list(&transition.from));
2560    pushln!(
2561        out,
2562        "    on = {}({})",
2563        transition.on.variant_str(),
2564        transition
2565            .on
2566            .bindings()
2567            .iter()
2568            .map(meerkat_machine_schema::identity::FieldId::as_str)
2569            .collect::<Vec<_>>()
2570            .join(", ")
2571    );
2572    if !transition.guards.is_empty() {
2573        pushln!(out, "    guards =");
2574        for guard in &transition.guards {
2575            render_guard(out, guard);
2576        }
2577    }
2578    if !transition.updates.is_empty() {
2579        pushln!(out, "    updates =");
2580        for update in &transition.updates {
2581            pushln!(out, "      - {}", render_update(update));
2582        }
2583    }
2584    pushln!(out, "    to = {}", tla_string(&transition.to));
2585    if !transition.emit.is_empty() {
2586        pushln!(out, "    emit =");
2587        for effect in &transition.emit {
2588            pushln!(out, "      - {}", render_effect_emit(effect));
2589        }
2590    }
2591}
2592
2593fn render_guard(out: &mut String, guard: &Guard) {
2594    pushln!(
2595        out,
2596        "      - {} == {}",
2597        guard.name,
2598        render_expr(&guard.expr)
2599    );
2600}
2601
2602fn render_field_init(out: &mut String, field: &FieldInit) {
2603    pushln!(out, "  {} = {}", field.field, render_expr(&field.expr));
2604}
2605
2606fn render_variant_fields(variant: &VariantSchema) -> String {
2607    if variant.fields.is_empty() {
2608        "[]".to_owned()
2609    } else {
2610        format!("[{}]", render_fields(&variant.fields))
2611    }
2612}
2613
2614fn render_fields(fields: &[FieldSchema]) -> String {
2615    fields
2616        .iter()
2617        .map(|field| format!("{}: {}", field.name, render_type_ref(&field.ty)))
2618        .collect::<Vec<_>>()
2619        .join(", ")
2620}
2621
2622fn render_update(update: &Update) -> String {
2623    match update {
2624        Update::Assign { field, expr } => format!("{field}' = {}", render_expr(expr)),
2625        Update::Increment { field, amount } => format!("{field}' = {field} + {amount}"),
2626        Update::Decrement { field, amount } => format!("{field}' = {field} - {amount}"),
2627        Update::MapInsert { field, key, value } => {
2628            format!(
2629                "{field}' = [ {field} EXCEPT ![{}] = {} ]",
2630                render_expr(key),
2631                render_expr(value)
2632            )
2633        }
2634        Update::MapRemove { field, key } => {
2635            format!("{field}' = MapRemove({field}, {})", render_expr(key))
2636        }
2637        Update::MapIncrement { field, key, amount } => {
2638            format!(
2639                "{field}' = [ {field} EXCEPT ![{}] = @ + {amount} ]",
2640                render_expr(key)
2641            )
2642        }
2643        Update::MapDecrement { field, key, amount } => {
2644            format!(
2645                "{field}' = [ {field} EXCEPT ![{}] = @ - {amount} ]",
2646                render_expr(key)
2647            )
2648        }
2649        Update::SetInsert { field, value } => {
2650            format!("{field}' = {field} \\cup {{ {} }}", render_expr(value))
2651        }
2652        Update::SetRemove { field, value } => {
2653            format!("{field}' = {field} \\ {{ {} }}", render_expr(value))
2654        }
2655        Update::SeqAppend { field, value } => {
2656            format!("{field}' = Append({field}, {})", render_expr(value))
2657        }
2658        Update::SeqPrepend { field, values } => {
2659            format!("{field}' = {} \\o {field}", render_expr(values))
2660        }
2661        Update::SeqPopFront { field } => {
2662            format!("{field}' = Tail({field})")
2663        }
2664        Update::SeqRemoveValue { field, value } => {
2665            format!("{field}' = SeqRemove({field}, {})", render_expr(value))
2666        }
2667        Update::SeqRemoveAll { field, values } => {
2668            format!("{field}' = SeqRemoveAll({field}, {})", render_expr(values))
2669        }
2670        Update::ForEach {
2671            binding,
2672            over,
2673            updates,
2674        } => {
2675            let body = updates
2676                .iter()
2677                .map(render_update)
2678                .collect::<Vec<_>>()
2679                .join("; ");
2680            format!("ForEach({binding} \\in {}) {{ {body} }}", render_expr(over))
2681        }
2682        Update::Conditional {
2683            condition,
2684            then_updates,
2685            else_updates,
2686        } => {
2687            let then_body = then_updates
2688                .iter()
2689                .map(render_update)
2690                .collect::<Vec<_>>()
2691                .join("; ");
2692            let else_body = else_updates
2693                .iter()
2694                .map(render_update)
2695                .collect::<Vec<_>>()
2696                .join("; ");
2697            format!(
2698                "If ({}) {{ {} }} Else {{ {} }}",
2699                render_expr(condition),
2700                then_body,
2701                else_body
2702            )
2703        }
2704    }
2705}
2706
2707fn render_effect_emit(effect: &EffectEmit) -> String {
2708    if effect.fields.is_empty() {
2709        effect.variant.as_str().to_owned()
2710    } else {
2711        let fields = effect
2712            .fields
2713            .iter()
2714            .map(|(name, expr)| format!("{name} |-> {}", render_expr(expr)))
2715            .collect::<Vec<_>>()
2716            .join(", ");
2717        format!("{}([{}])", effect.variant, fields)
2718    }
2719}
2720
2721/// Test hook for the expression renderer (#1811 map-literal rendering).
2722#[cfg(test)]
2723pub(crate) fn render_expr_for_tests(expr: &Expr) -> String {
2724    render_expr(expr)
2725}
2726
2727fn render_expr(expr: &Expr) -> String {
2728    match expr {
2729        Expr::Bool(value) => value.to_string().to_uppercase(),
2730        Expr::U64(value) => value.to_string(),
2731        Expr::U64Max => "u64::MAX".to_string(),
2732        Expr::String(value) => tla_string(value),
2733        Expr::NamedVariant { enum_name, variant } => tla_string(known_enum_variant_wire_label(
2734            enum_name.as_str(),
2735            variant.as_str(),
2736        )),
2737        Expr::FieldAccess { base, field } => {
2738            format!("{}.{}", render_expr(base), field.as_str())
2739        }
2740        Expr::EnumVariantIs { value, variant, .. } => {
2741            format!(
2742                "{}.tag = {}",
2743                render_expr(value),
2744                tla_string(variant.as_str())
2745            )
2746        }
2747        Expr::EnumStringSetPayload {
2748            value,
2749            variant,
2750            field,
2751            ..
2752        } => format!(
2753            "IF {}.tag = {} THEN {}.{} ELSE {{}}",
2754            render_expr(value),
2755            tla_string(variant.as_str()),
2756            render_expr(value),
2757            field.as_str()
2758        ),
2759        Expr::EmptySet => "{}".to_owned(),
2760        Expr::EmptyMap => "[x \\in {} |-> None]".to_owned(),
2761        Expr::SeqLiteral(items) => format!(
2762            "<<{}>>",
2763            items.iter().map(render_expr).collect::<Vec<_>>().join(", ")
2764        ),
2765        Expr::CurrentPhase => "phase".to_owned(),
2766        Expr::Phase(value) => tla_string(value),
2767        Expr::Field(name) => name.as_str().to_owned(),
2768        Expr::Binding(name) => name.clone(),
2769        Expr::Variant(name) => name.clone(),
2770        Expr::None => "None".to_owned(),
2771        Expr::IfElse {
2772            condition,
2773            then_expr,
2774            else_expr,
2775        } => format!(
2776            "IF {} THEN {} ELSE {}",
2777            render_expr(condition),
2778            render_expr(then_expr),
2779            render_expr(else_expr)
2780        ),
2781        Expr::Not(inner) => format!("~({})", render_expr(inner)),
2782        Expr::And(items) => join_exprs(items, " /\\ "),
2783        Expr::Or(items) => join_exprs(items, " \\/ "),
2784        Expr::Eq(left, right) => format!("{} = {}", render_expr(left), render_expr(right)),
2785        Expr::Neq(left, right) => format!("{} # {}", render_expr(left), render_expr(right)),
2786        Expr::Add(left, right) => format!("{} + {}", render_expr(left), render_expr(right)),
2787        Expr::Sub(left, right) => format!("{} - {}", render_expr(left), render_expr(right)),
2788        Expr::Gt(left, right) => format!("{} > {}", render_expr(left), render_expr(right)),
2789        Expr::Gte(left, right) => format!("{} >= {}", render_expr(left), render_expr(right)),
2790        Expr::Lt(left, right) => format!("{} < {}", render_expr(left), render_expr(right)),
2791        Expr::Lte(left, right) => format!("{} <= {}", render_expr(left), render_expr(right)),
2792        Expr::Contains { collection, value } => {
2793            format!("{} \\in {}", render_expr(value), render_expr(collection))
2794        }
2795        Expr::MapContainsKey { map, key } => {
2796            format!("{} \\in DOMAIN {}", render_expr(key), render_expr(map))
2797        }
2798        Expr::SeqStartsWith { seq, prefix } => {
2799            format!("StartsWith({}, {})", render_expr(seq), render_expr(prefix))
2800        }
2801        Expr::SeqElements(inner) => format!("SeqElements({})", render_expr(inner)),
2802        Expr::Len(inner) => format!("Len({})", render_expr(inner)),
2803        Expr::Count { collection, value } => {
2804            format!("Count({}, {})", render_expr(collection), render_expr(value))
2805        }
2806        Expr::Head(inner) => format!("Head({})", render_expr(inner)),
2807        Expr::MapKeys(inner) => format!("DOMAIN {}", render_expr(inner)),
2808        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
2809            format!("{}[{}]", render_expr(map), render_expr(key))
2810        }
2811        Expr::MapLiteral(entries) => format!(
2812            "({})",
2813            entries
2814                .iter()
2815                .map(|(key, value)| format!("{} :> {}", render_expr(key), render_expr(value)))
2816                .collect::<Vec<_>>()
2817                .join(" @@ ")
2818        ),
2819        Expr::Some(inner) => format!("Some({})", render_expr(inner)),
2820        Expr::Call { helper, args } => format!(
2821            "{}({})",
2822            helper,
2823            args.iter().map(render_expr).collect::<Vec<_>>().join(", ")
2824        ),
2825        Expr::Quantified {
2826            quantifier,
2827            binding,
2828            over,
2829            body,
2830        } => {
2831            let keyword = match quantifier {
2832                Quantifier::Any => "\\E",
2833                Quantifier::All => "\\A",
2834            };
2835            format!(
2836                "({} {} \\in {} : {})",
2837                keyword,
2838                binding,
2839                render_expr(over),
2840                render_expr(body)
2841            )
2842        }
2843    }
2844}
2845
2846fn join_exprs(items: &[Expr], separator: &str) -> String {
2847    if items.is_empty() {
2848        return "TRUE".to_owned();
2849    }
2850    items
2851        .iter()
2852        .map(render_expr)
2853        .collect::<Vec<_>>()
2854        .join(separator)
2855}
2856
2857fn render_type_ref(ty: &TypeRef) -> String {
2858    match ty {
2859        TypeRef::Bool => "Bool".to_owned(),
2860        TypeRef::U32 => "Nat".to_owned(),
2861        TypeRef::U64 => "Nat".to_owned(),
2862        TypeRef::String => "String".to_owned(),
2863        TypeRef::Named(name) => name.as_str().to_owned(),
2864        TypeRef::Enum(name) => name.as_str().to_owned(),
2865        TypeRef::Option(inner) => format!("Option({})", render_type_ref(inner)),
2866        TypeRef::Set(inner) => format!("Set({})", render_type_ref(inner)),
2867        TypeRef::Seq(inner) => format!("Seq({})", render_type_ref(inner)),
2868        TypeRef::Map(key, value) => {
2869            format!("Map({}, {})", render_type_ref(key), render_type_ref(value))
2870        }
2871    }
2872}
2873
2874/// Emit the derive line for a generated value struct. A struct with a
2875/// `#[redacted]` field gets a hand-written `Debug` from
2876/// [`render_redacted_debug_impl`] instead of the derived one.
2877#[cfg(not(test))]
2878fn render_value_derive(out: &mut String, indent: &str, fields: &[FieldSchema]) {
2879    let debug = if has_redacted_field(fields) {
2880        ""
2881    } else {
2882        "Debug, "
2883    };
2884    pushln!(
2885        out,
2886        "{indent}#[derive({debug}Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2887    );
2888}
2889
2890#[cfg(not(test))]
2891fn has_redacted_field(fields: &[FieldSchema]) -> bool {
2892    fields
2893        .iter()
2894        .any(|field| field.disclosure == meerkat_machine_schema::FieldDisclosure::Redacted)
2895}
2896
2897/// Emit `Debug` for a value struct that has `#[redacted]` fields: visible
2898/// fields print normally, a redacted field prints presence (option), entry
2899/// count (collection) or `"<redacted>"`, never its value.
2900#[cfg(not(test))]
2901fn render_redacted_debug_impl(
2902    out: &mut String,
2903    indent: &str,
2904    type_name: &str,
2905    leading_visible: &[&str],
2906    fields: &[FieldSchema],
2907) {
2908    if !has_redacted_field(fields) {
2909        return;
2910    }
2911    pushln!(out, "{indent}impl std::fmt::Debug for {type_name} {{");
2912    pushln!(
2913        out,
2914        "{indent}    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{"
2915    );
2916    pushln!(out, "{indent}        f.debug_struct(\"{type_name}\")");
2917    for name in leading_visible {
2918        pushln!(out, "{indent}            .field(\"{name}\", &self.{name})");
2919    }
2920    for field in fields {
2921        let label = field.name.as_str();
2922        let access = format!("self.{}", rust_field_ident(&field.name));
2923        let value = match (field.disclosure, &field.ty) {
2924            // Paths stay qualified: these helpers are compiled out of test builds.
2925            (meerkat_machine_schema::FieldDisclosure::Visible, _) => format!("&{access}"),
2926            (meerkat_machine_schema::FieldDisclosure::Redacted, TypeRef::Option(_)) => {
2927                format!("&{access}.as_ref().map(|_| \"<redacted>\")")
2928            }
2929            (
2930                meerkat_machine_schema::FieldDisclosure::Redacted,
2931                TypeRef::Set(_) | TypeRef::Seq(_) | TypeRef::Map(_, _),
2932            ) => {
2933                format!("&format_args!(\"<redacted; {{}} entries>\", {access}.len())")
2934            }
2935            (
2936                meerkat_machine_schema::FieldDisclosure::Redacted,
2937                TypeRef::Bool
2938                | TypeRef::U32
2939                | TypeRef::U64
2940                | TypeRef::String
2941                | TypeRef::Named(_)
2942                | TypeRef::Enum(_),
2943            ) => "&\"<redacted>\"".to_owned(),
2944        };
2945        pushln!(out, "{indent}            .field(\"{label}\", {value})");
2946    }
2947    pushln!(out, "{indent}            .finish()");
2948    pushln!(out, "{indent}    }}");
2949    pushln!(out, "{indent}}}");
2950}
2951
2952#[cfg(not(test))]
2953fn render_rust_type_ref(ty: &TypeRef) -> String {
2954    match ty {
2955        TypeRef::Bool => "bool".to_owned(),
2956        TypeRef::U32 => "u32".to_owned(),
2957        TypeRef::U64 => "u64".to_owned(),
2958        TypeRef::String => "String".to_owned(),
2959        TypeRef::Named(name) => rust_ident(name),
2960        TypeRef::Enum(name) => rust_ident(name),
2961        TypeRef::Option(inner) => format!("Option<{}>", render_rust_type_ref(inner)),
2962        TypeRef::Set(inner) => {
2963            format!(
2964                "std::collections::BTreeSet<{}>",
2965                render_rust_type_ref(inner)
2966            )
2967        }
2968        TypeRef::Seq(inner) => format!("Vec<{}>", render_rust_type_ref(inner)),
2969        TypeRef::Map(key, value) => format!(
2970            "std::collections::BTreeMap<{}, {}>",
2971            render_rust_type_ref(key),
2972            render_rust_type_ref(value)
2973        ),
2974    }
2975}
2976
2977#[cfg(not(test))]
2978fn collect_machine_named_types(schema: &MachineSchema) -> Vec<String> {
2979    let mut names = std::collections::BTreeSet::new();
2980
2981    for field in &schema.state.fields {
2982        collect_named_types_from_type_ref(&field.ty, &mut names);
2983    }
2984    for variant in &schema.inputs.variants {
2985        for field in &variant.fields {
2986            collect_named_types_from_type_ref(&field.ty, &mut names);
2987        }
2988    }
2989    for variant in &schema.signals.variants {
2990        for field in &variant.fields {
2991            collect_named_types_from_type_ref(&field.ty, &mut names);
2992        }
2993    }
2994    for variant in &schema.effects.variants {
2995        for field in &variant.fields {
2996            collect_named_types_from_type_ref(&field.ty, &mut names);
2997        }
2998    }
2999    for helper in schema.helpers.iter().chain(schema.derived.iter()) {
3000        for field in &helper.params {
3001            collect_named_types_from_type_ref(&field.ty, &mut names);
3002        }
3003        collect_named_types_from_type_ref(&helper.returns, &mut names);
3004    }
3005
3006    names.into_iter().collect()
3007}
3008
3009#[cfg(not(test))]
3010fn collect_named_types_from_type_ref(ty: &TypeRef, names: &mut std::collections::BTreeSet<String>) {
3011    match ty {
3012        TypeRef::Named(name) => {
3013            names.insert(rust_ident(name));
3014        }
3015        TypeRef::Enum(name) => {
3016            names.insert(rust_ident(name));
3017        }
3018        TypeRef::Option(inner) | TypeRef::Set(inner) | TypeRef::Seq(inner) => {
3019            collect_named_types_from_type_ref(inner, names);
3020        }
3021        TypeRef::Map(key, value) => {
3022            collect_named_types_from_type_ref(key, names);
3023            collect_named_types_from_type_ref(value, names);
3024        }
3025        TypeRef::Bool | TypeRef::U32 | TypeRef::U64 | TypeRef::String => {}
3026    }
3027}
3028
3029/// Render the Rust-code text for a [`RustTypeAtom`] — what appears on the
3030/// right-hand side of a `pub type Alias = ...;` declaration or the
3031/// return position of a default-value helper.
3032#[cfg(not(test))]
3033fn render_rust_type_atom(atom: &meerkat_machine_schema::RustTypeAtom) -> String {
3034    use meerkat_machine_schema::RustTypeAtom;
3035    match atom {
3036        RustTypeAtom::U8 => "u8".to_string(),
3037        RustTypeAtom::U16 => "u16".to_string(),
3038        RustTypeAtom::U32 => "u32".to_string(),
3039        RustTypeAtom::U64 => "u64".to_string(),
3040        RustTypeAtom::Bool => "bool".to_string(),
3041        RustTypeAtom::String => "String".to_string(),
3042        RustTypeAtom::StringEnum { .. } => "String".to_string(),
3043        RustTypeAtom::TypePath(path)
3044        | RustTypeAtom::TypePathFieldPresenceSet { path, .. }
3045        | RustTypeAtom::TypePathStruct { path, .. }
3046        | RustTypeAtom::TypePathEnum { path, .. } => path
3047            .strip_prefix("crate::catalog::")
3048            .map(|suffix| format!("meerkat_machine_schema::catalog::{suffix}"))
3049            .unwrap_or_else(|| path.clone()),
3050    }
3051}
3052
3053#[cfg(not(test))]
3054fn render_named_type_definition(
3055    out: &mut String,
3056    name: &str,
3057    atom: &meerkat_machine_schema::RustTypeAtom,
3058) {
3059    use meerkat_machine_schema::RustTypeAtom;
3060
3061    let rust_name = rust_ident(name);
3062    match atom {
3063        RustTypeAtom::TypePath(_)
3064        | RustTypeAtom::TypePathFieldPresenceSet { .. }
3065        | RustTypeAtom::TypePathStruct { .. }
3066        | RustTypeAtom::TypePathEnum { .. } => {
3067            pushln!(
3068                out,
3069                "pub type {} = {};",
3070                rust_name,
3071                render_rust_type_atom(atom)
3072            );
3073        }
3074        RustTypeAtom::String => {
3075            pushln!(
3076                out,
3077                "#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]"
3078            );
3079            pushln!(out, "pub struct {}(pub String);", rust_name);
3080            pushln!(out, "impl From<String> for {} {{", rust_name);
3081            pushln!(out, "    fn from(value: String) -> Self {{ Self(value) }}");
3082            pushln!(out, "}}");
3083            pushln!(out, "impl From<&str> for {} {{", rust_name);
3084            pushln!(
3085                out,
3086                "    fn from(value: &str) -> Self {{ Self(value.to_owned()) }}"
3087            );
3088            pushln!(out, "}}");
3089            pushln!(out, "impl std::fmt::Display for {} {{", rust_name);
3090            pushln!(
3091                out,
3092                "    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{ f.write_str(&self.0) }}"
3093            );
3094            pushln!(out, "}}");
3095        }
3096        RustTypeAtom::StringEnum { variants } => {
3097            if let Some((first, second, ident)) = string_enum_variant_ident_collision(variants) {
3098                pushln!(
3099                    out,
3100                    "compile_error!(\"string enum {} variants `{}` and `{}` sanitize to duplicate Rust identifier `{}`\");",
3101                    rust_name,
3102                    first,
3103                    second,
3104                    ident
3105                );
3106                return;
3107            }
3108            pushln!(out, "#[allow(non_camel_case_types)]");
3109            pushln!(
3110                out,
3111                "#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]"
3112            );
3113            pushln!(out, "pub enum {} {{", rust_name);
3114            for (index, variant) in variants.iter().enumerate() {
3115                if index == 0 {
3116                    pushln!(out, "    #[default]");
3117                }
3118                let wire_label = known_enum_variant_wire_label(&rust_name, variant.as_str());
3119                pushln!(out, "    #[serde(rename = {})]", tla_string(wire_label));
3120                pushln!(out, "    {},", rust_ident(variant.as_str()));
3121            }
3122            pushln!(out, "}}");
3123            pushln!(out, "impl {} {{", rust_name);
3124            pushln!(out, "    pub fn as_str(&self) -> &'static str {{");
3125            pushln!(out, "        match self {{");
3126            for variant in variants {
3127                let wire_expr = known_enum_variant_wire_expr(&rust_name, variant.as_str());
3128                pushln!(
3129                    out,
3130                    "            Self::{} => {},",
3131                    rust_ident(variant.as_str()),
3132                    wire_expr
3133                );
3134            }
3135            pushln!(out, "        }}");
3136            pushln!(out, "    }}");
3137            pushln!(out, "}}");
3138            pushln!(out, "impl std::convert::TryFrom<&str> for {} {{", rust_name);
3139            pushln!(out, "    type Error = String;");
3140            pushln!(
3141                out,
3142                "    fn try_from(value: &str) -> Result<Self, Self::Error> {{"
3143            );
3144            pushln!(out, "        match value {{");
3145            for variant in variants {
3146                let wire_label = known_enum_variant_wire_label(&rust_name, variant.as_str());
3147                pushln!(
3148                    out,
3149                    "            \"{}\" => Ok(Self::{}),",
3150                    wire_label,
3151                    rust_ident(variant.as_str())
3152                );
3153            }
3154            pushln!(
3155                out,
3156                "            other => Err(format!(\"invalid {} value `{{other}}`\")),",
3157                rust_name
3158            );
3159            pushln!(out, "        }}");
3160            pushln!(out, "    }}");
3161            pushln!(out, "}}");
3162            pushln!(
3163                out,
3164                "impl std::convert::TryFrom<String> for {} {{",
3165                rust_name
3166            );
3167            pushln!(out, "    type Error = String;");
3168            pushln!(
3169                out,
3170                "    fn try_from(value: String) -> Result<Self, Self::Error> {{ Self::try_from(value.as_str()) }}"
3171            );
3172            pushln!(out, "}}");
3173            pushln!(out, "impl std::fmt::Display for {} {{", rust_name);
3174            pushln!(
3175                out,
3176                "    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{ f.write_str(self.as_str()) }}"
3177            );
3178            pushln!(out, "}}");
3179        }
3180        RustTypeAtom::Bool
3181        | RustTypeAtom::U8
3182        | RustTypeAtom::U16
3183        | RustTypeAtom::U32
3184        | RustTypeAtom::U64 => {
3185            let inner = render_rust_type_atom(atom);
3186            pushln!(
3187                out,
3188                "#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]"
3189            );
3190            pushln!(out, "pub struct {}(pub {});", rust_name, inner);
3191            pushln!(out, "impl From<{}> for {} {{", inner, rust_name);
3192            pushln!(
3193                out,
3194                "    fn from(value: {}) -> Self {{ Self(value) }}",
3195                inner
3196            );
3197            pushln!(out, "}}");
3198            pushln!(out, "impl std::fmt::Display for {} {{", rust_name);
3199            pushln!(
3200                out,
3201                "    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{ write!(f, \"{{}}\", self.0) }}"
3202            );
3203            pushln!(out, "}}");
3204        }
3205    }
3206}
3207
3208#[cfg(not(test))]
3209fn string_enum_variant_ident_collision<T: AsRef<str>>(
3210    variants: &[T],
3211) -> Option<(String, String, String)> {
3212    let mut seen: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
3213    for variant in variants {
3214        let raw = variant.as_ref();
3215        let ident = rust_ident(raw);
3216        if let Some(first) = seen.get(&ident) {
3217            return Some((first.clone(), raw.to_owned(), ident));
3218        }
3219        seen.insert(ident, raw.to_owned());
3220    }
3221    None
3222}
3223
3224/// Look up the authoritative Rust atom for a `TypeRef::Named` slug.
3225///
3226#[cfg(not(test))]
3227fn lookup_named_type_atom<'a>(
3228    schema: &'a MachineSchema,
3229    name: &str,
3230) -> Option<&'a meerkat_machine_schema::RustTypeAtom> {
3231    schema
3232        .named_types
3233        .iter()
3234        .find(|binding| binding.name.as_str() == name)
3235        .map(|binding| &binding.rust)
3236}
3237
3238#[cfg(not(test))]
3239fn rust_ident(value: impl AsRef<str>) -> String {
3240    value
3241        .as_ref()
3242        .chars()
3243        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
3244        .collect()
3245}
3246
3247fn known_enum_variant_wire_label(enum_name: &str, variant: &str) -> String {
3248    if enum_name == meerkat_core::turn_execution_authority::ContentShape::SCHEMA_TYPE_NAME
3249        && let Some(shape) =
3250            meerkat_core::turn_execution_authority::ContentShape::from_schema_variant(variant)
3251    {
3252        return shape.as_str().to_owned();
3253    }
3254
3255    variant.to_owned()
3256}
3257
3258#[cfg_attr(test, allow(dead_code))]
3259fn known_enum_variant_wire_expr(enum_name: &str, variant: &str) -> String {
3260    if enum_name == meerkat_core::turn_execution_authority::ContentShape::SCHEMA_TYPE_NAME
3261        && let Some(shape) =
3262            meerkat_core::turn_execution_authority::ContentShape::from_schema_variant(variant)
3263    {
3264        return format!(
3265            "meerkat_core::turn_execution_authority::ContentShape::{}.as_str()",
3266            shape.schema_variant()
3267        );
3268    }
3269
3270    tla_string(variant)
3271}
3272
3273#[cfg(not(test))]
3274fn rust_field_ident(value: impl AsRef<str>) -> String {
3275    rust_ident(value)
3276}
3277
3278#[cfg(not(test))]
3279#[allow(dead_code)]
3280fn rust_fn_ident(value: &str) -> String {
3281    simple_snake_case(value)
3282}
3283
3284#[cfg(not(test))]
3285#[allow(dead_code)]
3286fn simple_snake_case(value: &str) -> String {
3287    let mut out = String::new();
3288    for (idx, ch) in value.chars().enumerate() {
3289        if ch.is_ascii_uppercase() {
3290            if idx != 0 {
3291                out.push('_');
3292            }
3293            out.push(ch.to_ascii_lowercase());
3294        } else if ch.is_ascii_alphanumeric() {
3295            out.push(ch.to_ascii_lowercase());
3296        } else {
3297            out.push('_');
3298        }
3299    }
3300    out
3301}
3302
3303fn render_enum_variants_inline(schema: &EnumSchema) -> String {
3304    let variants = schema
3305        .variants
3306        .iter()
3307        .map(|variant| tla_string(&variant.name))
3308        .collect::<Vec<_>>()
3309        .join(", ");
3310    format!("{{{variants}}}")
3311}
3312
3313fn render_string_list<S: AsRef<str>>(items: &[S]) -> String {
3314    let rendered = items.iter().map(tla_string).collect::<Vec<_>>().join(", ");
3315    format!("<<{rendered}>>")
3316}
3317
3318#[cfg(not(test))]
3319fn render_route_delivery(delivery: &RouteDelivery) -> &'static str {
3320    match delivery {
3321        RouteDelivery::Immediate => "Immediate",
3322        RouteDelivery::Enqueue => "Enqueue",
3323    }
3324}
3325
3326#[cfg(not(test))]
3327fn render_route_bindings(route: &meerkat_machine_schema::Route) -> String {
3328    route
3329        .bindings
3330        .iter()
3331        .map(|binding| match &binding.source {
3332            meerkat_machine_schema::RouteBindingSource::Field {
3333                from_field,
3334                allow_named_alias,
3335            } => {
3336                if *allow_named_alias {
3337                    format!("{from_field} ~> {}", binding.to_field)
3338                } else {
3339                    format!("{from_field} -> {}", binding.to_field)
3340                }
3341            }
3342            meerkat_machine_schema::RouteBindingSource::Literal(expr) => {
3343                format!("{} := {}", binding.to_field, render_expr(expr))
3344            }
3345            meerkat_machine_schema::RouteBindingSource::OwnerProvided => {
3346                format!("{} := <owner-provided>", binding.to_field)
3347            }
3348        })
3349        .collect::<Vec<_>>()
3350        .join(", ")
3351}
3352
3353#[cfg(not(test))]
3354fn render_scheduler_rule(rule: &SchedulerRule) -> String {
3355    match rule {
3356        SchedulerRule::PreemptWhenReady { higher, lower } => {
3357            format!("PreemptWhenReady({}, {})", higher, lower)
3358        }
3359    }
3360}
3361
3362#[cfg(not(test))]
3363fn render_composition_invariant_kind(kind: &CompositionInvariantKind) -> String {
3364    match kind {
3365        CompositionInvariantKind::RoutePresent {
3366            from_machine,
3367            effect_variant,
3368            to_machine,
3369            input_variant,
3370        } => format!(
3371            "RoutePresent({}, {}, {}, {})",
3372            from_machine, effect_variant, to_machine, input_variant
3373        ),
3374        CompositionInvariantKind::ActorPriorityPresent { higher, lower } => {
3375            format!("ActorPriorityPresent({}, {})", higher, lower)
3376        }
3377        CompositionInvariantKind::ObservedInputOriginatesFromEffect {
3378            to_machine,
3379            input_variant,
3380            from_machine,
3381            effect_variant,
3382        } => format!(
3383            "ObservedInputOriginatesFromEffect({}, {}, {}, {})",
3384            to_machine, input_variant, from_machine, effect_variant
3385        ),
3386        CompositionInvariantKind::ObservedRouteInputOriginatesFromEffect {
3387            route_name,
3388            to_machine,
3389            input_variant,
3390            from_machine,
3391            effect_variant,
3392        } => format!(
3393            "ObservedRouteInputOriginatesFromEffect({}, {}, {}, {}, {})",
3394            route_name, to_machine, input_variant, from_machine, effect_variant
3395        ),
3396        CompositionInvariantKind::SchedulerRulePresent { rule } => {
3397            format!("SchedulerRulePresent({})", render_scheduler_rule(rule))
3398        }
3399        CompositionInvariantKind::OutcomeHandled {
3400            from_machine,
3401            effect_variant,
3402            required_targets,
3403        } => format!(
3404            "OutcomeHandled({}, {}, {})",
3405            from_machine,
3406            effect_variant,
3407            required_targets
3408                .iter()
3409                .map(|target| format!("{}.{}", target.machine, target.input_variant))
3410                .collect::<Vec<_>>()
3411                .join(" | ")
3412        ),
3413        CompositionInvariantKind::HandoffProtocolCovered {
3414            producer_instance,
3415            effect_variant,
3416            protocol_name,
3417        } => format!(
3418            "HandoffProtocolCovered({}, {}, {})",
3419            producer_instance, effect_variant, protocol_name
3420        ),
3421    }
3422}
3423
3424fn tla_ident(value: impl AsRef<str>) -> String {
3425    value
3426        .as_ref()
3427        .chars()
3428        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
3429        .collect()
3430}
3431
3432fn tla_string(value: impl AsRef<str>) -> String {
3433    format!("\"{}\"", value.as_ref().replace('"', "\\\""))
3434}
3435
3436#[cfg(test)]
3437mod tests {
3438    use super::render_machine_module;
3439    use meerkat_machine_schema::identity::{
3440        EffectVariantId, EnumVariantId, FieldId, InputVariantId, MachineId, PhaseId, TransitionId,
3441    };
3442    use meerkat_machine_schema::{
3443        EffectEmit, EnumSchema, Expr, FieldInit, FieldSchema, InitSchema, MachineSchema,
3444        RustBinding, StateSchema, TransitionSchema, TriggerMatch, TypeRef, Update, VariantSchema,
3445    };
3446
3447    fn vid(s: &str) -> EnumVariantId {
3448        EnumVariantId::parse(s).expect("valid enum variant slug")
3449    }
3450
3451    fn fid(s: &str) -> FieldId {
3452        FieldId::parse(s).expect("valid field slug")
3453    }
3454
3455    fn pid(s: &str) -> PhaseId {
3456        PhaseId::parse(s).expect("valid phase slug")
3457    }
3458
3459    fn tid(s: &str) -> TransitionId {
3460        TransitionId::parse(s).expect("valid transition slug")
3461    }
3462
3463    fn ivid(s: &str) -> InputVariantId {
3464        InputVariantId::parse(s).expect("valid input variant slug")
3465    }
3466
3467    fn eid(s: &str) -> EffectVariantId {
3468        EffectVariantId::parse(s).expect("valid effect variant slug")
3469    }
3470
3471    fn turn_execution_fixture() -> MachineSchema {
3472        MachineSchema {
3473            machine: MachineId::parse("TurnExecutionMachine").expect("valid machine slug"),
3474            version: 1,
3475            rust: RustBinding {
3476                crate_name: "meerkat-core".to_owned(),
3477                module: "agent::turn_execution".to_owned(),
3478            },
3479            state: StateSchema {
3480                phase: EnumSchema {
3481                    name: "TurnExecutionPhase".to_owned(),
3482                    variants: vec![
3483                        VariantSchema {
3484                            name: vid("Idle"),
3485                            fields: vec![],
3486                        },
3487                        VariantSchema {
3488                            name: vid("Running"),
3489                            fields: vec![],
3490                        },
3491                        VariantSchema {
3492                            name: vid("AwaitingBoundary"),
3493                            fields: vec![],
3494                        },
3495                        VariantSchema {
3496                            name: vid("Cancelled"),
3497                            fields: vec![],
3498                        },
3499                    ],
3500                },
3501                fields: vec![FieldSchema {
3502                    name: fid("boundary_count"),
3503                    ty: TypeRef::U64,
3504                    disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
3505                }],
3506                init: InitSchema {
3507                    phase: pid("Idle"),
3508                    fields: vec![FieldInit {
3509                        field: fid("boundary_count"),
3510                        expr: Expr::U64(0),
3511                    }],
3512                },
3513                terminal_phases: vec![pid("Cancelled")],
3514            },
3515            inputs: EnumSchema {
3516                name: "TurnExecutionInput".to_owned(),
3517                variants: vec![
3518                    VariantSchema {
3519                        name: vid("StartConversationRun"),
3520                        fields: vec![FieldSchema {
3521                            name: fid("run_id"),
3522                            ty: TypeRef::String,
3523                            disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
3524                        }],
3525                    },
3526                    VariantSchema {
3527                        name: vid("PrimitiveAppliedConversationTurn"),
3528                        fields: vec![FieldSchema {
3529                            name: fid("run_id"),
3530                            ty: TypeRef::String,
3531                            disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
3532                        }],
3533                    },
3534                    VariantSchema {
3535                        name: vid("BoundaryComplete"),
3536                        fields: vec![],
3537                    },
3538                    VariantSchema {
3539                        name: vid("AcknowledgeTerminalFromCancelled"),
3540                        fields: vec![],
3541                    },
3542                ],
3543            },
3544            surface_only_inputs: vec![],
3545            runtime_internal_inputs: vec![],
3546            tlc_representative_inputs: vec![],
3547            signals: EnumSchema {
3548                name: "TurnExecutionSignal".to_owned(),
3549                variants: vec![],
3550            },
3551            effects: EnumSchema {
3552                name: "TurnExecutionEffect".to_owned(),
3553                variants: vec![VariantSchema {
3554                    name: vid("BoundaryApplied"),
3555                    fields: vec![
3556                        FieldSchema {
3557                            name: fid("run_id"),
3558                            ty: TypeRef::String,
3559                            disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
3560                        },
3561                        FieldSchema {
3562                            name: fid("boundary_sequence"),
3563                            ty: TypeRef::U64,
3564                            disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
3565                        },
3566                    ],
3567                }],
3568            },
3569            helpers: vec![],
3570            derived: vec![],
3571            command_plans: vec![],
3572            invariants: vec![],
3573            transitions: vec![
3574                TransitionSchema {
3575                    name: tid("StartConversationRun"),
3576                    from: vec![pid("Idle")],
3577                    on: TriggerMatch::Input {
3578                        variant: ivid("StartConversationRun"),
3579                        bindings: vec![fid("run_id")],
3580                    },
3581                    guards: vec![],
3582                    updates: vec![],
3583                    to: pid("Running"),
3584                    emit: vec![],
3585                },
3586                TransitionSchema {
3587                    name: tid("PrimitiveAppliedConversationTurn"),
3588                    from: vec![pid("Running")],
3589                    on: TriggerMatch::Input {
3590                        variant: ivid("PrimitiveAppliedConversationTurn"),
3591                        bindings: vec![fid("run_id")],
3592                    },
3593                    guards: vec![],
3594                    updates: vec![Update::Increment {
3595                        field: fid("boundary_count"),
3596                        amount: 1,
3597                    }],
3598                    to: pid("AwaitingBoundary"),
3599                    emit: vec![EffectEmit {
3600                        variant: eid("BoundaryApplied"),
3601                        fields: [
3602                            (fid("run_id"), Expr::Binding("run_id".to_owned())),
3603                            (
3604                                fid("boundary_sequence"),
3605                                Expr::Add(
3606                                    Box::new(Expr::Field(fid("boundary_count"))),
3607                                    Box::new(Expr::U64(1)),
3608                                ),
3609                            ),
3610                        ]
3611                        .into_iter()
3612                        .collect(),
3613                    }],
3614                },
3615                TransitionSchema {
3616                    name: tid("BoundaryComplete"),
3617                    from: vec![pid("AwaitingBoundary")],
3618                    on: TriggerMatch::Input {
3619                        variant: ivid("BoundaryComplete"),
3620                        bindings: vec![],
3621                    },
3622                    guards: vec![],
3623                    updates: vec![],
3624                    to: pid("Cancelled"),
3625                    emit: vec![],
3626                },
3627                TransitionSchema {
3628                    name: tid("AcknowledgeTerminalFromCancelled"),
3629                    from: vec![pid("Cancelled")],
3630                    on: TriggerMatch::Input {
3631                        variant: ivid("AcknowledgeTerminalFromCancelled"),
3632                        bindings: vec![],
3633                    },
3634                    guards: vec![],
3635                    updates: vec![],
3636                    to: pid("Cancelled"),
3637                    emit: vec![],
3638                },
3639            ],
3640            ci_step_limit: None,
3641            tlc_model: None,
3642            deep_domain_overrides: Default::default(),
3643            input_field_domains: Default::default(),
3644            effect_dispositions: vec![],
3645            named_types: vec![],
3646        }
3647    }
3648
3649    #[test]
3650    fn renders_turn_execution_with_boundary_and_terminal_transitions() {
3651        let rendered = render_machine_module(&turn_execution_fixture());
3652
3653        assert!(rendered.contains("TRANSITIONS\n  StartConversationRun"));
3654        assert!(rendered.contains("PrimitiveAppliedConversationTurn"));
3655        assert!(rendered.contains("BoundaryComplete"));
3656        assert!(rendered.contains("AcknowledgeTerminalFromCancelled"));
3657        assert!(rendered.contains(
3658            "BoundaryApplied([run_id |-> run_id, boundary_sequence |-> boundary_count + 1])"
3659        ));
3660    }
3661}