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