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