Skip to main content

meerkat_machine_codegen/
render.rs

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