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