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#[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#[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#[cfg(not(test))]
423const MEERKAT_APPENDED_INPUT_SECTION_LAST: &str = "ClassifyStopInputDisposition";
424
425#[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 "RequestFiniteSwitchTurnTranscriptUnsupportedIdle",
541 "RequestFiniteSwitchTurnTranscriptUnsupportedAttached",
542 "RequestFiniteSwitchTurnTranscriptUnsupportedRunning",
543 "RequestUntilChangedSwitchTurnTranscriptUnsupportedIdle",
544 "RequestUntilChangedSwitchTurnTranscriptUnsupportedAttached",
545 "RequestUntilChangedSwitchTurnTranscriptUnsupportedRunning",
546 "SuspendRunForStopFenceGapRunningToIdle",
547 "SuspendRunForStopFenceGapRunningToAttached",
548 "StopCurrentRunForRunResumableIdle",
549 "StopCurrentRunForRunResumableAttached",
550 "AbortUntilChangedSwitchTurnReconfigureIdle",
553 "AbortUntilChangedSwitchTurnReconfigureAttached",
554 "AbortUntilChangedSwitchTurnReconfigureRunning",
555 "AbortUntilChangedSwitchTurnReconfigureRetired",
556 "AbortUntilChangedSwitchTurnReconfigureStopped",
557 "RequestUntilChangedSwitchTurnPendingConflictIdle",
561 "RequestUntilChangedSwitchTurnPendingConflictAttached",
562 "RequestUntilChangedSwitchTurnPendingConflictRunning",
563 "CompleteUntilChangedSwitchTurnReconfigureRetired",
566 "CompleteUntilChangedSwitchTurnReconfigureStopped",
567 "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 "HoldResumedRunForAdmissionIdle",
594 "HoldResumedRunForAdmissionAttached",
595 "HoldResumedRunForAdmissionRunning",
596 "HoldResumedRunForAdmissionRetired",
597 "HoldResumedRunForAdmissionStopped",
598 "ReleaseResumedRunAdmissionIdle",
599 "ReleaseResumedRunAdmissionAttached",
600 "ReleaseResumedRunAdmissionRunning",
601 "ReleaseResumedRunAdmissionRetired",
602 "ReleaseResumedRunAdmissionStopped",
603 "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 "CloseLiveDelegationIntakeIdle",
622 "CloseLiveDelegationIntakeAttached",
623 "CloseLiveDelegationIntakeRunning",
624 "CloseLiveDelegationIntakeRetired",
625 "CloseLiveDelegationIntakeStopped",
626 "BindInputRequesterBatchKeyIdle",
629 "BindInputRequesterBatchKeyAttached",
630 "BindInputRequesterBatchKeyRunning",
631 "BindInputRequesterBatchKeyRetired",
632 "BindInputRequesterBatchKeyStopped",
633 "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 "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 "ClassifyRecoveredInputDurabilityRetainEphemeralPendingTerminalCarrierInitializing",
710 "ClassifyRecoveredInputDurabilityRetainEphemeralPendingTerminalCarrierIdle",
711 "ClassifyRecoveredInputDurabilityRetainEphemeralPendingTerminalCarrierAttached",
712 "ClassifyRecoveredInputDurabilityRetainEphemeralPendingTerminalCarrierRunning",
713 "ClassifyRecoveredInputDurabilityRetainEphemeralPendingTerminalCarrierRetired",
714 "ClassifyRecoveredInputDurabilityRetainEphemeralPendingTerminalCarrierStopped",
715 "RequestFiniteSwitchTurnReasoningEffortRefusedIdle",
722 "RequestFiniteSwitchTurnReasoningEffortRefusedAttached",
723 "RequestFiniteSwitchTurnReasoningEffortRefusedRunning",
724 "RequestUntilChangedSwitchTurnReasoningEffortRefusedIdle",
725 "RequestUntilChangedSwitchTurnReasoningEffortRefusedAttached",
726 "RequestUntilChangedSwitchTurnReasoningEffortRefusedRunning",
727 "DeferInputBehindBacklogEndedByStagedRollbackIdle",
732 "DeferInputBehindBacklogEndedByStagedRollbackAttached",
733 "DeferInputBehindBacklogEndedByStagedRollbackRunning",
734 "DeferInputBehindBacklogEndedByStagedRollbackRetired",
735 "DeferInputBehindBacklogEndedByStagedRollbackStopped",
736 "PeerMessageSentRecordingAIdle",
743 "PeerMessageSentRecordingAAttached",
744 "PeerMessageSentRecordingARunning",
745 "PeerMessageSentRecordingARetired",
746 "PeerMessageSentRecordingAStopped",
747 "PeerMessageSentRecordingBIdle",
748 "PeerMessageSentRecordingBAttached",
749 "PeerMessageSentRecordingBRunning",
750 "PeerMessageSentRecordingBRetired",
751 "PeerMessageSentRecordingBStopped",
752 "PeerMessageEndAnswerArrivedRecordedAIdle",
753 "PeerMessageEndAnswerArrivedRecordedAAttached",
754 "PeerMessageEndAnswerArrivedRecordedARunning",
755 "PeerMessageEndAnswerArrivedRecordedARetired",
756 "PeerMessageEndAnswerArrivedRecordedAStopped",
757 "PeerMessageEndAnswerArrivedRecordedBIdle",
758 "PeerMessageEndAnswerArrivedRecordedBAttached",
759 "PeerMessageEndAnswerArrivedRecordedBRunning",
760 "PeerMessageEndAnswerArrivedRecordedBRetired",
761 "PeerMessageEndAnswerArrivedRecordedBStopped",
762 "PeerMessageReceivedIdle",
763 "PeerMessageReceivedAttached",
764 "PeerMessageReceivedRunning",
765 "PeerMessageReceivedRetired",
766 "PeerMessageReceivedStopped",
767 "PeerInputEndedUnrunRequestIdle",
768 "PeerInputEndedUnrunRequestAttached",
769 "PeerInputEndedUnrunRequestRunning",
770 "PeerInputEndedUnrunRequestRetired",
771 "PeerInputEndedUnrunRequestStopped",
772 "PeerInputEndedUnfinishedRequestIdle",
773 "PeerInputEndedUnfinishedRequestAttached",
774 "PeerInputEndedUnfinishedRequestRunning",
775 "PeerInputEndedUnfinishedRequestRetired",
776 "PeerInputEndedUnfinishedRequestStopped",
777 "PeerInputEndedUnrunMessageIdle",
778 "PeerInputEndedUnrunMessageAttached",
779 "PeerInputEndedUnrunMessageRunning",
780 "PeerInputEndedUnrunMessageRetired",
781 "PeerInputEndedUnrunMessageStopped",
782 "PeerInputEndedUnfinishedMessageIdle",
783 "PeerInputEndedUnfinishedMessageAttached",
784 "PeerInputEndedUnfinishedMessageRunning",
785 "PeerInputEndedUnfinishedMessageRetired",
786 "PeerInputEndedUnfinishedMessageStopped",
787 "PeerEndAnswerClaimedIdle",
788 "PeerEndAnswerClaimedAttached",
789 "PeerEndAnswerClaimedRunning",
790 "PeerEndAnswerClaimedRetired",
791 "PeerEndAnswerClaimedStopped",
792 "PeerEndAnswerClaimedDestroyed",
793 "PeerMessageInputSettledIdle",
794 "PeerMessageInputSettledAttached",
795 "PeerMessageInputSettledRunning",
796 "PeerMessageInputSettledRetired",
797 "PeerMessageInputSettledStopped",
798 "PeerMessageInputSettledDestroyed",
799 "ResolveInboundPeerIdClaimRequestBySenderInitializing",
800 "ResolveInboundPeerIdClaimRequestBySenderIdle",
801 "ResolveInboundPeerIdClaimRequestBySenderAttached",
802 "ResolveInboundPeerIdClaimRequestBySenderRunning",
803 "ResolveInboundPeerIdClaimRequestBySenderRetired",
804 "ResolveInboundPeerIdClaimRequestBySenderStopped",
805 "ResolveInboundPeerIdClaimRequestBySenderDestroyed",
806 "ResolveInboundPeerIdClaimRequestByAnotherInitializing",
807 "ResolveInboundPeerIdClaimRequestByAnotherIdle",
808 "ResolveInboundPeerIdClaimRequestByAnotherAttached",
809 "ResolveInboundPeerIdClaimRequestByAnotherRunning",
810 "ResolveInboundPeerIdClaimRequestByAnotherRetired",
811 "ResolveInboundPeerIdClaimRequestByAnotherStopped",
812 "ResolveInboundPeerIdClaimRequestByAnotherDestroyed",
813 "ResolveInboundPeerIdClaimMessageBySenderInitializing",
814 "ResolveInboundPeerIdClaimMessageBySenderIdle",
815 "ResolveInboundPeerIdClaimMessageBySenderAttached",
816 "ResolveInboundPeerIdClaimMessageBySenderRunning",
817 "ResolveInboundPeerIdClaimMessageBySenderRetired",
818 "ResolveInboundPeerIdClaimMessageBySenderStopped",
819 "ResolveInboundPeerIdClaimMessageBySenderDestroyed",
820 "ResolveInboundPeerIdClaimMessageByAnotherInitializing",
821 "ResolveInboundPeerIdClaimMessageByAnotherIdle",
822 "ResolveInboundPeerIdClaimMessageByAnotherAttached",
823 "ResolveInboundPeerIdClaimMessageByAnotherRunning",
824 "ResolveInboundPeerIdClaimMessageByAnotherRetired",
825 "ResolveInboundPeerIdClaimMessageByAnotherStopped",
826 "ResolveInboundPeerIdClaimMessageByAnotherDestroyed",
827 "ResolveInboundPeerIdClaimOwedBySenderInitializing",
828 "ResolveInboundPeerIdClaimOwedBySenderIdle",
829 "ResolveInboundPeerIdClaimOwedBySenderAttached",
830 "ResolveInboundPeerIdClaimOwedBySenderRunning",
831 "ResolveInboundPeerIdClaimOwedBySenderRetired",
832 "ResolveInboundPeerIdClaimOwedBySenderStopped",
833 "ResolveInboundPeerIdClaimOwedBySenderDestroyed",
834 "ResolveInboundPeerIdClaimOwedByAnotherInitializing",
835 "ResolveInboundPeerIdClaimOwedByAnotherIdle",
836 "ResolveInboundPeerIdClaimOwedByAnotherAttached",
837 "ResolveInboundPeerIdClaimOwedByAnotherRunning",
838 "ResolveInboundPeerIdClaimOwedByAnotherRetired",
839 "ResolveInboundPeerIdClaimOwedByAnotherStopped",
840 "ResolveInboundPeerIdClaimOwedByAnotherDestroyed",
841 "ResolveInboundPeerIdClaimUnclaimedInitializing",
842 "ResolveInboundPeerIdClaimUnclaimedIdle",
843 "ResolveInboundPeerIdClaimUnclaimedAttached",
844 "ResolveInboundPeerIdClaimUnclaimedRunning",
845 "ResolveInboundPeerIdClaimUnclaimedRetired",
846 "ResolveInboundPeerIdClaimUnclaimedStopped",
847 "ResolveInboundPeerIdClaimUnclaimedDestroyed",
848 "PeerInputEndedInHistoryRequestIdle",
852 "PeerInputEndedInHistoryRequestAttached",
853 "PeerInputEndedInHistoryRequestRunning",
854 "PeerInputEndedInHistoryRequestRetired",
855 "PeerInputEndedInHistoryRequestStopped",
856 "PeerInputEndedInHistoryMessageIdle",
857 "PeerInputEndedInHistoryMessageAttached",
858 "PeerInputEndedInHistoryMessageRunning",
859 "PeerInputEndedInHistoryMessageRetired",
860 "PeerInputEndedInHistoryMessageStopped",
861 "PeerMarkedInputSessionEndedRequestIdle",
862 "PeerMarkedInputSessionEndedRequestAttached",
863 "PeerMarkedInputSessionEndedRequestRunning",
864 "PeerMarkedInputSessionEndedRequestRetired",
865 "PeerMarkedInputSessionEndedRequestStopped",
866 "PeerMarkedInputSessionEndedMessageIdle",
867 "PeerMarkedInputSessionEndedMessageAttached",
868 "PeerMarkedInputSessionEndedMessageRunning",
869 "PeerMarkedInputSessionEndedMessageRetired",
870 "PeerMarkedInputSessionEndedMessageStopped",
871 "PeerInputEndedSettledMessageIdle",
872 "PeerInputEndedSettledMessageAttached",
873 "PeerInputEndedSettledMessageRunning",
874 "PeerInputEndedSettledMessageRetired",
875 "PeerInputEndedSettledMessageStopped",
876 "ForgoLiveContextBootstrapIdle",
877 "ForgoLiveContextBootstrapAttached",
878 "ForgoLiveContextBootstrapRunning",
879 "DeclareNoActionRecorded",
884 "ResumeDeclaredNoActionToBoundary",
887 "BeginLiveCloseReplayIdle",
892 "BeginLiveCloseReplayAttached",
893 "BeginLiveCloseReplayRunning",
894 "BeginLiveCloseReplayRetired",
895 "BeginLiveCloseReplayStopped",
896 "EndLiveCloseReplayChannelGoneIdle",
897 "EndLiveCloseReplayChannelGoneAttached",
898 "EndLiveCloseReplayChannelGoneRunning",
899 "EndLiveCloseReplayChannelGoneRetired",
900 "EndLiveCloseReplayChannelGoneStopped",
901 "EndLiveCloseReplayChannelStillBoundIdle",
902 "EndLiveCloseReplayChannelStillBoundAttached",
903 "EndLiveCloseReplayChannelStillBoundRunning",
904 "EndLiveCloseReplayChannelStillBoundRetired",
905 "EndLiveCloseReplayChannelStillBoundStopped",
906 "ResolveAdmissionPlanStarterJobEndedContinuationIdle",
907 "ResolveAdmissionPlanStarterJobEndedContinuationAttached",
908 "ResolveAdmissionPlanStarterJobEndedContinuationWithheldIdle",
909 "ResolveAdmissionPlanStarterJobEndedContinuationWithheldAttached",
910 "ResolveAdmissionPlanStarterJobEndedContinuationWithheldRunning",
911 "ClassifyOperationStarterContinuationContinuesIdle",
912 "ClassifyOperationStarterContinuationContinuesAttached",
913 "ClassifyOperationStarterContinuationContinuesRunning",
914 "ClassifyOperationStarterContinuationContinuesRetired",
915 "ClassifyOperationStarterContinuationContinuesStopped",
916 "ClassifyOperationStarterContinuationDeclinesIdle",
917 "ClassifyOperationStarterContinuationDeclinesAttached",
918 "ClassifyOperationStarterContinuationDeclinesRunning",
919 "ClassifyOperationStarterContinuationDeclinesRetired",
920 "ClassifyOperationStarterContinuationDeclinesStopped",
921 "DeclareOperationStarterJobIdle",
922 "DeclareOperationStarterJobAttached",
923 "DeclareOperationStarterJobRunning",
924 "DeclareOperationStarterJobRetired",
925 "DeclareOperationStarterJobStopped",
926 "ResetStarterContinuationChainIdle",
927 "ResetStarterContinuationChainAttached",
928 "ResetStarterContinuationChainRunning",
929 "ResetStarterContinuationChainKeptIdle",
930 "ResetStarterContinuationChainKeptAttached",
931 "ResetStarterContinuationChainKeptRunning",
932 "ClassifyOperationStarterOutstandingOwedIdle",
933 "ClassifyOperationStarterOutstandingOwedAttached",
934 "ClassifyOperationStarterOutstandingOwedRunning",
935 "ClassifyOperationStarterOutstandingOwedRetired",
936 "ClassifyOperationStarterOutstandingOwedStopped",
937 "ClassifyOperationStarterOutstandingSettledIdle",
938 "ClassifyOperationStarterOutstandingSettledAttached",
939 "ClassifyOperationStarterOutstandingSettledRunning",
940 "ClassifyOperationStarterOutstandingSettledRetired",
941 "ClassifyOperationStarterOutstandingSettledStopped",
942 "SettleOperationStarterJobKeepsIdle",
943 "SettleOperationStarterJobKeepsAttached",
944 "SettleOperationStarterJobKeepsRunning",
945 "SettleOperationStarterJobKeepsRetired",
946 "SettleOperationStarterJobKeepsStopped",
947 "SettleOperationStarterJobWithdrawsIdle",
948 "SettleOperationStarterJobWithdrawsAttached",
949 "SettleOperationStarterJobWithdrawsRunning",
950 "SettleOperationStarterJobWithdrawsRetired",
951 "SettleOperationStarterJobWithdrawsStopped",
952 "SettleOperationStarterJobAfterEndIdle",
953 "SettleOperationStarterJobAfterEndAttached",
954 "SettleOperationStarterJobAfterEndRunning",
955 "SettleOperationStarterJobAfterEndRetired",
956 "SettleOperationStarterJobAfterEndStopped",
957 "ClassifyOperationStarterResumeAdmissibleIdle",
958 "ClassifyOperationStarterResumeAdmissibleAttached",
959 "ClassifyOperationStarterResumeAdmissibleRunning",
960 "ClassifyOperationStarterResumeAdmissibleRetired",
961 "ClassifyOperationStarterResumeAdmissibleStopped",
962 "ClassifyOperationStarterResumeRefusedIdle",
963 "ClassifyOperationStarterResumeRefusedAttached",
964 "ClassifyOperationStarterResumeRefusedRunning",
965 "ClassifyOperationStarterResumeRefusedRetired",
966 "ClassifyOperationStarterResumeRefusedStopped",
967 "ReserveStarterJobEndedTurnReservedIdle",
968 "ReserveStarterJobEndedTurnReservedAttached",
969 "ReserveStarterJobEndedTurnWithheldIdle",
970 "ReserveStarterJobEndedTurnWithheldAttached",
971 "ReserveStarterJobEndedTurnWithheldRunning",
972 "ResetStarterContinuationChainHoldingReservationIdle",
973 "ResetStarterContinuationChainHoldingReservationAttached",
974 "ResetStarterContinuationChainHoldingReservationRunning",
975 "SettleStarterJobEndedTurnReservationKeptIdle",
976 "SettleStarterJobEndedTurnReservationKeptAttached",
977 "SettleStarterJobEndedTurnReservationKeptRunning",
978 "SettleStarterJobEndedTurnReservationReleasedIdle",
979 "SettleStarterJobEndedTurnReservationReleasedAttached",
980 "SettleStarterJobEndedTurnReservationReleasedRunning",
981 "ReleaseOperationStarterDeliveryIdle",
982 "ReleaseOperationStarterDeliveryAttached",
983 "ReleaseOperationStarterDeliveryRunning",
984 "ReleaseOperationStarterDeliveryRetired",
985 "ReleaseOperationStarterDeliveryStopped",
986 "EvictCompletedOpHeldIdle",
987 "EvictCompletedOpHeldAttached",
988 "EvictCompletedOpHeldRunning",
989 "EvictCompletedOpHeldRetired",
990 "EvictCompletedOpHeldStopped",
991 "KeepEmptyResumeForStarterJobIdle",
992 "KeepEmptyResumeForStarterJobAttached",
993 "KeepEmptyResumeForStarterJobRunning",
994 "KeepEmptyResumeForStarterJobRetired",
995 "KeepEmptyResumeForStarterJobStopped",
996 "CollectCompletedOpHeldIdle",
997 "CollectCompletedOpHeldAttached",
998 "CollectCompletedOpHeldRunning",
999 "CollectCompletedOpHeldRetired",
1000 "CollectCompletedOpHeldStopped",
1001 "ClassifyAgentCompletionToldThroughCarriedByThisRunIdle",
1002 "ClassifyAgentCompletionToldThroughCarriedByThisRunAttached",
1003 "ClassifyAgentCompletionToldThroughCarriedByThisRunRunning",
1004 "ClassifyAgentCompletionToldThroughCarriedByThisRunRetired",
1005 "ClassifyAgentCompletionToldThroughCarriedByThisRunStopped",
1006 "ClassifyAgentCompletionToldThroughNotCarriedByThisRunIdle",
1007 "ClassifyAgentCompletionToldThroughNotCarriedByThisRunAttached",
1008 "ClassifyAgentCompletionToldThroughNotCarriedByThisRunRunning",
1009 "ClassifyAgentCompletionToldThroughNotCarriedByThisRunRetired",
1010 "ClassifyAgentCompletionToldThroughNotCarriedByThisRunStopped",
1011 "CarryAgentCompletionCursorSameRunIdle",
1012 "CarryAgentCompletionCursorSameRunAttached",
1013 "CarryAgentCompletionCursorSameRunRunning",
1014 "CarryAgentCompletionCursorSameRunRetired",
1015 "CarryAgentCompletionCursorSameRunStopped",
1016 "CarryAgentCompletionCursorNewRunIdle",
1017 "CarryAgentCompletionCursorNewRunAttached",
1018 "CarryAgentCompletionCursorNewRunRunning",
1019 "CarryAgentCompletionCursorNewRunRetired",
1020 "CarryAgentCompletionCursorNewRunStopped",
1021 "CommitAgentCarriedCompletionsCarriedIdle",
1022 "CommitAgentCarriedCompletionsCarriedAttached",
1023 "CommitAgentCarriedCompletionsCarriedRunning",
1024 "CommitAgentCarriedCompletionsCarriedRetired",
1025 "CommitAgentCarriedCompletionsCarriedStopped",
1026 "CommitAgentCarriedCompletionsNothingCarriedIdle",
1027 "CommitAgentCarriedCompletionsNothingCarriedAttached",
1028 "CommitAgentCarriedCompletionsNothingCarriedRunning",
1029 "CommitAgentCarriedCompletionsNothingCarriedRetired",
1030 "CommitAgentCarriedCompletionsNothingCarriedStopped",
1031 "ClassifyAgentCompletionCarryOutstandingOwedIdle",
1032 "ClassifyAgentCompletionCarryOutstandingOwedAttached",
1033 "ClassifyAgentCompletionCarryOutstandingOwedRunning",
1034 "ClassifyAgentCompletionCarryOutstandingOwedRetired",
1035 "ClassifyAgentCompletionCarryOutstandingOwedStopped",
1036 "ClassifyAgentCompletionCarryOutstandingSettledIdle",
1037 "ClassifyAgentCompletionCarryOutstandingSettledAttached",
1038 "ClassifyAgentCompletionCarryOutstandingSettledRunning",
1039 "ClassifyAgentCompletionCarryOutstandingSettledRetired",
1040 "ClassifyAgentCompletionCarryOutstandingSettledStopped",
1041 "KeepEmptyResumeForCarriedJobEndIdle",
1042 "KeepEmptyResumeForCarriedJobEndAttached",
1043 "KeepEmptyResumeForCarriedJobEndRunning",
1044 "KeepEmptyResumeForCarriedJobEndRetired",
1045 "KeepEmptyResumeForCarriedJobEndStopped",
1046 "AdmitUrgentOperatorNoticeIdle",
1050 "AdmitUrgentOperatorNoticeAttached",
1051 "AdmitUrgentOperatorNoticeRunning",
1052 "AdmitUrgentOperatorNoticeRetired",
1053 "AdmitUrgentOperatorNoticeStopped",
1054 "RecoverOperatorNoticeIdle",
1055 "RecoverOperatorNoticeAttached",
1056 "RecoverOperatorNoticeRunning",
1057 "RecoverOperatorNoticeRetired",
1058 "RecoverOperatorNoticeStopped",
1059 "RecoverInputAcknowledgementIdle",
1060 "RecoverInputAcknowledgementAttached",
1061 "RecoverInputAcknowledgementRunning",
1062 "RecoverInputAcknowledgementRetired",
1063 "RecoverInputAcknowledgementStopped",
1064 "AcknowledgeInputIdle",
1065 "AcknowledgeInputAttached",
1066 "AcknowledgeInputRunning",
1067 "AcknowledgeInputRetired",
1068 "AcknowledgeInputStopped",
1069 "AcknowledgeInputAlreadyAcknowledgedInitializing",
1070 "AcknowledgeInputAlreadyAcknowledgedIdle",
1071 "AcknowledgeInputAlreadyAcknowledgedAttached",
1072 "AcknowledgeInputAlreadyAcknowledgedRunning",
1073 "AcknowledgeInputAlreadyAcknowledgedRetired",
1074 "AcknowledgeInputAlreadyAcknowledgedStopped",
1075 "AcknowledgeInputAlreadyAcknowledgedDestroyed",
1076 "AcknowledgeInputNotToldInitializing",
1077 "AcknowledgeInputNotToldIdle",
1078 "AcknowledgeInputNotToldAttached",
1079 "AcknowledgeInputNotToldRunning",
1080 "AcknowledgeInputNotToldRetired",
1081 "AcknowledgeInputNotToldStopped",
1082 "AcknowledgeInputNotToldDestroyed",
1083 "AcknowledgeInputUntrackedInitializing",
1084 "AcknowledgeInputUntrackedIdle",
1085 "AcknowledgeInputUntrackedAttached",
1086 "AcknowledgeInputUntrackedRunning",
1087 "AcknowledgeInputUntrackedRetired",
1088 "AcknowledgeInputUntrackedStopped",
1089 "AcknowledgeInputUntrackedDestroyed",
1090 "AcknowledgeInputClosedInitializing",
1091 "AcknowledgeInputClosedDestroyed",
1092 "ClassifyCompletionNoticeOwedOwedIdle",
1096 "ClassifyCompletionNoticeOwedOwedAttached",
1097 "ClassifyCompletionNoticeOwedOwedRunning",
1098 "ClassifyCompletionNoticeOwedOwedRetired",
1099 "ClassifyCompletionNoticeOwedOwedStopped",
1100 "ClassifyCompletionNoticeOwedToldIdle",
1101 "ClassifyCompletionNoticeOwedToldAttached",
1102 "ClassifyCompletionNoticeOwedToldRunning",
1103 "ClassifyCompletionNoticeOwedToldRetired",
1104 "ClassifyCompletionNoticeOwedToldStopped",
1105 "ResolveRuntimeOpsLifecycleDurabilityForUntoldEndIdle",
1106 "ResolveRuntimeOpsLifecycleDurabilityForUntoldEndAttached",
1107 "ResolveRuntimeOpsLifecycleDurabilityForUntoldEndRunning",
1108 "ResolveRuntimeOpsLifecycleDurabilityForUntoldEndRetired",
1109 "ResolveRuntimeOpsLifecycleDurabilityForUntoldEndStopped",
1110 "PeerSendRecordedRecordingAIdle",
1113 "PeerSendRecordedRecordingAAttached",
1114 "PeerSendRecordedRecordingARunning",
1115 "PeerSendRecordedRecordingARetired",
1116 "PeerSendRecordedRecordingAStopped",
1117 "PeerSendRecordedRecordingBIdle",
1118 "PeerSendRecordedRecordingBAttached",
1119 "PeerSendRecordedRecordingBRunning",
1120 "PeerSendRecordedRecordingBRetired",
1121 "PeerSendRecordedRecordingBStopped",
1122 "PeerSendStateObservedInAIdle",
1123 "PeerSendStateObservedInAAttached",
1124 "PeerSendStateObservedInARunning",
1125 "PeerSendStateObservedInARetired",
1126 "PeerSendStateObservedInAStopped",
1127 "PeerSendStateObservedInBIdle",
1128 "PeerSendStateObservedInBAttached",
1129 "PeerSendStateObservedInBRunning",
1130 "PeerSendStateObservedInBRetired",
1131 "PeerSendStateObservedInBStopped",
1132 "RecordRecoveryDiscardedCursorInputInitializing",
1136 "RecordRecoveryDiscardedCursorInputIdle",
1137 "RecordRecoveryDiscardedCursorInputAttached",
1138 "ClassifyRecoveredOperationRecordToldFromRecordDiscardIdle",
1141 "ResolveLiveContextAppendAmbiguousRevokedIdle",
1142 "ResolveLiveContextAppendAmbiguousRevokedAttached",
1143 "ResolveLiveContextAppendAmbiguousRevokedRunning",
1144];
1145
1146#[cfg(not(test))]
1148struct RetiredTransitionVariant {
1149 name: &'static str,
1151 follows: &'static str,
1154}
1155
1156#[cfg(not(test))]
1165const MEERKAT_TRANSITION_ENUM_RETIRED: &[RetiredTransitionVariant] = &[
1166 RetiredTransitionVariant {
1167 name: "ResolveRuntimeCompletionCleanupRuntimeTerminatedIdle",
1168 follows: "ResolveRuntimeCompletionCleanupRuntimeTerminatedInitializing",
1169 },
1170 RetiredTransitionVariant {
1171 name: "ResolveRuntimeCompletionCleanupRuntimeTerminatedAttached",
1172 follows: "ResolveRuntimeCompletionCleanupRuntimeTerminatedIdle",
1173 },
1174 RetiredTransitionVariant {
1175 name: "ResolveRuntimeCompletionCleanupRuntimeTerminatedRunning",
1176 follows: "ResolveRuntimeCompletionCleanupRuntimeTerminatedAttached",
1177 },
1178];
1179
1180#[cfg(not(test))]
1186const MACHINE_TRANSITION_ENUM_LATE_TAILS: &[(&str, &[&str])] = &[
1187 (
1192 "SessionDocumentMachine",
1193 &[
1194 "ClassifyDurableTailContinuable",
1195 "RecoverSessionInstructionState",
1196 "RecoverSessionInstructionTarget",
1197 "RecoverSessionInstructionEffective",
1198 "RecordInstructionTargetAdvance",
1199 "RecordInstructionTargetActiveBudgetExceeded",
1200 "RecordInstructionTargetSlotLimitExceeded",
1201 "RecordInstructionTargetAlreadyRecorded",
1202 "RecordInstructionTargetOwnedBySession",
1203 "RecordInstructionTargetAdopt",
1204 "RecordInstructionTargetAdoptActiveBudgetExceeded",
1205 "RecordInstructionTargetAdoptSlotLimitExceeded",
1206 "RecordInstructionTargetOwnedByOtherMob",
1207 "SetSessionInstructionNew",
1208 "SetSessionInstructionAdvance",
1209 "SetSessionInstructionActiveBudgetExceeded",
1210 "SetSessionInstructionDuplicate",
1211 "SetSessionInstructionConflict",
1212 "SetSessionInstructionStale",
1213 "SetSessionInstructionOwnedByMob",
1214 "SetSessionInstructionMemberSession",
1215 "SetSessionInstructionSlotLimitExceeded",
1216 "SetSessionInstructionUnknownSlot",
1217 "RebindInstructionOwner",
1218 "RebindInstructionOwnerUnowned",
1219 "RebindInstructionOwnerMemberSession",
1220 "ReleaseInstructionTarget",
1221 "ReleaseInstructionTargetAlreadyUnowned",
1222 "ReleaseInstructionTargetOwnedByOtherMob",
1223 "ReleaseInstructionTargetOwnedBySession",
1224 "ResolveRunStartInstructionsApply",
1225 "ResolveRunStartInstructionsNoChange",
1226 "ResolveRunStartInstructionsDeferredLeadingPrefix",
1227 "ResolveRunStartInstructionsDeferredUnavailable",
1228 "AuthorizeInstructionFoldAtRunStart",
1229 "AuthorizeInstructionFoldEffective",
1230 "RecoverSessionActivationBodies",
1231 "AuthorizeActivationBodyRetirement",
1232 ],
1233 ),
1234 (
1235 "SessionTurnAdmissionMachine",
1236 &["ResolveDispositionResumeRun"],
1237 ),
1238 (
1239 "OccurrenceLifecycleMachine",
1240 &[
1241 "ClassifyDuePendingReclaimExhausted",
1242 "ClaimPendingAfterAdmission",
1243 "ClaimPendingAfterUnprovenDispatch",
1244 "TargetProbeBusyExistingRedelivery",
1245 "ReclaimExhaustedAfterAdmission",
1246 "ReclaimExhaustedAfterUnprovenDispatch",
1247 "UnprovenLateNotAdmittedFromClaimed",
1248 "UnprovenLateNotAdmittedFromDispatching",
1249 "ReleaseClaimBeforeDispatchFromClaimed",
1252 "ReleaseClaimBeforeDispatchAfterSupersession",
1253 "SupersedeByLaterDueFromPending",
1256 "PlanStandsForFromPending",
1257 "RecordReplacedDueTimesFromClaimed",
1258 "ConditionMetFromClaimed",
1261 "ConditionNotMetSkipsFromClaimed",
1262 ],
1263 ),
1264 (
1269 "MobMachine",
1270 &[
1271 "RetireMemberArchiveOnly",
1272 "AdmitDestroyMemberRetireArchiveOnlyRunning",
1273 "AdmitDestroyMemberRetireArchiveOnlyStopped",
1274 "WireExternalPeerDormantRunning",
1275 "WireExternalPeerAlreadyWiredDormant",
1276 "UnwireExternalPeerDormantRunning",
1277 "RetireRunningReleasingArchiveOnly",
1278 "RetireRunningPreservingBindingArchiveOnly",
1279 "RetireStoppedReleasingArchiveOnly",
1280 "RetireStoppedPreservingBindingArchiveOnly",
1281 "ResolveMemberRevivalSessionCreatedRunning",
1282 "ResolveMemberRevivalSessionCreatedStaleRunning",
1283 "ResolveMemberRevivalSessionCreatedStaleStopped",
1284 "ResolveMemberRevivalSessionCreatedStaleCompleted",
1285 "ResolveMemberRevivalSessionCreatedStaleDestroyed",
1286 "RecoverMemberSeatSessionUnbornRunning",
1287 "RecoverMemberSeatSessionBornRunning",
1288 "AuthorizeSpawnProfileSeatedRunning",
1289 "ExemptMemberFromDefinitionWiringSeatedRunning",
1290 "ExemptMemberFromDefinitionWiringSeatedStopped",
1291 "ProbeMemberAdmissionIdentityMemberRunning",
1295 "ProbeMemberAdmissionIdentityMemberStopped",
1296 "ProbeMemberAdmissionIdentityMemberCompleted",
1297 "ProbeMemberAdmissionIdentityMemberDestroyed",
1298 "RecoverIdentityEntrySeatedRunning",
1299 "RecoverIdentityEntrySeatedStopped",
1300 "AdoptLegacyIdentityEntryAdopted",
1301 "AdoptLegacyIdentityEntryNameHeldByWorker",
1302 "AdoptLegacyIdentityEntryNotAdoptable",
1303 "AdoptLegacyIdentityEntryStaleObservation",
1304 "AdoptLegacyIdentityEntryNotSeated",
1305 "AdoptLegacyIdentityEntryAlreadyAnEntry",
1306 "AdoptLegacyIdentityEntryNonAuthoritative",
1307 "AdoptLegacyIdentityEntryMobNotRunningStopped",
1308 "AdoptLegacyIdentityEntryMobNotRunningCompleted",
1309 "AdoptLegacyIdentityEntryMobNotRunningDestroyed",
1310 "ResolveAgentLaneMemberAdmissionAdmittedRunning",
1311 "ResolveAgentLaneMemberAdmissionAdmittedStopped",
1312 "ResolveAgentLaneMemberAdmissionAdmittedCompleted",
1313 "ResolveAgentLaneMemberAdmissionAdmittedDestroyed",
1314 "ResolveAgentLaneMemberAdmissionIdentityMemberRunning",
1315 "ResolveAgentLaneMemberAdmissionIdentityMemberStopped",
1316 "ResolveAgentLaneMemberAdmissionIdentityMemberCompleted",
1317 "ResolveAgentLaneMemberAdmissionIdentityMemberDestroyed",
1318 "BeginMemberRotationSameSessionRunning",
1322 "CommitMemberRotationSameSessionRunning",
1323 "CommitMemberRotationSameSessionStopped",
1324 "CommitMemberRotationSameSessionKickoffRunning",
1325 "CommitMemberRotationSameSessionKickoffStopped",
1326 "RecoverMemberRotationIntentFreshSessionRunning",
1327 "RecoverMemberRotationIntentSameSessionRunning",
1328 "RecoverMemberRotationIntentDestroyingRunning",
1329 "ClassifyMemberReleaseStaleRunning",
1330 "ClassifyMemberReleaseStaleStopped",
1331 "ClassifyMemberReleaseStaleCompleted",
1332 "ClassifyMemberReleaseStaleDestroyed",
1333 "RespawnIdentityEntryRefusedRunning",
1336 "RespawnIdentityEntryRefusedStopped",
1337 "RespawnIdentityEntryRefusedCompleted",
1338 "DeclareIdentityEntryKept",
1343 "DeclareIdentityEntrySeatOwed",
1344 "DeclareIdentityEntryHostedOnFirstUse",
1345 "DeclareIdentityEntryAwaitHeldCreation",
1346 "DeclareIdentityEntryRuntimeModeRestamp",
1347 "DeclareIdentityEntryRoleMigrate",
1348 "DeclareIdentityEntryRoleRotate",
1349 "DeclareIdentityEntryRoleMigrationHeld",
1350 "DeclareIdentityEntryLifecycleInFlight",
1351 "DeclareIdentityEntryRefusedNameHeldByWorker",
1352 "DeclareIdentityEntryRefusedHostAdopted",
1353 "DeclareIdentityEntryRefusedNonAuthoritative",
1354 "DeclareIdentityEntryMobNotRunningStopped",
1355 "DeclareIdentityEntryMobNotRunningCompleted",
1356 "DeclareIdentityEntryMobNotRunningDestroyed",
1357 "SealDeclaredRosterSealed",
1358 "SealDeclaredRosterNonAuthoritative",
1359 "SealDeclaredRosterMobNotRunningStopped",
1360 "SealDeclaredRosterMobNotRunningCompleted",
1361 "SealDeclaredRosterMobNotRunningDestroyed",
1362 "RecoverIdentityEntryRetiringMarkedRunning",
1363 "ForgetArchivedSession",
1364 "AuthorizeExplicitResumeMemberHeldRunning",
1367 "RecoverIdentityEntryRetiringStaleRunning",
1370 "OpenDeclaredApplyOpened",
1371 "OpenDeclaredApplyBusy",
1372 "OpenDeclaredApplyMobNotRunningStopped",
1373 "OpenDeclaredApplyMobNotRunningCompleted",
1374 "OpenDeclaredApplyMobNotRunningDestroyed",
1375 "CloseDeclaredApplyRunning",
1376 "CloseDeclaredApplyStopped",
1377 "CloseDeclaredApplyCompleted",
1378 "CloseDeclaredApplyDestroyed",
1379 "AdmitResetRunning",
1381 "AdmitResetStopped",
1382 "AdmitResetCompleted",
1383 "AuthorizeExplicitResumeMemberHeldStopped",
1386 "ProbeMemberAdmissionIdentityMemberOfAnotherOriginRunning",
1393 "ProbeMemberAdmissionIdentityMemberOfAnotherOriginStopped",
1394 "ProbeMemberAdmissionIdentityMemberOfAnotherOriginCompleted",
1395 "ProbeMemberAdmissionIdentityMemberOfAnotherOriginDestroyed",
1396 "ProbeMemberAdmissionIdentityNameReservedRunning",
1397 "ProbeMemberAdmissionIdentityNameReservedStopped",
1398 "ProbeMemberAdmissionIdentityNameReservedCompleted",
1399 "ProbeMemberAdmissionIdentityNameReservedDestroyed",
1400 "DeclareIdentityEntryRefusedNameOwnedByCreated",
1401 "DeclareIdentityEntryRefusedNameTombstoned",
1402 "DeclareIdentityEntryRefusedNameUnreadable",
1403 "AdoptLegacyIdentityEntryOtherCustody",
1404 "ResolveAgentLaneMemberAdmissionUnreadableNameRunning",
1405 "ResolveAgentLaneMemberAdmissionUnreadableNameStopped",
1406 "ResolveAgentLaneMemberAdmissionUnreadableNameCompleted",
1407 "ResolveAgentLaneMemberAdmissionUnreadableNameDestroyed",
1408 "RecoverCreatedIdentityEntrySeatedRunning",
1409 "RecoverCreatedIdentityEntrySeatedStopped",
1410 "RecoverCreatedIdentityEntryRetiredRunning",
1411 "RecoverCreatedIdentityEntryRetiredStopped",
1412 "RecoverCreatedIdentityEntryPendingRunning",
1413 "RecoverCreatedIdentityEntryPendingStopped",
1414 "RecoverCreatedIdentityEntryTombstoneRunning",
1415 "RecoverCreatedIdentityEntryTombstoneStopped",
1416 "RecoverCreatedIdentityEntryUnreadableRunning",
1417 "RecoverCreatedIdentityEntryUnreadableStopped",
1418 "RetireAbsentCompleted",
1422 "RetireAbsentDestroyed",
1423 "SetOperatorInstructionBodyTooLargeRunning",
1425 "SetOperatorInstructionBodyTooLargeStopped",
1426 "SetOperatorInstructionSlotLimitExceededRunning",
1427 "SetOperatorInstructionSlotLimitExceededStopped",
1428 "SetOperatorInstructionNewOverBudgetRunning",
1429 "SetOperatorInstructionNewOverBudgetStopped",
1430 "SetOperatorInstructionNewRunning",
1431 "SetOperatorInstructionNewStopped",
1432 "SetOperatorInstructionStaleRunning",
1433 "SetOperatorInstructionStaleStopped",
1434 "SetOperatorInstructionDuplicateRunning",
1435 "SetOperatorInstructionDuplicateStopped",
1436 "SetOperatorInstructionConflictRunning",
1437 "SetOperatorInstructionConflictStopped",
1438 "SetOperatorInstructionAdvanceOverBudgetRunning",
1439 "SetOperatorInstructionAdvanceOverBudgetStopped",
1440 "SetOperatorInstructionAdvanceRunning",
1441 "SetOperatorInstructionAdvanceStopped",
1442 "SetOperatorInstructionTerminalCompleted",
1443 "SetOperatorInstructionTerminalDestroyed",
1444 "RevokeOperatorInstructionUnknownSlotRunning",
1445 "RevokeOperatorInstructionUnknownSlotStopped",
1446 "RevokeOperatorInstructionStaleRunning",
1447 "RevokeOperatorInstructionStaleStopped",
1448 "RevokeOperatorInstructionDuplicateRunning",
1449 "RevokeOperatorInstructionDuplicateStopped",
1450 "RevokeOperatorInstructionConflictRunning",
1451 "RevokeOperatorInstructionConflictStopped",
1452 "RevokeOperatorInstructionAdvanceRunning",
1453 "RevokeOperatorInstructionAdvanceStopped",
1454 "RevokeOperatorInstructionTerminalCompleted",
1455 "RevokeOperatorInstructionTerminalDestroyed",
1456 "RecoverOperatorInstructionAppliedRunning",
1457 "RecoverOperatorInstructionAppliedStopped",
1458 "RecoverOperatorInstructionAppliedCompleted",
1459 "RecoverOperatorInstructionStaleRunning",
1460 "RecoverOperatorInstructionStaleStopped",
1461 "RecoverOperatorInstructionStaleCompleted",
1462 "RecoverOperatorInstructionGenerationHighwaterRaised",
1463 "RecoverOperatorInstructionGenerationHighwaterKept",
1464 "PrepareMemberInstructionDeliveryNotOwedRunning",
1465 "PrepareMemberInstructionDeliveryNotOwedStopped",
1466 "PrepareMemberInstructionDeliveryUnbornRunning",
1467 "PrepareMemberInstructionDeliveryUnbornStopped",
1468 "PrepareMemberInstructionDeliveryUnboundRunning",
1469 "PrepareMemberInstructionDeliveryUnboundStopped",
1470 "PrepareMemberInstructionDeliveryRetiringRunning",
1471 "PrepareMemberInstructionDeliveryRetiringStopped",
1472 "PrepareMemberInstructionDeliveryDeliverRunning",
1473 "PrepareMemberInstructionDeliveryDeliverStopped",
1474 "PrepareMemberInstructionDeliveryMobNotRunningCompleted",
1475 "PrepareMemberInstructionDeliveryMobNotRunningDestroyed",
1476 "RecordMemberInstructionTargetNotOwedRunning",
1477 "RecordMemberInstructionTargetNotOwedStopped",
1478 "RecordMemberInstructionTargetNotOwedCompleted",
1479 "RecordMemberInstructionTargetNotOwedDestroyed",
1480 "RecordMemberInstructionTargetStaleSessionRunning",
1481 "RecordMemberInstructionTargetStaleSessionStopped",
1482 "RecordMemberInstructionTargetStaleSessionCompleted",
1483 "RecordMemberInstructionTargetStaleSessionDestroyed",
1484 "RecordMemberInstructionTargetSupersededRunning",
1485 "RecordMemberInstructionTargetSupersededStopped",
1486 "RecordMemberInstructionTargetSupersededCompleted",
1487 "RecordMemberInstructionTargetSupersededDestroyed",
1488 "RecordMemberInstructionTargetCurrentRunning",
1489 "RecordMemberInstructionTargetCurrentStopped",
1490 "RecordMemberInstructionTargetCurrentCompleted",
1491 "RecordMemberInstructionTargetCurrentDestroyed",
1492 "RecordMemberInstructionTargetUnmintedRunning",
1493 "RecordMemberInstructionTargetUnmintedStopped",
1494 "RecordMemberInstructionTargetUnmintedCompleted",
1495 "RecordMemberInstructionTargetUnmintedDestroyed",
1496 "RefuseMemberInstructionTargetNotOwedRunning",
1497 "RefuseMemberInstructionTargetNotOwedStopped",
1498 "RefuseMemberInstructionTargetNotOwedCompleted",
1499 "RefuseMemberInstructionTargetNotOwedDestroyed",
1500 "RefuseMemberInstructionTargetStaleSessionRunning",
1501 "RefuseMemberInstructionTargetStaleSessionStopped",
1502 "RefuseMemberInstructionTargetStaleSessionCompleted",
1503 "RefuseMemberInstructionTargetStaleSessionDestroyed",
1504 "RefuseMemberInstructionTargetSupersededRunning",
1505 "RefuseMemberInstructionTargetSupersededStopped",
1506 "RefuseMemberInstructionTargetSupersededCompleted",
1507 "RefuseMemberInstructionTargetSupersededDestroyed",
1508 "RefuseMemberInstructionTargetBlockedRunning",
1509 "RefuseMemberInstructionTargetBlockedStopped",
1510 "RefuseMemberInstructionTargetBlockedCompleted",
1511 "RefuseMemberInstructionTargetBlockedDestroyed",
1512 "ResolveMemberInstructionReleaseAuthorizedRunning",
1513 "ResolveMemberInstructionReleaseAuthorizedStopped",
1514 "ResolveMemberInstructionReleaseAuthorizedCompleted",
1515 "ResolveMemberInstructionReleaseAuthorizedDestroyed",
1516 "ResolveMemberInstructionReleaseNotNeededRunning",
1517 "ResolveMemberInstructionReleaseNotNeededStopped",
1518 "ResolveMemberInstructionReleaseNotNeededCompleted",
1519 "ResolveMemberInstructionReleaseNotNeededDestroyed",
1520 "PrepareMemberInstructionDeliverySpawningRunning",
1521 "PrepareMemberInstructionDeliverySpawningStopped",
1522 "AdmitIdentityChangeAdmitted",
1525 "AdmitIdentityChangeReplayed",
1526 "AdmitIdentityChangeOperationReused",
1527 "AdmitIdentityChangeNonAuthoritative",
1528 "AdmitIdentityChangeChangesHeld",
1529 "AdmitIdentityChangeDecisionUnbound",
1530 "AdmitIdentityChangeDecisionExpired",
1531 "AdmitIdentityChangeImportedNotHostOperator",
1532 "AdmitIdentityChangeGrantRevoked",
1533 "AdmitIdentityChangeMobNotRunningStopped",
1534 "AdmitIdentityChangeMobNotRunningCompleted",
1535 "AdmitIdentityChangeMobNotRunningDestroyed",
1536 "RecordCreatedIdentityEntryRecorded",
1537 "RecordCreatedIdentityEntryNameHeldByIdentity",
1538 "RecordCreatedIdentityEntryNameHeldByWorker",
1539 "RecordCreatedIdentityEntryNameTombstoned",
1540 "RecordCreatedIdentityEntryNameUnreadable",
1541 "RecordCreatedIdentityEntryNonAuthoritative",
1542 "RecordCreatedIdentityEntryChangesHeld",
1543 "RecordCreatedIdentityEntryMobNotRunningStopped",
1544 "RecordCreatedIdentityEntryMobNotRunningCompleted",
1545 "RecordCreatedIdentityEntryMobNotRunningDestroyed",
1546 "SetIdentityChangesHeldRunning",
1547 "SetIdentityChangesHeldStopped",
1548 "SetIdentityChangesHeldCompleted",
1549 "SetIdentityChangesHeldDestroyed",
1550 "RemoveIdentityEntryRetiring",
1554 "RemoveIdentityEntryRemoved",
1555 "RemoveIdentityEntryAlreadyRemoved",
1556 "RemoveIdentityEntryUnknown",
1557 "RemoveIdentityEntryInFlight",
1558 "RemoveIdentityEntryNameUnreadable",
1559 "RemoveIdentityEntryNonAuthoritative",
1560 "RemoveIdentityEntryChangesHeld",
1561 "RemoveIdentityEntryMobNotRunningStopped",
1562 "RemoveIdentityEntryMobNotRunningCompleted",
1563 "RemoveIdentityEntryMobNotRunningDestroyed",
1564 "ArchiveIdentityEntryArchiving",
1565 "ArchiveIdentityEntryArchived",
1566 "ArchiveIdentityEntryAlreadyArchived",
1567 "ArchiveIdentityEntryOwnedByRoster",
1568 "ArchiveIdentityEntryUnknown",
1569 "ArchiveIdentityEntryInFlight",
1570 "ArchiveIdentityEntryNameUnreadable",
1571 "ArchiveIdentityEntryNonAuthoritative",
1572 "ArchiveIdentityEntryChangesHeld",
1573 "ArchiveIdentityEntryMobNotRunningStopped",
1574 "ArchiveIdentityEntryMobNotRunningCompleted",
1575 "ArchiveIdentityEntryMobNotRunningDestroyed",
1576 "UnarchiveIdentityEntryRestored",
1577 "UnarchiveIdentityEntryNotArchived",
1578 "UnarchiveIdentityEntryOwnedByRoster",
1579 "UnarchiveIdentityEntryUnknown",
1580 "UnarchiveIdentityEntryInFlight",
1581 "UnarchiveIdentityEntryNameUnreadable",
1582 "UnarchiveIdentityEntryNonAuthoritative",
1583 "UnarchiveIdentityEntryChangesHeld",
1584 "UnarchiveIdentityEntryMobNotRunningStopped",
1585 "UnarchiveIdentityEntryMobNotRunningCompleted",
1586 "UnarchiveIdentityEntryMobNotRunningDestroyed",
1587 "RecoverCreatedIdentityEntryRemovingRunning",
1588 "RecoverCreatedIdentityEntryRemovingStopped",
1589 "RecoverCreatedIdentityEntryArchivingRunning",
1590 "RecoverCreatedIdentityEntryArchivingStopped",
1591 "RecoverCreatedIdentityEntryArchivedRunning",
1592 "RecoverCreatedIdentityEntryArchivedStopped",
1593 "AdmitIdentityChangeStaleSpec",
1596 "DeclareIdentityEntryPreparationPending",
1600 "BeginPreparationConstructionHeld",
1601 "BeginPreparationConstructionNotPending",
1602 "BeginPreparationConstructionNotConstructed",
1603 "BeginPreparationConstructionConstructionOpen",
1604 "BeginPreparationConstructionNonAuthoritative",
1605 "BeginPreparationConstructionMobNotRunningStopped",
1606 "BeginPreparationConstructionMobNotRunningCompleted",
1607 "BeginPreparationConstructionMobNotRunningDestroyed",
1608 "SettleHostPreparationSeat",
1609 "SettleHostPreparationActivationAccepted",
1610 "SettleHostPreparationNotPending",
1611 "SettleHostPreparationConstructionRequired",
1612 "SettleHostPreparationConstructionOpen",
1613 "SettleHostPreparationStaleAttempt",
1614 "SettleHostPreparationExpired",
1615 "SettleHostPreparationMismatch",
1616 "SettleHostPreparationActivationPending",
1617 "SettleHostPreparationNonAuthoritative",
1618 "SettleHostPreparationMobNotRunningStopped",
1619 "SettleHostPreparationMobNotRunningCompleted",
1620 "SettleHostPreparationMobNotRunningDestroyed",
1621 "EndPreparationConstructionEndedRunning",
1622 "EndPreparationConstructionEndedStopped",
1623 "EndPreparationConstructionEndedCompleted",
1624 "EndPreparationConstructionEndedDestroyed",
1625 "EndPreparationConstructionNotOpenRunning",
1626 "EndPreparationConstructionNotOpenStopped",
1627 "EndPreparationConstructionNotOpenCompleted",
1628 "EndPreparationConstructionNotOpenDestroyed",
1629 "EndPreparationConstructionActivationPendingRunning",
1630 "EndPreparationConstructionActivationPendingStopped",
1631 "EndPreparationConstructionActivationPendingCompleted",
1632 "EndPreparationConstructionActivationPendingDestroyed",
1633 "ArchiveIdentityEntryPreparationPending",
1638 "DeclareIdentityEntryRecordOnly",
1639 "UnlistIdentityEntryRetiring",
1640 "UnlistIdentityEntryRemoved",
1641 "UnlistIdentityEntryDeferred",
1642 "UnlistIdentityEntryNotADeclaredEntry",
1643 "UnlistIdentityEntryNonAuthoritative",
1644 "UnlistIdentityEntryMobNotRunningStopped",
1645 "UnlistIdentityEntryMobNotRunningCompleted",
1646 "UnlistIdentityEntryMobNotRunningDestroyed",
1647 "AdoptLegacyIdentityEntryAdoptedUnlisted",
1651 "AdoptLegacyIdentityEntryRetireUnadopted",
1652 "ObserveMemberRetirementArchivedLiveHostAdopted",
1656 "ObserveMemberRetirementArchivedRetiredHostAdopted",
1657 "TakeOverIdentityEntryAdopting",
1658 "TakeOverIdentityEntryEnded",
1659 "TakeOverIdentityEntryDeferred",
1660 "TakeOverIdentityEntryNotADeclaredEntry",
1661 "TakeOverIdentityEntryNonAuthoritative",
1662 "TakeOverIdentityEntryMobNotRunningStopped",
1663 "TakeOverIdentityEntryMobNotRunningCompleted",
1664 "TakeOverIdentityEntryMobNotRunningDestroyed",
1665 "RecoverIdentityEntryAdoptingMarkedRunning",
1666 "RecoverIdentityEntryAdoptingStaleRunning",
1667 "ResolveMemberRevivalRetryableBuildPreparationRunning",
1670 "ResolveMemberBuildPreparationRunning",
1671 "ResolveMemberBuildPreparationStopped",
1672 "ResolveMemberBuildPreparationCompleted",
1673 "DeclareOwnedIdentityEdgeDeclared",
1677 "DeclareOwnedIdentityEdgeAlreadyOwned",
1678 "DeclareOwnedIdentityEdgePeerUnknown",
1679 "DeclareOwnedIdentityEdgeOwnerInvalid",
1680 "DeclareOwnedIdentityEdgeMobNotRunningStopped",
1681 "DeclareOwnedIdentityEdgeMobNotRunningCompleted",
1682 "DeclareOwnedIdentityEdgeMobNotRunningDestroyed",
1683 "EndOwnedIdentityEdgeEnded",
1684 "EndOwnedIdentityEdgeNotOwner",
1685 "EndOwnedIdentityEdgeAbsent",
1686 "EndOwnedIdentityEdgeNonAuthoritative",
1687 "EndOwnedIdentityEdgeChangesHeld",
1688 "EndOwnedIdentityEdgeMobNotRunningStopped",
1689 "EndOwnedIdentityEdgeMobNotRunningCompleted",
1690 "EndOwnedIdentityEdgeMobNotRunningDestroyed",
1691 "AdmitMemberUnwireAdmittedRunning",
1692 "AdmitMemberUnwireAdmittedStopped",
1693 "AdmitMemberUnwireAdmittedCompleted",
1694 "AdmitMemberUnwireAdmittedDestroyed",
1695 "AdmitMemberUnwireOwnedEdgeRunning",
1696 "AdmitMemberUnwireOwnedEdgeStopped",
1697 "AdmitMemberUnwireOwnedEdgeCompleted",
1698 "AdmitMemberUnwireOwnedEdgeDestroyed",
1699 "RecoverOwnedIdentityEdgeRecoveredRunning",
1700 "RecoverOwnedIdentityEdgeRecoveredStopped",
1701 "RecoverOwnedIdentityEdgeSkippedRunning",
1702 "RecoverOwnedIdentityEdgeSkippedStopped",
1703 "AdoptIdentityIntoStoreAdopted",
1705 "AdoptIdentityIntoStoreNotAdoptable",
1706 "AdoptIdentityIntoStorePredecessorMismatch",
1707 "AdoptIdentityIntoStoreAdmissionUnsettled",
1708 "AdoptIdentityIntoStoreDeclaredApplyOpen",
1709 "AdoptIdentityIntoStoreNameUnreadable",
1710 "AdoptIdentityIntoStoreNameTombstoned",
1711 "AdoptIdentityIntoStoreNonAuthoritative",
1712 "AdoptIdentityIntoStoreChangesHeld",
1713 "AdoptIdentityIntoStoreMobNotRunningStopped",
1714 "AdoptIdentityIntoStoreMobNotRunningCompleted",
1715 "AdoptIdentityIntoStoreMobNotRunningDestroyed",
1716 "AdmitIdentityChangeRowsPurged",
1720 "PurgeIdentityRowsPurged",
1721 "PurgeIdentityRowsNonAuthoritative",
1722 "PurgeIdentityRowsReplayed",
1723 "PurgeIdentityRowsOperationReused",
1724 "PurgeIdentityRowsRowsPurged",
1725 "PurgeIdentityRowsNotHostOperator",
1726 "PurgeIdentityRowsChangesNotHeld",
1727 "PurgeIdentityRowsMobNotRunningStopped",
1728 "PurgeIdentityRowsMobNotRunningCompleted",
1729 "PurgeIdentityRowsMobNotRunningDestroyed",
1730 "RecoverRowlessCreatedEntryReservedRunning",
1731 "RecoverRowlessCreatedEntryReservedStopped",
1732 "RecoverRowlessCreatedEntryKeptRunning",
1733 "RecoverRowlessCreatedEntryKeptStopped",
1734 "ImportIdentityRecordRestoredInPlace",
1735 "ImportIdentityRecordRestoredOwedSeat",
1736 "ImportIdentityRecordRestoredPending",
1737 "ImportIdentityRecordRestoredArchived",
1738 "ImportIdentityRecordRestoredTombstone",
1739 "ImportIdentityRecordRestoredByAdoption",
1740 "ImportIdentityRecordUnchanged",
1741 "ImportIdentityRecordNameTakenMeanwhile",
1742 "ImportIdentityRecordUnsettled",
1743 "ImportIdentityRecordNonAuthoritative",
1744 "ImportIdentityRecordChangesHeld",
1745 "ImportIdentityRecordRowsPurged",
1746 "ImportIdentityRecordMobNotRunningStopped",
1747 "ImportIdentityRecordMobNotRunningCompleted",
1748 "ImportIdentityRecordMobNotRunningDestroyed",
1749 "AdmitOwnedEdgeRealizationRealizeRunning",
1753 "AdmitOwnedEdgeRealizationRealizeStopped",
1754 "AdmitOwnedEdgeRealizationRealizeCompleted",
1755 "AdmitOwnedEdgeRealizationRealizeDestroyed",
1756 "AdmitOwnedEdgeRealizationNotOwnedRunning",
1757 "AdmitOwnedEdgeRealizationNotOwnedStopped",
1758 "AdmitOwnedEdgeRealizationNotOwnedCompleted",
1759 "AdmitOwnedEdgeRealizationNotOwnedDestroyed",
1760 "AdmitOwnedEdgeRealizationEndNotAnIdentityRunning",
1761 "AdmitOwnedEdgeRealizationEndNotAnIdentityStopped",
1762 "AdmitOwnedEdgeRealizationEndNotAnIdentityCompleted",
1763 "AdmitOwnedEdgeRealizationEndNotAnIdentityDestroyed",
1764 "RestoreOwnedIdentityEdgeRestored",
1765 "RestoreOwnedIdentityEdgeSkipped",
1766 "RestoreOwnedIdentityEdgeMobNotRunningStopped",
1767 "RestoreOwnedIdentityEdgeMobNotRunningCompleted",
1768 "RestoreOwnedIdentityEdgeMobNotRunningDestroyed",
1769 "PurgeIdentityRowsNothingToPurge",
1770 "SealDeclaredRosterRefused",
1773 "ObserveRespawnTopologyAbandonedStaleEndedSuccessor",
1776 "ResolveMemberDispatchAdmissionAskHostRunning",
1779 "ResolveMemberDispatchAdmissionAskHostStopped",
1780 "ResolveMemberDispatchAdmissionAskHostCompleted",
1781 "ResolveMemberDispatchAdmissionAskHostDestroyed",
1782 "ResolveMemberDispatchAdmissionInheritRunning",
1783 "ResolveMemberDispatchAdmissionInheritStopped",
1784 "ResolveMemberDispatchAdmissionInheritCompleted",
1785 "ResolveMemberDispatchAdmissionInheritDestroyed",
1786 "ResolveMemberDispatchAdmissionRefusedRunning",
1787 "ResolveMemberDispatchAdmissionRefusedStopped",
1788 "ResolveMemberDispatchAdmissionRefusedCompleted",
1789 "ResolveMemberDispatchAdmissionRefusedDestroyed",
1790 "ResolveMemberDispatchAdmissionNoneRequiredRunning",
1791 "ResolveMemberDispatchAdmissionNoneRequiredStopped",
1792 "ResolveMemberDispatchAdmissionNoneRequiredCompleted",
1793 "ResolveMemberDispatchAdmissionNoneRequiredDestroyed",
1794 "RecordMemberDispatchAdmissionLineageRunning",
1797 "RecordMemberDispatchAdmissionLineageStopped",
1798 "EndIdentityLifeRunning",
1801 "EndIdentityLifeStopped",
1802 "EndIdentityLifeCompleted",
1803 "EndIdentityLifeDestroyed",
1804 "RecoverIdentityLifeResetsRunning",
1805 "RecoverIdentityLifeResetsStopped",
1806 "RecoverIdentityLifeResetsCompleted",
1807 "RecoverIdentityLifeResetsDestroyed",
1808 "ResolveSubmitWorkRejectionIdentityMember",
1811 "ResolveSubmitWorkRejectionIdentityMemberUnreadableName",
1812 "SetOperatorInstructionAdvanceSlotLimitExceededRunning",
1816 "SetOperatorInstructionAdvanceSlotLimitExceededStopped",
1817 "RecordMemberInstructionLineageRunning",
1820 "RecordMemberInstructionLineageStopped",
1821 "AuthorizeExternalPeerReciprocalTrustRemovalRunning",
1825 "AuthorizeExternalPeerReciprocalTrustRemovalStopped",
1826 "ResolvePeerWakeAdmissionRunning",
1829 "BeginMemberReleaseCloseRunning",
1833 "BeginMemberReleaseCloseStopped",
1834 "BeginMemberReleaseCloseCompleted",
1835 "ResolveMemberReleaseClosedRunning",
1836 "ResolveMemberReleaseClosedStopped",
1837 "ResolveMemberReleaseClosedCompleted",
1838 "ResolveMemberReleaseClosedStaleRunning",
1839 "ResolveMemberReleaseClosedStaleStopped",
1840 "ResolveMemberReleaseClosedStaleCompleted",
1841 "ResolveMemberReleaseClosedStaleDestroyed",
1842 "EndMemberReleaseCloseRunning",
1843 "EndMemberReleaseCloseStopped",
1844 "EndMemberReleaseCloseCompleted",
1845 "EndMemberReleaseCloseDestroyed",
1846 "ClearOwnerArchiveCleanupRunning",
1850 "ClearOwnerArchiveCleanupNothingToClear",
1851 "RecoverOwnerArchiveCleanupClearedRunning",
1852 "ClearOwnerArchiveCleanupLifecycleQuiescing",
1855 "MarkMemberOperationOwnerEndedRunning",
1861 "MarkMemberOperationOwnerEndedNoChange",
1862 "UnmarkMemberOperationOwnerEndedRunning",
1863 "UnmarkMemberOperationOwnerEndedNoChange",
1864 "ReleaseMemberOperationOwnerRecorded",
1865 "ReleaseMemberOperationOwnerNothingRecorded",
1866 "RecoverMemberOperationOwnerEndedRunning",
1867 "RecoverMemberReleasedFromOperationOwnerRunning",
1868 "RecoverMemberOperationOwnerEndNotAppliedRunning",
1869 "RecoverMemberSessionBindingFreshOwnerEndedRunning",
1870 "RecoverMemberSessionBindingReplacingOwnerEndedRunning",
1871 "RecoverMemberSessionBindingAlreadyCurrentOwnerEndedRunning",
1872 "RecoverMemberSeatBeganRunning",
1876 "ClassifyMemberLiveMaterializationOperationOwnerEndedRunning",
1877 "WakeMemberOperationOwnerEndedRunning",
1882 "MarkMemberOperationOwnerEndedStopped",
1883 "MarkMemberOperationOwnerEndedNoChangeStopped",
1884 "UnmarkMemberOperationOwnerEndedStopped",
1885 "UnmarkMemberOperationOwnerEndedNoChangeStopped",
1886 "ReleaseMemberOperationOwnerRecordedStopped",
1887 "ReleaseMemberOperationOwnerNothingRecordedStopped",
1888 "MarkMemberOperationOwnerEndedCompleted",
1889 "MarkMemberOperationOwnerEndedNoChangeCompleted",
1890 "UnmarkMemberOperationOwnerEndedCompleted",
1891 "UnmarkMemberOperationOwnerEndedNoChangeCompleted",
1892 "ReleaseMemberOperationOwnerRecordedCompleted",
1893 "ReleaseMemberOperationOwnerNothingRecordedCompleted",
1894 "RecoverMemberOperationOwnerEndedCompleted",
1895 "RecoverMemberReleasedFromOperationOwnerCompleted",
1896 "RecoverMemberOperationOwnerEndNotAppliedCompleted",
1897 "AuthorizeExplicitResumeMemberOperationOwnerEndedRunning",
1902 "AuthorizeExplicitResumeMemberOperationOwnerEndedStopped",
1903 "RecoverMemberSeatBeganCompleted",
1904 "RecordExplicitResumeMemberOperationOwnerEndedDormantRunning",
1910 "RecordExplicitResumeMemberOperationOwnerEndedDormantNoChangeRunning",
1911 "RecordExplicitResumeMemberOperationOwnerEndedDormantStopped",
1912 "RecordExplicitResumeMemberOperationOwnerEndedDormantNoChangeStopped",
1913 "BeginPlacedMemberRetirementQuiesceRunning",
1917 "BeginPlacedMemberRetirementQuiesceStopped",
1918 "ResolvePlacedMemberRetirementQuiesceRunning",
1919 "ResolvePlacedMemberRetirementQuiesceStopped",
1920 ],
1921 ),
1922 (
1928 "ToolGrantLifecycleMachine",
1929 &[
1930 "EndWithSubjectActive",
1931 "EndWithSubjectAfterDeadline",
1932 "EndWithSubjectSettledExpired",
1933 "EndWithSubjectSettledRevoked",
1934 "AdmitEndedWithSubject",
1935 "EndWithSubjectSettledRunEnded",
1936 ],
1937 ),
1938 (
1942 "ApprovalLifecycleMachine",
1943 &[
1944 "AdmitEnteredStepRejectedMissing",
1945 "AdmitEnteredStepRejectedConsentLinked",
1946 "AdmitEnteredStepRejectedRetired",
1947 "AdmitEnteredStepRejectedNotEntered",
1948 "AdmitEnteredStep",
1949 "AdmitEnteredStepRejectedClosing",
1950 "ReleaseReviewUsedClosing",
1951 "ReleaseReviewRejectedClosing",
1952 "FinishEnteredStepRejectedMissing",
1953 "FinishEnteredStepRejectedNotInFlight",
1954 "FinishEnteredStepOpen",
1955 "FinishEnteredStepClosing",
1956 "FinishEnteredStepReleases",
1957 ],
1958 ),
1959];
1960
1961#[cfg(not(test))]
1962fn transitions_in_public_enum_order(
1963 schema: &MachineSchema,
1964) -> Result<Vec<&TransitionSchema>, MachineKernelRenderError> {
1965 if schema.machine.as_ref() != "MeerkatMachine" {
1966 let late_names = MACHINE_TRANSITION_ENUM_LATE_TAILS
1967 .iter()
1968 .find(|(machine, _)| *machine == schema.machine.as_ref())
1969 .map_or(&[][..], |(_, names)| *names);
1970 let mut ordered: Vec<&TransitionSchema> = schema
1971 .transitions
1972 .iter()
1973 .filter(|transition| !late_names.contains(&transition.name.as_ref()))
1974 .collect();
1975 for expected_name in late_names {
1976 let transition = schema
1977 .transitions
1978 .iter()
1979 .find(|transition| transition.name.as_ref() == *expected_name)
1980 .ok_or_else(|| MachineKernelRenderError::MissingPublicTransitionTail {
1981 transition: (*expected_name).to_owned(),
1982 })?;
1983 ordered.push(transition);
1984 }
1985 return Ok(ordered);
1986 }
1987
1988 let named_transitions = |names: &[&str]| {
1989 names
1990 .iter()
1991 .map(|expected_name| {
1992 schema
1993 .transitions
1994 .iter()
1995 .find(|transition| transition.name.as_ref() == *expected_name)
1996 .ok_or_else(|| MachineKernelRenderError::MissingPublicTransitionTail {
1997 transition: (*expected_name).to_owned(),
1998 })
1999 })
2000 .collect::<Result<Vec<_>, _>>()
2001 };
2002 let compatibility_tail = named_transitions(MEERKAT_TRANSITION_ENUM_TAIL)?;
2003 let late_tail = named_transitions(MEERKAT_TRANSITION_ENUM_LATE_TAIL)?;
2004 let listed_in_a_tail = |transition: &TransitionSchema| {
2005 MEERKAT_TRANSITION_ENUM_TAIL.contains(&transition.name.as_ref())
2006 || MEERKAT_TRANSITION_ENUM_LATE_TAIL.contains(&transition.name.as_ref())
2007 };
2008 let input_position = |transition: &TransitionSchema| match &transition.on {
2009 meerkat_machine_schema::TriggerMatch::Input { variant, .. } => schema
2010 .inputs
2011 .variants
2012 .iter()
2013 .position(|input| input.name.as_str() == variant.as_str()),
2014 meerkat_machine_schema::TriggerMatch::Signal { .. } => None,
2015 };
2016 let compatibility_input_end = compatibility_tail
2020 .iter()
2021 .filter_map(|transition| input_position(transition))
2022 .max();
2023 let appended_section_last = schema
2024 .inputs
2025 .variants
2026 .iter()
2027 .position(|input| input.name.as_str() == MEERKAT_APPENDED_INPUT_SECTION_LAST)
2028 .ok_or_else(
2029 || MachineKernelRenderError::MissingAppendedInputSectionLast {
2030 input: MEERKAT_APPENDED_INPUT_SECTION_LAST.to_owned(),
2031 },
2032 )?;
2033 let appended_input_transition = |transition: &TransitionSchema| {
2034 compatibility_input_end
2035 .zip(input_position(transition))
2036 .is_some_and(|(end, position)| position > end)
2037 };
2038 if let Some(unlisted) = schema.transitions.iter().find(|transition| {
2039 input_position(transition).is_some_and(|position| position > appended_section_last)
2040 && !MEERKAT_TRANSITION_ENUM_LATE_TAIL.contains(&transition.name.as_ref())
2041 }) {
2042 return Err(MachineKernelRenderError::UnlistedLateTransition {
2043 transition: unlisted.name.as_ref().to_owned(),
2044 });
2045 }
2046 let mut ordered = Vec::with_capacity(schema.transitions.len());
2047 ordered.extend(schema.transitions.iter().filter(|transition| {
2048 !listed_in_a_tail(transition) && !appended_input_transition(transition)
2049 }));
2050 ordered.extend(compatibility_tail);
2051 ordered.extend(schema.transitions.iter().filter(|transition| {
2052 !listed_in_a_tail(transition) && appended_input_transition(transition)
2053 }));
2054 ordered.extend(late_tail);
2055 if ordered.len() != schema.transitions.len() {
2056 return Err(MachineKernelRenderError::NonUniquePublicTransitionTail {
2057 rendered: ordered.len(),
2058 schema: schema.transitions.len(),
2059 });
2060 }
2061 Ok(ordered)
2062}
2063
2064#[cfg(not(test))]
2066enum PublicTransitionVariant<'a> {
2067 Live(&'a TransitionSchema),
2069 Retired(&'static str),
2072}
2073
2074#[cfg(not(test))]
2080fn public_transition_enum_variants(
2081 schema: &MachineSchema,
2082) -> Result<Vec<PublicTransitionVariant<'_>>, MachineKernelRenderError> {
2083 let mut variants: Vec<PublicTransitionVariant<'_>> = transitions_in_public_enum_order(schema)?
2084 .into_iter()
2085 .map(PublicTransitionVariant::Live)
2086 .collect();
2087 if schema.machine.as_ref() != "MeerkatMachine" {
2088 return Ok(variants);
2089 }
2090 for retired in MEERKAT_TRANSITION_ENUM_RETIRED {
2091 if schema
2092 .transitions
2093 .iter()
2094 .any(|transition| transition.name.as_ref() == retired.name)
2095 {
2096 return Err(MachineKernelRenderError::RetiredTransitionStillLive {
2097 transition: retired.name.to_owned(),
2098 });
2099 }
2100 let follows = variants
2101 .iter()
2102 .position(|variant| match variant {
2103 PublicTransitionVariant::Live(transition) => {
2104 transition.name.as_ref() == retired.follows
2105 }
2106 PublicTransitionVariant::Retired(name) => *name == retired.follows,
2107 })
2108 .ok_or_else(
2109 || MachineKernelRenderError::RetiredTransitionFollowsUnknown {
2110 transition: retired.name.to_owned(),
2111 follows: retired.follows.to_owned(),
2112 },
2113 )?;
2114 variants.insert(follows + 1, PublicTransitionVariant::Retired(retired.name));
2115 }
2116 Ok(variants)
2117}
2118
2119#[cfg(not(test))]
2120fn render_canonical_stub_modeled_module(
2121 schema: &MachineSchema,
2122) -> Result<String, MachineKernelRenderError> {
2123 let mut out = String::new();
2124 let module_name = machine_slug(&schema.machine);
2125 let catalog_fn = format!("catalog::dsl::dsl_{module_name}_machine");
2126 let has_signals = !schema.signals.variants.is_empty();
2127
2128 pushln!(
2129 &mut out,
2130 "// @generated — Generated by `cargo xtask machine-codegen --all`."
2131 );
2132 pushln!(
2133 &mut out,
2134 "#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::implicit_clone, clippy::unnecessary_cast, clippy::redundant_clone, clippy::zero_sized_map_values)]"
2135 );
2136 pushln!(&mut out);
2137 pushln!(
2138 &mut out,
2139 "pub fn schema() -> meerkat_machine_schema::MachineSchema {{"
2140 );
2141 pushln!(&mut out, " meerkat_machine_schema::{catalog_fn}()");
2142 pushln!(&mut out, "}}");
2143 pushln!(&mut out);
2144
2145 let named_type_aliases = collect_machine_named_types(schema);
2146 if !named_type_aliases.is_empty() {
2147 for alias in named_type_aliases {
2148 if let Some(atom) = lookup_named_type_atom(schema, &alias) {
2149 render_named_type_definition(&mut out, &alias, atom);
2150 }
2151 }
2152 pushln!(&mut out);
2153 }
2154
2155 pushln!(&mut out, "pub trait Context {{}}");
2156 pushln!(&mut out, "pub struct EmptyContext;");
2157 pushln!(&mut out, "impl Context for EmptyContext {{}}");
2158 pushln!(&mut out);
2159
2160 pushln!(&mut out, "#[allow(non_camel_case_types)]");
2161 pushln!(
2162 &mut out,
2163 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2164 );
2165 pushln!(&mut out, "pub enum Phase {{");
2166 for variant in &schema.state.phase.variants {
2167 pushln!(&mut out, " {},", rust_ident(&variant.name));
2168 }
2169 pushln!(&mut out, "}}");
2170 pushln!(&mut out);
2171
2172 render_value_derive(&mut out, "", &schema.state.fields);
2173 pushln!(&mut out, "pub struct State {{");
2174 pushln!(&mut out, " pub phase: Phase,");
2175 for field in &schema.state.fields {
2176 pushln!(
2177 &mut out,
2178 " pub {}: {},",
2179 rust_field_ident(&field.name),
2180 render_rust_type_ref(&field.ty)
2181 );
2182 }
2183 pushln!(&mut out, "}}");
2184 render_redacted_debug_impl(&mut out, "", "State", &["phase"], &schema.state.fields);
2185 pushln!(&mut out, "impl Default for State {{");
2186 pushln!(&mut out, " fn default() -> Self {{");
2187 pushln!(&mut out, " initial_state()");
2188 pushln!(&mut out, " }}");
2189 pushln!(&mut out, "}}");
2190 pushln!(&mut out);
2191
2192 pushln!(&mut out, "pub mod inputs {{");
2193 pushln!(&mut out, " #[allow(unused_imports)]");
2194 pushln!(&mut out, " use super::*;");
2195 for variant in &schema.inputs.variants {
2196 render_value_derive(&mut out, " ", &variant.fields);
2197 pushln!(&mut out, " pub struct {} {{", rust_ident(&variant.name));
2198 for field in &variant.fields {
2199 pushln!(
2200 &mut out,
2201 " pub {}: {},",
2202 rust_field_ident(&field.name),
2203 render_rust_type_ref(&field.ty)
2204 );
2205 }
2206 pushln!(&mut out, " }}");
2207 render_redacted_debug_impl(
2208 &mut out,
2209 " ",
2210 &rust_ident(&variant.name),
2211 &[],
2212 &variant.fields,
2213 );
2214 }
2215 pushln!(&mut out, "}}");
2216 pushln!(&mut out);
2217 pushln!(
2218 &mut out,
2219 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2220 );
2221 pushln!(&mut out, "pub enum Input {{");
2222 for variant in &schema.inputs.variants {
2223 pushln!(
2224 &mut out,
2225 " {}(inputs::{}),",
2226 rust_ident(&variant.name),
2227 rust_ident(&variant.name)
2228 );
2229 }
2230 pushln!(&mut out, "}}");
2231 pushln!(&mut out, "impl Input {{");
2232 pushln!(&mut out, " pub fn kind(&self) -> InputKind {{");
2233 pushln!(&mut out, " match self {{");
2234 for variant in &schema.inputs.variants {
2235 pushln!(
2236 &mut out,
2237 " Self::{}(_) => InputKind::{},",
2238 rust_ident(&variant.name),
2239 rust_ident(&variant.name)
2240 );
2241 }
2242 pushln!(&mut out, " }}");
2243 pushln!(&mut out, " }}");
2244 pushln!(&mut out, "}}");
2245 pushln!(
2246 &mut out,
2247 "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2248 );
2249 pushln!(&mut out, "pub enum InputKind {{");
2250 for variant in &schema.inputs.variants {
2251 pushln!(&mut out, " {},", rust_ident(&variant.name));
2252 }
2253 pushln!(&mut out, "}}");
2254 pushln!(&mut out);
2255
2256 if has_signals {
2257 pushln!(&mut out, "pub mod signals {{");
2258 pushln!(&mut out, " #[allow(unused_imports)]");
2259 pushln!(&mut out, " use super::*;");
2260 for variant in &schema.signals.variants {
2261 render_value_derive(&mut out, " ", &variant.fields);
2262 pushln!(&mut out, " pub struct {} {{", rust_ident(&variant.name));
2263 for field in &variant.fields {
2264 pushln!(
2265 &mut out,
2266 " pub {}: {},",
2267 rust_field_ident(&field.name),
2268 render_rust_type_ref(&field.ty)
2269 );
2270 }
2271 pushln!(&mut out, " }}");
2272 render_redacted_debug_impl(
2273 &mut out,
2274 " ",
2275 &rust_ident(&variant.name),
2276 &[],
2277 &variant.fields,
2278 );
2279 }
2280 pushln!(&mut out, "}}");
2281 pushln!(&mut out);
2282 pushln!(
2283 &mut out,
2284 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2285 );
2286 pushln!(&mut out, "pub enum Signal {{");
2287 for variant in &schema.signals.variants {
2288 pushln!(
2289 &mut out,
2290 " {}(signals::{}),",
2291 rust_ident(&variant.name),
2292 rust_ident(&variant.name)
2293 );
2294 }
2295 pushln!(&mut out, "}}");
2296 pushln!(&mut out, "impl Signal {{");
2297 pushln!(&mut out, " pub fn kind(&self) -> SignalKind {{");
2298 pushln!(&mut out, " match self {{");
2299 for variant in &schema.signals.variants {
2300 pushln!(
2301 &mut out,
2302 " Self::{}(_) => SignalKind::{},",
2303 rust_ident(&variant.name),
2304 rust_ident(&variant.name)
2305 );
2306 }
2307 pushln!(&mut out, " }}");
2308 pushln!(&mut out, " }}");
2309 pushln!(&mut out, "}}");
2310 pushln!(
2311 &mut out,
2312 "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2313 );
2314 pushln!(&mut out, "pub enum SignalKind {{");
2315 for variant in &schema.signals.variants {
2316 pushln!(&mut out, " {},", rust_ident(&variant.name));
2317 }
2318 pushln!(&mut out, "}}");
2319 pushln!(&mut out);
2320 }
2321
2322 pushln!(&mut out, "pub mod effects {{");
2323 pushln!(&mut out, " #[allow(unused_imports)]");
2324 pushln!(&mut out, " use super::*;");
2325 for variant in &schema.effects.variants {
2326 render_value_derive(&mut out, " ", &variant.fields);
2327 pushln!(&mut out, " pub struct {} {{", rust_ident(&variant.name));
2328 for field in &variant.fields {
2329 pushln!(
2330 &mut out,
2331 " pub {}: {},",
2332 rust_field_ident(&field.name),
2333 render_rust_type_ref(&field.ty)
2334 );
2335 }
2336 pushln!(&mut out, " }}");
2337 render_redacted_debug_impl(
2338 &mut out,
2339 " ",
2340 &rust_ident(&variant.name),
2341 &[],
2342 &variant.fields,
2343 );
2344 }
2345 pushln!(&mut out, "}}");
2346 pushln!(&mut out);
2347 pushln!(
2348 &mut out,
2349 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2350 );
2351 pushln!(&mut out, "pub enum Effect {{");
2352 for variant in &schema.effects.variants {
2353 pushln!(
2354 &mut out,
2355 " {}(effects::{}),",
2356 rust_ident(&variant.name),
2357 rust_ident(&variant.name)
2358 );
2359 }
2360 pushln!(&mut out, "}}");
2361 pushln!(
2362 &mut out,
2363 "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2364 );
2365 pushln!(&mut out, "pub enum EffectKind {{");
2366 for variant in &schema.effects.variants {
2367 pushln!(&mut out, " {},", rust_ident(&variant.name));
2368 }
2369 pushln!(&mut out, "}}");
2370 pushln!(&mut out);
2371
2372 render_command_capability_section(&mut out, schema);
2373
2374 pushln!(&mut out, "#[allow(non_camel_case_types)]");
2375 pushln!(
2376 &mut out,
2377 "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2378 );
2379 pushln!(&mut out, "pub enum TransitionId {{");
2380 for variant in public_transition_enum_variants(schema)? {
2381 match variant {
2382 PublicTransitionVariant::Live(transition) => {
2383 pushln!(&mut out, " {},", rust_ident(&transition.name));
2384 }
2385 PublicTransitionVariant::Retired(name) => {
2386 pushln!(
2387 &mut out,
2388 " /// Retired: never fired. No transition has this id any more; the"
2389 );
2390 pushln!(
2391 &mut out,
2392 " /// variant keeps its place so that no published discriminant moves."
2393 );
2394 pushln!(&mut out, " {name},");
2395 }
2396 }
2397 }
2398 pushln!(&mut out, "}}");
2399 pushln!(&mut out, "#[allow(non_camel_case_types)]");
2400 pushln!(
2401 &mut out,
2402 "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2403 );
2404 pushln!(&mut out, "pub enum GuardId {{");
2405 pushln!(&mut out, " None,");
2406 pushln!(&mut out, "}}");
2407 pushln!(&mut out, "#[allow(non_camel_case_types)]");
2408 pushln!(
2409 &mut out,
2410 "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2411 );
2412 pushln!(&mut out, "pub enum HelperId {{");
2413 pushln!(&mut out, " None,");
2414 pushln!(&mut out, "}}");
2415 pushln!(&mut out);
2416 pushln!(
2417 &mut out,
2418 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2419 );
2420 pushln!(&mut out, "pub struct GuardRejection {{");
2421 pushln!(&mut out, " pub transition_id: TransitionId,");
2422 pushln!(&mut out, " pub guard_id: GuardId,");
2423 pushln!(&mut out, "}}");
2424 pushln!(
2425 &mut out,
2426 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2427 );
2428 pushln!(&mut out, "pub enum TriggerDiscriminant {{");
2429 pushln!(&mut out, " Input(InputKind),");
2430 if has_signals {
2431 pushln!(&mut out, " Signal(SignalKind),");
2432 }
2433 pushln!(&mut out, "}}");
2434 pushln!(
2435 &mut out,
2436 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2437 );
2438 pushln!(&mut out, "pub enum TransitionRefusal {{");
2439 pushln!(
2440 &mut out,
2441 " NoMatchingTransition {{ phase: Phase, trigger: TriggerDiscriminant }},"
2442 );
2443 pushln!(
2444 &mut out,
2445 " GuardRejected {{ rejections: Vec<GuardRejection> }},"
2446 );
2447 pushln!(
2448 &mut out,
2449 " AmbiguousTransition {{ transitions: Vec<TransitionId> }},"
2450 );
2451 pushln!(&mut out, "}}");
2452 pushln!(
2453 &mut out,
2454 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2455 );
2456 pushln!(&mut out, "pub enum KernelError {{");
2457 pushln!(
2458 &mut out,
2459 " ContextViolation {{ transition_id: TransitionId, detail: String }},"
2460 );
2461 pushln!(
2462 &mut out,
2463 " HelperEvaluation {{ helper_id: HelperId, detail: String }},"
2464 );
2465 pushln!(&mut out, " CodegenInvariant {{ detail: String }},");
2466 pushln!(&mut out, "}}");
2467 pushln!(
2468 &mut out,
2469 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2470 );
2471 pushln!(&mut out, "pub enum TransitionError {{");
2472 pushln!(&mut out, " Refusal(TransitionRefusal),");
2473 pushln!(&mut out, " Kernel(KernelError),");
2474 pushln!(&mut out, "}}");
2475 pushln!(
2476 &mut out,
2477 "#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
2478 );
2479 pushln!(&mut out, "pub struct Outcome {{");
2480 pushln!(&mut out, " pub transition_id: TransitionId,");
2481 pushln!(&mut out, " pub next_state: State,");
2482 pushln!(&mut out, " pub effects: Vec<Effect>,");
2483 pushln!(&mut out, "}}");
2484 pushln!(&mut out);
2485 pushln!(&mut out, "pub mod helpers {{");
2486 pushln!(&mut out, " #[allow(unused_imports)]");
2487 pushln!(&mut out, " use super::*;");
2488 pushln!(
2489 &mut out,
2490 " pub fn none<C: Context>(_: &State, context: &C) -> Result<(), KernelError> {{"
2491 );
2492 pushln!(&mut out, " let _ = context;");
2493 pushln!(&mut out, " Ok(())");
2494 pushln!(&mut out, " }}");
2495 pushln!(&mut out, "}}");
2496 pushln!(&mut out);
2497
2498 let init_phase = rust_ident(schema.state.init.phase.as_str());
2499 pushln!(&mut out, "pub fn initial_state() -> State {{");
2500 pushln!(&mut out, " State {{");
2501 pushln!(&mut out, " phase: Phase::{init_phase},");
2502 for field in &schema.state.fields {
2503 let init_expr = schema
2504 .state
2505 .init
2506 .fields
2507 .iter()
2508 .find(|item| item.field == field.name)
2509 .map(|item| rust_initial_value_expr(&item.expr, &field.ty))
2510 .unwrap_or_else(|| direct_default_value_expr(&field.ty));
2511 pushln!(
2512 &mut out,
2513 " {}: {},",
2514 rust_field_ident(&field.name),
2515 init_expr
2516 );
2517 }
2518 pushln!(&mut out, " }}");
2519 pushln!(&mut out, "}}");
2520 Ok(out)
2521}
2522
2523#[cfg(not(test))]
2524fn render_command_capability_section(out: &mut String, schema: &MachineSchema) {
2525 if schema.command_plans.is_empty() {
2526 return;
2527 }
2528
2529 pushln!(out, "pub mod command_capabilities {{");
2530 pushln!(out, " mod private {{");
2531 pushln!(out, " #[derive(Debug, PartialEq, Eq)]");
2532 pushln!(out, " pub struct Sealed;");
2533 pushln!(out, " }}");
2534 pushln!(out);
2535
2536 pushln!(out, " #[derive(Debug, Clone, Copy, PartialEq, Eq)]");
2537 pushln!(out, " pub enum CommandPlanKind {{");
2538 for plan in &schema.command_plans {
2539 pushln!(out, " {},", rust_ident(&plan.name));
2540 }
2541 pushln!(out, " }}");
2542 pushln!(out);
2543 pushln!(out, " impl CommandPlanKind {{");
2544 pushln!(out, " #[must_use]");
2545 pushln!(out, " pub const fn as_str(self) -> &'static str {{");
2546 pushln!(out, " match self {{");
2547 for plan in &schema.command_plans {
2548 pushln!(
2549 out,
2550 " Self::{} => {:?},",
2551 rust_ident(&plan.name),
2552 plan.name
2553 );
2554 }
2555 pushln!(out, " }}");
2556 pushln!(out, " }}");
2557 pushln!(out, " }}");
2558 pushln!(out);
2559
2560 if schema
2561 .command_plans
2562 .iter()
2563 .any(|plan| plan.authority_type == "AuthorizedRuntimeLoopBatch")
2564 {
2565 pushln!(out, " #[derive(Debug, Clone, Copy, PartialEq, Eq)]");
2566 pushln!(out, " pub enum RuntimeLoopBatchSource {{");
2567 pushln!(out, " Queue,");
2568 pushln!(out, " Steer,");
2569 pushln!(out, " }}");
2570 pushln!(out);
2571 pushln!(
2572 out,
2573 " /// The most inputs one runtime-loop batch stages into a run: the bound of"
2574 );
2575 pushln!(
2576 out,
2577 " /// the one terminal-completion batch a run's commit names."
2578 );
2579 pushln!(
2580 out,
2581 " pub const RUNTIME_LOOP_BATCH_MAX_INPUTS: usize = {};",
2582 meerkat_machine_schema::catalog::dsl::meerkat_machine::command_capabilities::RUNTIME_LOOP_BATCH_MAX_INPUTS
2583 );
2584 pushln!(out);
2585 pushln!(
2586 out,
2587 " #[must_use = \"generated runtime-loop batch plan must be consumed by exact dequeue/stage realization\"]"
2588 );
2589 pushln!(out, " #[derive(Debug, PartialEq, Eq)]");
2590 pushln!(out, " pub struct RuntimeLoopBatchPlan {{");
2591 pushln!(out, " batch_capability: AuthorizedRuntimeLoopBatch,");
2592 pushln!(out, " input_ids: Vec<String>,");
2593 pushln!(out, " source: RuntimeLoopBatchSource,");
2594 pushln!(out, " }}");
2595 pushln!(out);
2596 pushln!(
2597 out,
2598 " #[must_use = \"generated stage-for-run plan must be consumed by exact stage realization\"]"
2599 );
2600 pushln!(out, " #[derive(Debug, PartialEq, Eq)]");
2601 pushln!(out, " pub struct StageForRunPlan {{");
2602 pushln!(out, " stage_capability: AuthorizedStageForRun,");
2603 pushln!(out, " input_ids: Vec<String>,");
2604 pushln!(out, " source: RuntimeLoopBatchSource,");
2605 pushln!(out, " }}");
2606 pushln!(out);
2607 pushln!(out, " impl RuntimeLoopBatchPlan {{");
2608 pushln!(out, " #[must_use]");
2609 pushln!(out, " pub fn input_ids(&self) -> &[String] {{");
2610 pushln!(out, " &self.input_ids");
2611 pushln!(out, " }}");
2612 pushln!(out);
2613 pushln!(out, " #[must_use]");
2614 pushln!(
2615 out,
2616 " pub const fn source(&self) -> RuntimeLoopBatchSource {{"
2617 );
2618 pushln!(out, " self.source");
2619 pushln!(out, " }}");
2620 pushln!(out);
2621 pushln!(
2622 out,
2623 " pub fn into_parts(self) -> (AuthorizedRuntimeLoopBatch, Vec<String>, RuntimeLoopBatchSource) {{"
2624 );
2625 pushln!(
2626 out,
2627 " (self.batch_capability, self.input_ids, self.source)"
2628 );
2629 pushln!(out, " }}");
2630 pushln!(out, " }}");
2631 pushln!(out);
2632 pushln!(out, " impl StageForRunPlan {{");
2633 pushln!(out, " #[must_use]");
2634 pushln!(out, " pub fn input_ids(&self) -> &[String] {{");
2635 pushln!(out, " &self.input_ids");
2636 pushln!(out, " }}");
2637 pushln!(out);
2638 pushln!(out, " #[must_use]");
2639 pushln!(
2640 out,
2641 " pub const fn source(&self) -> RuntimeLoopBatchSource {{"
2642 );
2643 pushln!(out, " self.source");
2644 pushln!(out, " }}");
2645 pushln!(out);
2646 pushln!(
2647 out,
2648 " pub fn into_parts(self) -> (AuthorizedStageForRun, Vec<String>, RuntimeLoopBatchSource) {{"
2649 );
2650 pushln!(
2651 out,
2652 " (self.stage_capability, self.input_ids, self.source)"
2653 );
2654 pushln!(out, " }}");
2655 pushln!(out, " }}");
2656 pushln!(out);
2657 }
2658
2659 for plan in &schema.command_plans {
2660 let type_name = rust_ident(&plan.authority_type);
2661 let kind_name = rust_ident(&plan.name);
2662 pushln!(
2663 out,
2664 " #[must_use = {:?}]",
2665 format!(
2666 "generated command capability `{}` must be consumed by the shell action it authorizes",
2667 plan.authority_type
2668 )
2669 );
2670 pushln!(out, " #[derive(Debug, PartialEq, Eq)]");
2671 pushln!(out, " pub struct {type_name} {{");
2672 pushln!(out, " _sealed: private::Sealed,");
2673 pushln!(out, " }}");
2674 pushln!(out);
2675 pushln!(out, " impl {type_name} {{");
2676 pushln!(out, " #[doc(hidden)]");
2677 pushln!(out, " #[allow(dead_code)]");
2678 pushln!(
2679 out,
2680 " pub(crate) fn mint_from_generated_command_plan() -> Self {{"
2681 );
2682 pushln!(out, " Self {{ _sealed: private::Sealed }}");
2683 pushln!(out, " }}");
2684 pushln!(out);
2685 pushln!(out, " #[must_use]");
2686 pushln!(
2687 out,
2688 " pub const fn plan(&self) -> CommandPlanKind {{"
2689 );
2690 pushln!(out, " CommandPlanKind::{kind_name}");
2691 pushln!(out, " }}");
2692 pushln!(out, " }}");
2693 pushln!(out);
2694 }
2695
2696 if schema
2697 .command_plans
2698 .iter()
2699 .any(|plan| plan.authority_type == "AuthorizedRuntimeLoopBatch")
2700 {
2701 pushln!(out, " impl AuthorizedRuntimeLoopBatch {{");
2702 pushln!(out, " #[must_use]");
2703 pushln!(
2704 out,
2705 " pub fn authorize_runtime_loop_batch_from_state(state: &super::State) -> Option<RuntimeLoopBatchPlan> {{"
2706 );
2707 pushln!(
2708 out,
2709 " runtime_loop_batch_from_state(state, super::InputLane::Steer, RuntimeLoopBatchSource::Steer)"
2710 );
2711 pushln!(
2712 out,
2713 " .or_else(|| runtime_loop_batch_from_state(state, super::InputLane::Queue, RuntimeLoopBatchSource::Queue))"
2714 );
2715 pushln!(out, " }}");
2716 pushln!(out, " }}");
2717 pushln!(out);
2718 pushln!(out, " impl AuthorizedStageForRun {{");
2719 pushln!(out, " #[must_use]");
2720 pushln!(
2721 out,
2722 " pub fn authorize_stage_for_run_from_state(state: &super::State, input_ids: &[String], run_id: &super::RunId, source: RuntimeLoopBatchSource) -> Option<StageForRunPlan> {{"
2723 );
2724 pushln!(
2725 out,
2726 " runtime_stage_for_run_from_state(state, input_ids, run_id, source)"
2727 );
2728 pushln!(out, " }}");
2729 pushln!(out, " }}");
2730 pushln!(out);
2731 pushln!(out, " fn runtime_loop_batch_from_state(");
2732 pushln!(out, " state: &super::State,");
2733 pushln!(out, " lane: super::InputLane,");
2734 pushln!(out, " source: RuntimeLoopBatchSource,");
2735 pushln!(out, " ) -> Option<RuntimeLoopBatchPlan> {{");
2736 pushln!(
2737 out,
2738 " // A kept governed input held for its controller is never selected: later work of its lane goes first."
2739 );
2740 pushln!(
2741 out,
2742 " let ordered: Vec<String> = ordered_queued_lane_inputs(state, lane)?.into_iter().filter(|input_id| !state.input_controller_holds.contains(input_id)).collect();"
2743 );
2744 pushln!(out, " let first = ordered.first()?;");
2745 pushln!(
2746 out,
2747 " // AppendContentAndRun owns exactly one SystemNotice per run."
2748 );
2749 pushln!(
2750 out,
2751 " let selected = if state.input_runtime_peer_response_terminal_apply_intent.get(first) == Some(&super::RecoveredPeerResponseTerminalApplyIntent::AppendContentAndRun) {{"
2752 );
2753 pushln!(out, " vec![first.clone()]");
2754 pushln!(out, " }} else {{");
2755 pushln!(out, " match source {{");
2756 pushln!(
2757 out,
2758 " RuntimeLoopBatchSource::Steer => select_steer_batch(state, &ordered, first),"
2759 );
2760 pushln!(
2761 out,
2762 " RuntimeLoopBatchSource::Queue => select_queue_batch(state, &ordered, first),"
2763 );
2764 pushln!(out, " }}");
2765 pushln!(out, " }};");
2766 pushln!(out, " if selected.is_empty() {{");
2767 pushln!(out, " None");
2768 pushln!(out, " }} else {{");
2769 pushln!(out, " Some(RuntimeLoopBatchPlan {{");
2770 pushln!(
2771 out,
2772 " batch_capability: AuthorizedRuntimeLoopBatch::mint_from_generated_command_plan(),"
2773 );
2774 pushln!(out, " input_ids: selected,");
2775 pushln!(out, " source,");
2776 pushln!(out, " }})");
2777 pushln!(out, " }}");
2778 pushln!(out, " }}");
2779 pushln!(out);
2780 pushln!(out, " fn runtime_stage_for_run_from_state(");
2781 pushln!(out, " state: &super::State,");
2782 pushln!(out, " input_ids: &[String],");
2783 pushln!(out, " run_id: &super::RunId,");
2784 pushln!(out, " source: RuntimeLoopBatchSource,");
2785 pushln!(out, " ) -> Option<StageForRunPlan> {{");
2786 pushln!(out, " if input_ids.is_empty() {{");
2787 pushln!(out, " return None;");
2788 pushln!(out, " }}");
2789 pushln!(
2790 out,
2791 " // A separately requested stage must preserve terminal-response cardinality."
2792 );
2793 pushln!(
2794 out,
2795 " 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)) {{"
2796 );
2797 pushln!(out, " return None;");
2798 pushln!(out, " }}");
2799 pushln!(
2800 out,
2801 " if state.current_run_id.as_ref() != Some(run_id) {{"
2802 );
2803 pushln!(out, " return None;");
2804 pushln!(out, " }}");
2805 pushln!(out, " let expected_lane = match source {{");
2806 pushln!(
2807 out,
2808 " RuntimeLoopBatchSource::Queue => super::InputLane::Queue,"
2809 );
2810 pushln!(
2811 out,
2812 " RuntimeLoopBatchSource::Steer => super::InputLane::Steer,"
2813 );
2814 pushln!(out, " }};");
2815 pushln!(out, " for input_id in input_ids {{");
2816 pushln!(
2817 out,
2818 " if state.input_phases.get(input_id) != Some(&super::InputPhase::Queued) {{"
2819 );
2820 pushln!(out, " return None;");
2821 pushln!(out, " }}");
2822 pushln!(
2823 out,
2824 " if state.input_lane.get(input_id) != Some(&expected_lane) {{"
2825 );
2826 pushln!(out, " return None;");
2827 pushln!(out, " }}");
2828 pushln!(
2829 out,
2830 " if !state.input_admission_seq.contains_key(input_id) {{"
2831 );
2832 pushln!(out, " return None;");
2833 pushln!(out, " }}");
2834 pushln!(
2835 out,
2836 " if !state.input_recovery_lanes.contains_key(input_id) {{"
2837 );
2838 pushln!(out, " return None;");
2839 pushln!(out, " }}");
2840 pushln!(
2841 out,
2842 " if state.input_run_associations.contains_key(input_id) {{"
2843 );
2844 pushln!(out, " return None;");
2845 pushln!(out, " }}");
2846 pushln!(
2847 out,
2848 " // Mirrors the StageForRun `input_controller_not_held` guard."
2849 );
2850 pushln!(
2851 out,
2852 " if state.input_controller_holds.contains(input_id) {{"
2853 );
2854 pushln!(out, " return None;");
2855 pushln!(out, " }}");
2856 pushln!(out, " }}");
2857 pushln!(out, " Some(StageForRunPlan {{");
2858 pushln!(
2859 out,
2860 " stage_capability: AuthorizedStageForRun::mint_from_generated_command_plan(),"
2861 );
2862 pushln!(out, " input_ids: input_ids.to_vec(),");
2863 pushln!(out, " source,");
2864 pushln!(out, " }})");
2865 pushln!(out, " }}");
2866 pushln!(out);
2867 pushln!(out, " fn ordered_queued_lane_inputs(");
2868 pushln!(out, " state: &super::State,");
2869 pushln!(out, " lane: super::InputLane,");
2870 pushln!(out, " ) -> Option<Vec<String>> {{");
2871 pushln!(out, " let mut ordered = Vec::new();");
2872 pushln!(
2873 out,
2874 " for (input_id, input_lane) in &state.input_lane {{"
2875 );
2876 pushln!(out, " if *input_lane != lane {{");
2877 pushln!(out, " continue;");
2878 pushln!(out, " }}");
2879 pushln!(
2880 out,
2881 " if state.input_phases.get(input_id) != Some(&super::InputPhase::Queued) {{"
2882 );
2883 pushln!(out, " return None;");
2884 pushln!(out, " }}");
2885 pushln!(
2886 out,
2887 " let sequence = *state.input_admission_seq.get(input_id)?;"
2888 );
2889 pushln!(
2890 out,
2891 " ordered.push((sequence, input_id.clone()));"
2892 );
2893 pushln!(out, " }}");
2894 pushln!(
2895 out,
2896 " ordered.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));"
2897 );
2898 pushln!(
2899 out,
2900 " Some(ordered.into_iter().map(|(_, input_id)| input_id).collect())"
2901 );
2902 pushln!(out, " }}");
2903 pushln!(out);
2904 pushln!(out, " fn select_steer_batch(");
2905 pushln!(out, " state: &super::State,");
2906 pushln!(out, " ordered: &[String],");
2907 pushln!(out, " first: &String,");
2908 pushln!(out, " ) -> Vec<String> {{");
2909 pushln!(
2910 out,
2911 " let Some(target_boundary) = state.input_runtime_boundary.get(first).copied() else {{"
2912 );
2913 pushln!(out, " return vec![first.clone()];");
2914 pushln!(out, " }};");
2915 pushln!(
2916 out,
2917 " let Some(target_execution_kind) = state.input_runtime_execution_kind.get(first).copied() else {{"
2918 );
2919 pushln!(out, " return vec![first.clone()];");
2920 pushln!(out, " }};");
2921 pushln!(out, " let target_terminal_intent = state");
2922 pushln!(
2923 out,
2924 " .input_runtime_peer_response_terminal_apply_intent"
2925 );
2926 pushln!(out, " .get(first)");
2927 pushln!(out, " .copied();");
2928 pushln!(out, " ordered");
2929 pushln!(out, " .iter()");
2930 pushln!(out, " .take_while(|input_id| {{");
2931 pushln!(
2932 out,
2933 " state.input_runtime_boundary.get(*input_id).copied() == Some(target_boundary)"
2934 );
2935 pushln!(
2936 out,
2937 " && state.input_runtime_execution_kind.get(*input_id).copied()"
2938 );
2939 pushln!(
2940 out,
2941 " == Some(target_execution_kind)"
2942 );
2943 pushln!(out, " && state");
2944 pushln!(
2945 out,
2946 " .input_runtime_peer_response_terminal_apply_intent"
2947 );
2948 pushln!(out, " .get(*input_id)");
2949 pushln!(out, " .copied()");
2950 pushln!(out, " == target_terminal_intent");
2951 pushln!(out, " }})");
2952 pushln!(out, " .take(RUNTIME_LOOP_BATCH_MAX_INPUTS)");
2953 pushln!(out, " .cloned()");
2954 pushln!(out, " .collect()");
2955 pushln!(out, " }}");
2956 pushln!(out);
2957 pushln!(out, " fn select_queue_batch(");
2958 pushln!(out, " state: &super::State,");
2959 pushln!(out, " ordered: &[String],");
2960 pushln!(out, " first: &String,");
2961 pushln!(out, " ) -> Vec<String> {{");
2962 pushln!(
2963 out,
2964 " let Some(target_execution_kind) = state.input_runtime_execution_kind.get(first).copied() else {{"
2965 );
2966 pushln!(out, " return vec![first.clone()];");
2967 pushln!(out, " }};");
2968 pushln!(out, " let target_terminal_intent = state");
2969 pushln!(
2970 out,
2971 " .input_runtime_peer_response_terminal_apply_intent"
2972 );
2973 pushln!(out, " .get(first)");
2974 pushln!(out, " .copied();");
2975 pushln!(
2976 out,
2977 " let Some(driver_is_prompt) = state.input_is_prompt.get(first).copied() else {{"
2978 );
2979 pushln!(out, " return vec![first.clone()];");
2980 pushln!(out, " }};");
2981 pushln!(out, " let mut selected = Vec::new();");
2982 pushln!(out, " for input_id in ordered {{");
2983 pushln!(
2984 out,
2985 " if selected.len() == RUNTIME_LOOP_BATCH_MAX_INPUTS {{"
2986 );
2987 pushln!(out, " break;");
2988 pushln!(out, " }}");
2989 pushln!(
2990 out,
2991 " if state.input_runtime_execution_kind.get(input_id).copied()"
2992 );
2993 pushln!(out, " != Some(target_execution_kind)");
2994 pushln!(out, " || state");
2995 pushln!(
2996 out,
2997 " .input_runtime_peer_response_terminal_apply_intent"
2998 );
2999 pushln!(out, " .get(input_id)");
3000 pushln!(out, " .copied()");
3001 pushln!(out, " != target_terminal_intent");
3002 pushln!(out, " {{");
3003 pushln!(out, " break;");
3004 pushln!(out, " }}");
3005 pushln!(
3006 out,
3007 " let Some(is_prompt) = state.input_is_prompt.get(input_id).copied() else {{"
3008 );
3009 pushln!(out, " break;");
3010 pushln!(out, " }};");
3011 pushln!(out, " if !driver_is_prompt && is_prompt {{");
3012 pushln!(out, " break;");
3013 pushln!(out, " }}");
3014 pushln!(out, " selected.push(input_id.clone());");
3015 pushln!(out, " if is_prompt || driver_is_prompt {{");
3016 pushln!(out, " break;");
3017 pushln!(out, " }}");
3018 pushln!(out, " }}");
3019 pushln!(out, " selected");
3020 pushln!(out, " }}");
3021 pushln!(out);
3022 }
3023 pushln!(out, "}}");
3024 pushln!(out);
3025}
3026
3027#[cfg(not(test))]
3028fn direct_default_value_expr(ty: &TypeRef) -> String {
3029 match ty {
3030 TypeRef::Bool => "false".to_string(),
3031 TypeRef::U32 | TypeRef::U64 => "0".to_string(),
3032 TypeRef::String => "String::new()".to_string(),
3033 TypeRef::Named(name) => format!("{}::default()", rust_ident(name.as_str())),
3034 TypeRef::Enum(name) => format!("{}::default()", rust_ident(name.as_str())),
3035 TypeRef::Option(_) => "None".to_string(),
3036 TypeRef::Set(_) => "Default::default()".to_string(),
3037 TypeRef::Seq(_) => "Vec::new()".to_string(),
3038 TypeRef::Map(_, _) => "Default::default()".to_string(),
3039 }
3040}
3041
3042#[cfg(not(test))]
3043fn rust_initial_value_expr(expr: &Expr, ty: &TypeRef) -> String {
3044 match expr {
3045 Expr::Bool(value) => value.to_string(),
3046 Expr::U64(value) => value.to_string(),
3047 Expr::U64Max => "u64::MAX".to_string(),
3048 Expr::String(value) => match ty {
3049 TypeRef::Named(name) => {
3050 format!("{}({value:?}.to_string())", rust_ident(name.as_str()))
3051 }
3052 _ => format!("{value:?}.to_string()"),
3053 },
3054 Expr::NamedVariant { enum_name, variant } => {
3055 format!(
3056 "{}::{}",
3057 rust_ident(enum_name.as_str()),
3058 rust_ident(variant.as_str())
3059 )
3060 }
3061 Expr::EmptySet | Expr::EmptyMap => direct_default_value_expr(ty),
3062 Expr::SeqLiteral(items) => {
3063 let inner = match ty {
3064 TypeRef::Seq(inner) => inner.as_ref(),
3065 other => other,
3066 };
3067 format!(
3068 "vec![{}]",
3069 items
3070 .iter()
3071 .map(|item| rust_initial_value_expr(item, inner))
3072 .collect::<Vec<_>>()
3073 .join(", ")
3074 )
3075 }
3076 Expr::None => "None".to_string(),
3077 Expr::Some(inner) => {
3078 let inner_ty = match ty {
3079 TypeRef::Option(inner_ty) => inner_ty.as_ref(),
3080 other => other,
3081 };
3082 format!("Some({})", rust_initial_value_expr(inner, inner_ty))
3083 }
3084 Expr::Phase(value) => format!("Phase::{}", rust_ident(value.as_str())),
3085 other => {
3086 let message =
3087 format!("unsupported generated kernel state initializer expression: {other:?}");
3088 format!("{{ compile_error!({message:?}); Default::default() }}")
3089 }
3090 }
3091}
3092
3093#[cfg(not(test))]
3094pub fn render_generated_kernel_mod(schemas: &[MachineSchema]) -> String {
3095 let mut out = String::new();
3096 pushln!(
3097 &mut out,
3098 "// @generated — Generated by `cargo xtask machine-codegen --all`."
3099 );
3100 let mut module_slugs: Vec<_> = schemas
3101 .iter()
3102 .map(|schema| machine_slug(&schema.machine))
3103 .collect();
3104 module_slugs.sort();
3105 for slug in module_slugs {
3106 pushln!(&mut out, "pub mod {slug};");
3107 }
3108 out
3109}
3110
3111#[cfg(not(test))]
3112fn render_semantic_mapping_section(
3113 out: &mut String,
3114 heading: &str,
3115 entries: &[SemanticCoverageEntry],
3116) {
3117 pushln!(out, "### {heading}");
3118 if entries.is_empty() {
3119 pushln!(out, "- `(none)`");
3120 out.push('\n');
3121 return;
3122 }
3123
3124 for entry in entries {
3125 pushln!(out, "- `{}`", entry.name);
3126 pushln!(
3127 out,
3128 " - anchors: {}",
3129 render_semantic_id_list(&entry.anchor_ids)
3130 );
3131 pushln!(
3132 out,
3133 " - scenarios: {}",
3134 render_semantic_id_list(&entry.scenario_ids)
3135 );
3136 }
3137 out.push('\n');
3138}
3139
3140#[cfg(not(test))]
3143fn render_semantic_id_list(ids: &[String]) -> String {
3144 if ids.is_empty() {
3145 return "(unclaimed)".to_owned();
3146 }
3147 ids.iter()
3148 .map(|id| format!("`{id}`"))
3149 .collect::<Vec<_>>()
3150 .join(", ")
3151}
3152
3153#[cfg(not(test))]
3154fn machine_slug(machine_name: impl AsRef<str>) -> String {
3155 let machine_name = machine_name.as_ref();
3156 let trimmed = machine_name.strip_suffix("Machine").unwrap_or(machine_name);
3157 to_snake_case(trimmed)
3158}
3159
3160#[cfg(not(test))]
3161fn to_snake_case(value: &str) -> String {
3162 let mut out = String::new();
3163 let mut previous_is_sep = true;
3164
3165 for ch in value.chars() {
3166 if ch == '_' || ch == '-' || ch == ' ' {
3167 if !previous_is_sep {
3168 out.push('_');
3169 previous_is_sep = true;
3170 }
3171 continue;
3172 }
3173
3174 if ch.is_ascii_uppercase() {
3175 if !out.is_empty() && !previous_is_sep {
3176 out.push('_');
3177 }
3178 out.push(ch.to_ascii_lowercase());
3179 previous_is_sep = false;
3180 } else {
3181 out.push(ch.to_ascii_lowercase());
3182 previous_is_sep = false;
3183 }
3184 }
3185
3186 out.trim_matches('_').to_owned()
3187}
3188
3189#[cfg(not(test))]
3190pub fn merge_mapping_document(existing: Option<&str>, title: &str, generated: &str) -> String {
3191 let generated_block =
3192 format!("{GENERATED_COVERAGE_START}\n{generated}\n{GENERATED_COVERAGE_END}\n");
3193
3194 if let Some(existing) = existing {
3195 if let Some(start) = existing.find(GENERATED_COVERAGE_START) {
3196 if let Some(end) = existing.find(GENERATED_COVERAGE_END) {
3197 let end_idx = end + GENERATED_COVERAGE_END.len();
3198 let before = existing[..start].trim_end();
3199 let after = existing[end_idx..].trim_start();
3200 return if after.is_empty() {
3201 format!("{before}\n\n{generated_block}")
3202 } else {
3203 format!("{before}\n\n{generated_block}\n{after}")
3204 };
3205 }
3206 }
3207
3208 let trimmed = existing.trim_end();
3209 if trimmed.is_empty() {
3210 return generated_block;
3211 }
3212 return format!("{trimmed}\n\n{generated_block}");
3213 }
3214
3215 format!("# {title} Mapping Note\n\n{generated_block}")
3216}
3217
3218fn render_enum_section(out: &mut String, label: &str, schema: &EnumSchema) {
3219 pushln!(out, "{label}");
3220 pushln!(
3221 out,
3222 " {} = {}",
3223 schema.name,
3224 render_enum_variants_inline(schema)
3225 );
3226 for variant in &schema.variants {
3227 pushln!(
3228 out,
3229 " {} == {}",
3230 variant.name,
3231 render_variant_fields(variant)
3232 );
3233 }
3234 out.push('\n');
3235}
3236
3237fn render_helpers_section(out: &mut String, label: &str, helpers: &[HelperSchema]) {
3238 if helpers.is_empty() {
3239 return;
3240 }
3241 pushln!(out, "{label}");
3242 for helper in helpers {
3243 pushln!(
3244 out,
3245 " {}({}) : {}",
3246 helper.name,
3247 render_fields(&helper.params),
3248 render_type_ref(&helper.returns)
3249 );
3250 pushln!(out, " == {}", render_expr(&helper.body));
3251 }
3252 out.push('\n');
3253}
3254
3255fn render_invariants_section(out: &mut String, schema: &MachineSchema) {
3256 pushln!(out, "INVARIANTS");
3257 for invariant in &schema.invariants {
3258 pushln!(
3259 out,
3260 " {} == {}",
3261 invariant.name,
3262 render_expr(&invariant.expr)
3263 );
3264 }
3265 out.push('\n');
3266}
3267
3268fn render_transitions_section(out: &mut String, schema: &MachineSchema) {
3269 pushln!(out, "TRANSITIONS");
3270 for transition in &schema.transitions {
3271 render_transition(out, transition);
3272 }
3273 out.push('\n');
3274}
3275
3276fn render_transition(out: &mut String, transition: &TransitionSchema) {
3277 pushln!(out, " {}", transition.name);
3278 pushln!(out, " from = {}", render_string_list(&transition.from));
3279 pushln!(
3280 out,
3281 " on = {}({})",
3282 transition.on.variant_str(),
3283 transition
3284 .on
3285 .bindings()
3286 .iter()
3287 .map(meerkat_machine_schema::identity::FieldId::as_str)
3288 .collect::<Vec<_>>()
3289 .join(", ")
3290 );
3291 if !transition.guards.is_empty() {
3292 pushln!(out, " guards =");
3293 for guard in &transition.guards {
3294 render_guard(out, guard);
3295 }
3296 }
3297 if !transition.updates.is_empty() {
3298 pushln!(out, " updates =");
3299 for update in &transition.updates {
3300 pushln!(out, " - {}", render_update(update));
3301 }
3302 }
3303 pushln!(out, " to = {}", tla_string(&transition.to));
3304 if !transition.emit.is_empty() {
3305 pushln!(out, " emit =");
3306 for effect in &transition.emit {
3307 pushln!(out, " - {}", render_effect_emit(effect));
3308 }
3309 }
3310}
3311
3312fn render_guard(out: &mut String, guard: &Guard) {
3313 pushln!(
3314 out,
3315 " - {} == {}",
3316 guard.name,
3317 render_expr(&guard.expr)
3318 );
3319}
3320
3321fn render_field_init(out: &mut String, field: &FieldInit) {
3322 pushln!(out, " {} = {}", field.field, render_expr(&field.expr));
3323}
3324
3325fn render_variant_fields(variant: &VariantSchema) -> String {
3326 if variant.fields.is_empty() {
3327 "[]".to_owned()
3328 } else {
3329 format!("[{}]", render_fields(&variant.fields))
3330 }
3331}
3332
3333fn render_fields(fields: &[FieldSchema]) -> String {
3334 fields
3335 .iter()
3336 .map(|field| format!("{}: {}", field.name, render_type_ref(&field.ty)))
3337 .collect::<Vec<_>>()
3338 .join(", ")
3339}
3340
3341fn render_update(update: &Update) -> String {
3342 match update {
3343 Update::Assign { field, expr } => format!("{field}' = {}", render_expr(expr)),
3344 Update::Increment { field, amount } => format!("{field}' = {field} + {amount}"),
3345 Update::Decrement { field, amount } => format!("{field}' = {field} - {amount}"),
3346 Update::MapInsert { field, key, value } => {
3347 format!(
3348 "{field}' = [ {field} EXCEPT ![{}] = {} ]",
3349 render_expr(key),
3350 render_expr(value)
3351 )
3352 }
3353 Update::MapRemove { field, key } => {
3354 format!("{field}' = MapRemove({field}, {})", render_expr(key))
3355 }
3356 Update::MapIncrement { field, key, amount } => {
3357 format!(
3358 "{field}' = [ {field} EXCEPT ![{}] = @ + {amount} ]",
3359 render_expr(key)
3360 )
3361 }
3362 Update::MapDecrement { field, key, amount } => {
3363 format!(
3364 "{field}' = [ {field} EXCEPT ![{}] = @ - {amount} ]",
3365 render_expr(key)
3366 )
3367 }
3368 Update::SetInsert { field, value } => {
3369 format!("{field}' = {field} \\cup {{ {} }}", render_expr(value))
3370 }
3371 Update::SetRemove { field, value } => {
3372 format!("{field}' = {field} \\ {{ {} }}", render_expr(value))
3373 }
3374 Update::SeqAppend { field, value } => {
3375 format!("{field}' = Append({field}, {})", render_expr(value))
3376 }
3377 Update::SeqPrepend { field, values } => {
3378 format!("{field}' = {} \\o {field}", render_expr(values))
3379 }
3380 Update::SeqPopFront { field } => {
3381 format!("{field}' = Tail({field})")
3382 }
3383 Update::SeqRemoveValue { field, value } => {
3384 format!("{field}' = SeqRemove({field}, {})", render_expr(value))
3385 }
3386 Update::SeqRemoveAll { field, values } => {
3387 format!("{field}' = SeqRemoveAll({field}, {})", render_expr(values))
3388 }
3389 Update::ForEach {
3390 binding,
3391 over,
3392 updates,
3393 } => {
3394 let body = updates
3395 .iter()
3396 .map(render_update)
3397 .collect::<Vec<_>>()
3398 .join("; ");
3399 format!("ForEach({binding} \\in {}) {{ {body} }}", render_expr(over))
3400 }
3401 Update::Conditional {
3402 condition,
3403 then_updates,
3404 else_updates,
3405 } => {
3406 let then_body = then_updates
3407 .iter()
3408 .map(render_update)
3409 .collect::<Vec<_>>()
3410 .join("; ");
3411 let else_body = else_updates
3412 .iter()
3413 .map(render_update)
3414 .collect::<Vec<_>>()
3415 .join("; ");
3416 format!(
3417 "If ({}) {{ {} }} Else {{ {} }}",
3418 render_expr(condition),
3419 then_body,
3420 else_body
3421 )
3422 }
3423 }
3424}
3425
3426fn render_effect_emit(effect: &EffectEmit) -> String {
3427 if effect.fields.is_empty() {
3428 effect.variant.as_str().to_owned()
3429 } else {
3430 let fields = effect
3431 .fields
3432 .iter()
3433 .map(|(name, expr)| format!("{name} |-> {}", render_expr(expr)))
3434 .collect::<Vec<_>>()
3435 .join(", ");
3436 format!("{}([{}])", effect.variant, fields)
3437 }
3438}
3439
3440#[cfg(test)]
3442pub(crate) fn render_expr_for_tests(expr: &Expr) -> String {
3443 render_expr(expr)
3444}
3445
3446fn render_expr(expr: &Expr) -> String {
3447 match expr {
3448 Expr::Bool(value) => value.to_string().to_uppercase(),
3449 Expr::U64(value) => value.to_string(),
3450 Expr::U64Max => "u64::MAX".to_string(),
3451 Expr::String(value) => tla_string(value),
3452 Expr::NamedVariant { enum_name, variant } => tla_string(known_enum_variant_wire_label(
3453 enum_name.as_str(),
3454 variant.as_str(),
3455 )),
3456 Expr::FieldAccess { base, field } => {
3457 format!("{}.{}", render_expr(base), field.as_str())
3458 }
3459 Expr::EnumVariantIs { value, variant, .. } => {
3460 format!(
3461 "{}.tag = {}",
3462 render_expr(value),
3463 tla_string(variant.as_str())
3464 )
3465 }
3466 Expr::EnumStringSetPayload {
3467 value,
3468 variant,
3469 field,
3470 ..
3471 } => format!(
3472 "IF {}.tag = {} THEN {}.{} ELSE {{}}",
3473 render_expr(value),
3474 tla_string(variant.as_str()),
3475 render_expr(value),
3476 field.as_str()
3477 ),
3478 Expr::EmptySet => "{}".to_owned(),
3479 Expr::EmptyMap => "[x \\in {} |-> None]".to_owned(),
3480 Expr::SeqLiteral(items) => format!(
3481 "<<{}>>",
3482 items.iter().map(render_expr).collect::<Vec<_>>().join(", ")
3483 ),
3484 Expr::CurrentPhase => "phase".to_owned(),
3485 Expr::Phase(value) => tla_string(value),
3486 Expr::Field(name) => name.as_str().to_owned(),
3487 Expr::Binding(name) => name.clone(),
3488 Expr::Variant(name) => name.clone(),
3489 Expr::None => "None".to_owned(),
3490 Expr::IfElse {
3491 condition,
3492 then_expr,
3493 else_expr,
3494 } => format!(
3495 "IF {} THEN {} ELSE {}",
3496 render_expr(condition),
3497 render_expr(then_expr),
3498 render_expr(else_expr)
3499 ),
3500 Expr::Not(inner) => format!("~({})", render_expr(inner)),
3501 Expr::And(items) => join_exprs(items, " /\\ "),
3502 Expr::Or(items) => join_exprs(items, " \\/ "),
3503 Expr::Eq(left, right) => format!("{} = {}", render_expr(left), render_expr(right)),
3504 Expr::Neq(left, right) => format!("{} # {}", render_expr(left), render_expr(right)),
3505 Expr::Add(left, right) => format!("{} + {}", render_expr(left), render_expr(right)),
3506 Expr::Sub(left, right) => format!("{} - {}", render_expr(left), render_expr(right)),
3507 Expr::Gt(left, right) => format!("{} > {}", render_expr(left), render_expr(right)),
3508 Expr::Gte(left, right) => format!("{} >= {}", render_expr(left), render_expr(right)),
3509 Expr::Lt(left, right) => format!("{} < {}", render_expr(left), render_expr(right)),
3510 Expr::Lte(left, right) => format!("{} <= {}", render_expr(left), render_expr(right)),
3511 Expr::Contains { collection, value } => {
3512 format!("{} \\in {}", render_expr(value), render_expr(collection))
3513 }
3514 Expr::MapContainsKey { map, key } => {
3515 format!("{} \\in DOMAIN {}", render_expr(key), render_expr(map))
3516 }
3517 Expr::SeqStartsWith { seq, prefix } => {
3518 format!("StartsWith({}, {})", render_expr(seq), render_expr(prefix))
3519 }
3520 Expr::SeqElements(inner) => format!("SeqElements({})", render_expr(inner)),
3521 Expr::Len(inner) => format!("Len({})", render_expr(inner)),
3522 Expr::Count { collection, value } => {
3523 format!("Count({}, {})", render_expr(collection), render_expr(value))
3524 }
3525 Expr::Head(inner) => format!("Head({})", render_expr(inner)),
3526 Expr::MapKeys(inner) => format!("DOMAIN {}", render_expr(inner)),
3527 Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
3528 format!("{}[{}]", render_expr(map), render_expr(key))
3529 }
3530 Expr::MapLiteral(entries) => format!(
3531 "({})",
3532 entries
3533 .iter()
3534 .map(|(key, value)| format!("{} :> {}", render_expr(key), render_expr(value)))
3535 .collect::<Vec<_>>()
3536 .join(" @@ ")
3537 ),
3538 Expr::Some(inner) => format!("Some({})", render_expr(inner)),
3539 Expr::Call { helper, args } => format!(
3540 "{}({})",
3541 helper,
3542 args.iter().map(render_expr).collect::<Vec<_>>().join(", ")
3543 ),
3544 Expr::Quantified {
3545 quantifier,
3546 binding,
3547 over,
3548 body,
3549 } => {
3550 let keyword = match quantifier {
3551 Quantifier::Any => "\\E",
3552 Quantifier::All => "\\A",
3553 };
3554 format!(
3555 "({} {} \\in {} : {})",
3556 keyword,
3557 binding,
3558 render_expr(over),
3559 render_expr(body)
3560 )
3561 }
3562 }
3563}
3564
3565fn join_exprs(items: &[Expr], separator: &str) -> String {
3566 if items.is_empty() {
3567 return "TRUE".to_owned();
3568 }
3569 items
3570 .iter()
3571 .map(render_expr)
3572 .collect::<Vec<_>>()
3573 .join(separator)
3574}
3575
3576fn render_type_ref(ty: &TypeRef) -> String {
3577 match ty {
3578 TypeRef::Bool => "Bool".to_owned(),
3579 TypeRef::U32 => "Nat".to_owned(),
3580 TypeRef::U64 => "Nat".to_owned(),
3581 TypeRef::String => "String".to_owned(),
3582 TypeRef::Named(name) => name.as_str().to_owned(),
3583 TypeRef::Enum(name) => name.as_str().to_owned(),
3584 TypeRef::Option(inner) => format!("Option({})", render_type_ref(inner)),
3585 TypeRef::Set(inner) => format!("Set({})", render_type_ref(inner)),
3586 TypeRef::Seq(inner) => format!("Seq({})", render_type_ref(inner)),
3587 TypeRef::Map(key, value) => {
3588 format!("Map({}, {})", render_type_ref(key), render_type_ref(value))
3589 }
3590 }
3591}
3592
3593#[cfg(not(test))]
3597fn render_value_derive(out: &mut String, indent: &str, fields: &[FieldSchema]) {
3598 let debug = if has_redacted_field(fields) {
3599 ""
3600 } else {
3601 "Debug, "
3602 };
3603 pushln!(
3604 out,
3605 "{indent}#[derive({debug}Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]"
3606 );
3607}
3608
3609#[cfg(not(test))]
3610fn has_redacted_field(fields: &[FieldSchema]) -> bool {
3611 fields
3612 .iter()
3613 .any(|field| field.disclosure == meerkat_machine_schema::FieldDisclosure::Redacted)
3614}
3615
3616#[cfg(not(test))]
3620fn render_redacted_debug_impl(
3621 out: &mut String,
3622 indent: &str,
3623 type_name: &str,
3624 leading_visible: &[&str],
3625 fields: &[FieldSchema],
3626) {
3627 if !has_redacted_field(fields) {
3628 return;
3629 }
3630 pushln!(out, "{indent}impl std::fmt::Debug for {type_name} {{");
3631 pushln!(
3632 out,
3633 "{indent} fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{"
3634 );
3635 pushln!(out, "{indent} f.debug_struct(\"{type_name}\")");
3636 for name in leading_visible {
3637 pushln!(out, "{indent} .field(\"{name}\", &self.{name})");
3638 }
3639 for field in fields {
3640 let label = field.name.as_str();
3641 let access = format!("self.{}", rust_field_ident(&field.name));
3642 let value = match (field.disclosure, &field.ty) {
3643 (meerkat_machine_schema::FieldDisclosure::Visible, _) => format!("&{access}"),
3645 (meerkat_machine_schema::FieldDisclosure::Redacted, TypeRef::Option(_)) => {
3646 format!("&{access}.as_ref().map(|_| \"<redacted>\")")
3647 }
3648 (
3649 meerkat_machine_schema::FieldDisclosure::Redacted,
3650 TypeRef::Set(_) | TypeRef::Seq(_) | TypeRef::Map(_, _),
3651 ) => {
3652 format!("&format_args!(\"<redacted; {{}} entries>\", {access}.len())")
3653 }
3654 (
3655 meerkat_machine_schema::FieldDisclosure::Redacted,
3656 TypeRef::Bool
3657 | TypeRef::U32
3658 | TypeRef::U64
3659 | TypeRef::String
3660 | TypeRef::Named(_)
3661 | TypeRef::Enum(_),
3662 ) => "&\"<redacted>\"".to_owned(),
3663 };
3664 pushln!(out, "{indent} .field(\"{label}\", {value})");
3665 }
3666 pushln!(out, "{indent} .finish()");
3667 pushln!(out, "{indent} }}");
3668 pushln!(out, "{indent}}}");
3669}
3670
3671#[cfg(not(test))]
3672fn render_rust_type_ref(ty: &TypeRef) -> String {
3673 match ty {
3674 TypeRef::Bool => "bool".to_owned(),
3675 TypeRef::U32 => "u32".to_owned(),
3676 TypeRef::U64 => "u64".to_owned(),
3677 TypeRef::String => "String".to_owned(),
3678 TypeRef::Named(name) => rust_ident(name),
3679 TypeRef::Enum(name) => rust_ident(name),
3680 TypeRef::Option(inner) => format!("Option<{}>", render_rust_type_ref(inner)),
3681 TypeRef::Set(inner) => {
3682 format!(
3683 "std::collections::BTreeSet<{}>",
3684 render_rust_type_ref(inner)
3685 )
3686 }
3687 TypeRef::Seq(inner) => format!("Vec<{}>", render_rust_type_ref(inner)),
3688 TypeRef::Map(key, value) => format!(
3689 "std::collections::BTreeMap<{}, {}>",
3690 render_rust_type_ref(key),
3691 render_rust_type_ref(value)
3692 ),
3693 }
3694}
3695
3696#[cfg(not(test))]
3697fn collect_machine_named_types(schema: &MachineSchema) -> Vec<String> {
3698 let mut names = std::collections::BTreeSet::new();
3699
3700 for field in &schema.state.fields {
3701 collect_named_types_from_type_ref(&field.ty, &mut names);
3702 }
3703 for variant in &schema.inputs.variants {
3704 for field in &variant.fields {
3705 collect_named_types_from_type_ref(&field.ty, &mut names);
3706 }
3707 }
3708 for variant in &schema.signals.variants {
3709 for field in &variant.fields {
3710 collect_named_types_from_type_ref(&field.ty, &mut names);
3711 }
3712 }
3713 for variant in &schema.effects.variants {
3714 for field in &variant.fields {
3715 collect_named_types_from_type_ref(&field.ty, &mut names);
3716 }
3717 }
3718 for helper in schema.helpers.iter().chain(schema.derived.iter()) {
3719 for field in &helper.params {
3720 collect_named_types_from_type_ref(&field.ty, &mut names);
3721 }
3722 collect_named_types_from_type_ref(&helper.returns, &mut names);
3723 }
3724
3725 names.into_iter().collect()
3726}
3727
3728#[cfg(not(test))]
3729fn collect_named_types_from_type_ref(ty: &TypeRef, names: &mut std::collections::BTreeSet<String>) {
3730 match ty {
3731 TypeRef::Named(name) => {
3732 names.insert(rust_ident(name));
3733 }
3734 TypeRef::Enum(name) => {
3735 names.insert(rust_ident(name));
3736 }
3737 TypeRef::Option(inner) | TypeRef::Set(inner) | TypeRef::Seq(inner) => {
3738 collect_named_types_from_type_ref(inner, names);
3739 }
3740 TypeRef::Map(key, value) => {
3741 collect_named_types_from_type_ref(key, names);
3742 collect_named_types_from_type_ref(value, names);
3743 }
3744 TypeRef::Bool | TypeRef::U32 | TypeRef::U64 | TypeRef::String => {}
3745 }
3746}
3747
3748#[cfg(not(test))]
3752fn render_rust_type_atom(atom: &meerkat_machine_schema::RustTypeAtom) -> String {
3753 use meerkat_machine_schema::RustTypeAtom;
3754 match atom {
3755 RustTypeAtom::U8 => "u8".to_string(),
3756 RustTypeAtom::U16 => "u16".to_string(),
3757 RustTypeAtom::U32 => "u32".to_string(),
3758 RustTypeAtom::U64 => "u64".to_string(),
3759 RustTypeAtom::Bool => "bool".to_string(),
3760 RustTypeAtom::String => "String".to_string(),
3761 RustTypeAtom::StringEnum { .. } => "String".to_string(),
3762 RustTypeAtom::TypePath(path)
3763 | RustTypeAtom::TypePathFieldPresenceSet { path, .. }
3764 | RustTypeAtom::TypePathStruct { path, .. }
3765 | RustTypeAtom::TypePathEnum { path, .. } => path
3766 .strip_prefix("crate::catalog::")
3767 .map(|suffix| format!("meerkat_machine_schema::catalog::{suffix}"))
3768 .unwrap_or_else(|| path.clone()),
3769 }
3770}
3771
3772#[cfg(not(test))]
3773fn render_named_type_definition(
3774 out: &mut String,
3775 name: &str,
3776 atom: &meerkat_machine_schema::RustTypeAtom,
3777) {
3778 use meerkat_machine_schema::RustTypeAtom;
3779
3780 let rust_name = rust_ident(name);
3781 match atom {
3782 RustTypeAtom::TypePath(_)
3783 | RustTypeAtom::TypePathFieldPresenceSet { .. }
3784 | RustTypeAtom::TypePathStruct { .. }
3785 | RustTypeAtom::TypePathEnum { .. } => {
3786 pushln!(
3787 out,
3788 "pub type {} = {};",
3789 rust_name,
3790 render_rust_type_atom(atom)
3791 );
3792 }
3793 RustTypeAtom::String => {
3794 pushln!(
3795 out,
3796 "#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]"
3797 );
3798 pushln!(out, "pub struct {}(pub String);", rust_name);
3799 pushln!(out, "impl From<String> for {} {{", rust_name);
3800 pushln!(out, " fn from(value: String) -> Self {{ Self(value) }}");
3801 pushln!(out, "}}");
3802 pushln!(out, "impl From<&str> for {} {{", rust_name);
3803 pushln!(
3804 out,
3805 " fn from(value: &str) -> Self {{ Self(value.to_owned()) }}"
3806 );
3807 pushln!(out, "}}");
3808 pushln!(out, "impl std::fmt::Display for {} {{", rust_name);
3809 pushln!(
3810 out,
3811 " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{ f.write_str(&self.0) }}"
3812 );
3813 pushln!(out, "}}");
3814 }
3815 RustTypeAtom::StringEnum { variants } => {
3816 if let Some((first, second, ident)) = string_enum_variant_ident_collision(variants) {
3817 pushln!(
3818 out,
3819 "compile_error!(\"string enum {} variants `{}` and `{}` sanitize to duplicate Rust identifier `{}`\");",
3820 rust_name,
3821 first,
3822 second,
3823 ident
3824 );
3825 return;
3826 }
3827 pushln!(out, "#[allow(non_camel_case_types)]");
3828 pushln!(
3829 out,
3830 "#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]"
3831 );
3832 pushln!(out, "pub enum {} {{", rust_name);
3833 for (index, variant) in variants.iter().enumerate() {
3834 if index == 0 {
3835 pushln!(out, " #[default]");
3836 }
3837 let wire_label = known_enum_variant_wire_label(&rust_name, variant.as_str());
3838 pushln!(out, " #[serde(rename = {})]", tla_string(wire_label));
3839 pushln!(out, " {},", rust_ident(variant.as_str()));
3840 }
3841 pushln!(out, "}}");
3842 pushln!(out, "impl {} {{", rust_name);
3843 pushln!(out, " pub fn as_str(&self) -> &'static str {{");
3844 pushln!(out, " match self {{");
3845 for variant in variants {
3846 let wire_expr = known_enum_variant_wire_expr(&rust_name, variant.as_str());
3847 pushln!(
3848 out,
3849 " Self::{} => {},",
3850 rust_ident(variant.as_str()),
3851 wire_expr
3852 );
3853 }
3854 pushln!(out, " }}");
3855 pushln!(out, " }}");
3856 pushln!(out, "}}");
3857 pushln!(out, "impl std::convert::TryFrom<&str> for {} {{", rust_name);
3858 pushln!(out, " type Error = String;");
3859 pushln!(
3860 out,
3861 " fn try_from(value: &str) -> Result<Self, Self::Error> {{"
3862 );
3863 pushln!(out, " match value {{");
3864 for variant in variants {
3865 let wire_label = known_enum_variant_wire_label(&rust_name, variant.as_str());
3866 pushln!(
3867 out,
3868 " \"{}\" => Ok(Self::{}),",
3869 wire_label,
3870 rust_ident(variant.as_str())
3871 );
3872 }
3873 pushln!(
3874 out,
3875 " other => Err(format!(\"invalid {} value `{{other}}`\")),",
3876 rust_name
3877 );
3878 pushln!(out, " }}");
3879 pushln!(out, " }}");
3880 pushln!(out, "}}");
3881 pushln!(
3882 out,
3883 "impl std::convert::TryFrom<String> for {} {{",
3884 rust_name
3885 );
3886 pushln!(out, " type Error = String;");
3887 pushln!(
3888 out,
3889 " fn try_from(value: String) -> Result<Self, Self::Error> {{ Self::try_from(value.as_str()) }}"
3890 );
3891 pushln!(out, "}}");
3892 pushln!(out, "impl std::fmt::Display for {} {{", rust_name);
3893 pushln!(
3894 out,
3895 " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{ f.write_str(self.as_str()) }}"
3896 );
3897 pushln!(out, "}}");
3898 }
3899 RustTypeAtom::Bool
3900 | RustTypeAtom::U8
3901 | RustTypeAtom::U16
3902 | RustTypeAtom::U32
3903 | RustTypeAtom::U64 => {
3904 let inner = render_rust_type_atom(atom);
3905 pushln!(
3906 out,
3907 "#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]"
3908 );
3909 pushln!(out, "pub struct {}(pub {});", rust_name, inner);
3910 pushln!(out, "impl From<{}> for {} {{", inner, rust_name);
3911 pushln!(
3912 out,
3913 " fn from(value: {}) -> Self {{ Self(value) }}",
3914 inner
3915 );
3916 pushln!(out, "}}");
3917 pushln!(out, "impl std::fmt::Display for {} {{", rust_name);
3918 pushln!(
3919 out,
3920 " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{ write!(f, \"{{}}\", self.0) }}"
3921 );
3922 pushln!(out, "}}");
3923 }
3924 }
3925}
3926
3927#[cfg(not(test))]
3928fn string_enum_variant_ident_collision<T: AsRef<str>>(
3929 variants: &[T],
3930) -> Option<(String, String, String)> {
3931 let mut seen: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
3932 for variant in variants {
3933 let raw = variant.as_ref();
3934 let ident = rust_ident(raw);
3935 if let Some(first) = seen.get(&ident) {
3936 return Some((first.clone(), raw.to_owned(), ident));
3937 }
3938 seen.insert(ident, raw.to_owned());
3939 }
3940 None
3941}
3942
3943#[cfg(not(test))]
3946fn lookup_named_type_atom<'a>(
3947 schema: &'a MachineSchema,
3948 name: &str,
3949) -> Option<&'a meerkat_machine_schema::RustTypeAtom> {
3950 schema
3951 .named_types
3952 .iter()
3953 .find(|binding| binding.name.as_str() == name)
3954 .map(|binding| &binding.rust)
3955}
3956
3957#[cfg(not(test))]
3958fn rust_ident(value: impl AsRef<str>) -> String {
3959 value
3960 .as_ref()
3961 .chars()
3962 .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
3963 .collect()
3964}
3965
3966fn known_enum_variant_wire_label(enum_name: &str, variant: &str) -> String {
3967 if enum_name == meerkat_core::turn_execution_authority::ContentShape::SCHEMA_TYPE_NAME
3968 && let Some(shape) =
3969 meerkat_core::turn_execution_authority::ContentShape::from_schema_variant(variant)
3970 {
3971 return shape.as_str().to_owned();
3972 }
3973
3974 variant.to_owned()
3975}
3976
3977#[cfg_attr(test, allow(dead_code))]
3978fn known_enum_variant_wire_expr(enum_name: &str, variant: &str) -> String {
3979 if enum_name == meerkat_core::turn_execution_authority::ContentShape::SCHEMA_TYPE_NAME
3980 && let Some(shape) =
3981 meerkat_core::turn_execution_authority::ContentShape::from_schema_variant(variant)
3982 {
3983 return format!(
3984 "meerkat_core::turn_execution_authority::ContentShape::{}.as_str()",
3985 shape.schema_variant()
3986 );
3987 }
3988
3989 tla_string(variant)
3990}
3991
3992#[cfg(not(test))]
3993fn rust_field_ident(value: impl AsRef<str>) -> String {
3994 rust_ident(value)
3995}
3996
3997#[cfg(not(test))]
3998#[allow(dead_code)]
3999fn rust_fn_ident(value: &str) -> String {
4000 simple_snake_case(value)
4001}
4002
4003#[cfg(not(test))]
4004#[allow(dead_code)]
4005fn simple_snake_case(value: &str) -> String {
4006 let mut out = String::new();
4007 for (idx, ch) in value.chars().enumerate() {
4008 if ch.is_ascii_uppercase() {
4009 if idx != 0 {
4010 out.push('_');
4011 }
4012 out.push(ch.to_ascii_lowercase());
4013 } else if ch.is_ascii_alphanumeric() {
4014 out.push(ch.to_ascii_lowercase());
4015 } else {
4016 out.push('_');
4017 }
4018 }
4019 out
4020}
4021
4022fn render_enum_variants_inline(schema: &EnumSchema) -> String {
4023 let variants = schema
4024 .variants
4025 .iter()
4026 .map(|variant| tla_string(&variant.name))
4027 .collect::<Vec<_>>()
4028 .join(", ");
4029 format!("{{{variants}}}")
4030}
4031
4032fn render_string_list<S: AsRef<str>>(items: &[S]) -> String {
4033 let rendered = items.iter().map(tla_string).collect::<Vec<_>>().join(", ");
4034 format!("<<{rendered}>>")
4035}
4036
4037#[cfg(not(test))]
4038fn render_route_delivery(delivery: &RouteDelivery) -> &'static str {
4039 match delivery {
4040 RouteDelivery::Immediate => "Immediate",
4041 RouteDelivery::Enqueue => "Enqueue",
4042 }
4043}
4044
4045#[cfg(not(test))]
4046fn render_route_bindings(route: &meerkat_machine_schema::Route) -> String {
4047 route
4048 .bindings
4049 .iter()
4050 .map(|binding| match &binding.source {
4051 meerkat_machine_schema::RouteBindingSource::Field {
4052 from_field,
4053 allow_named_alias,
4054 } => {
4055 if *allow_named_alias {
4056 format!("{from_field} ~> {}", binding.to_field)
4057 } else {
4058 format!("{from_field} -> {}", binding.to_field)
4059 }
4060 }
4061 meerkat_machine_schema::RouteBindingSource::Literal(expr) => {
4062 format!("{} := {}", binding.to_field, render_expr(expr))
4063 }
4064 meerkat_machine_schema::RouteBindingSource::OwnerProvided => {
4065 format!("{} := <owner-provided>", binding.to_field)
4066 }
4067 })
4068 .collect::<Vec<_>>()
4069 .join(", ")
4070}
4071
4072#[cfg(not(test))]
4073fn render_scheduler_rule(rule: &SchedulerRule) -> String {
4074 match rule {
4075 SchedulerRule::PreemptWhenReady { higher, lower } => {
4076 format!("PreemptWhenReady({}, {})", higher, lower)
4077 }
4078 }
4079}
4080
4081#[cfg(not(test))]
4082fn render_composition_invariant_kind(kind: &CompositionInvariantKind) -> String {
4083 match kind {
4084 CompositionInvariantKind::RoutePresent {
4085 from_machine,
4086 effect_variant,
4087 to_machine,
4088 input_variant,
4089 } => format!(
4090 "RoutePresent({}, {}, {}, {})",
4091 from_machine, effect_variant, to_machine, input_variant
4092 ),
4093 CompositionInvariantKind::ActorPriorityPresent { higher, lower } => {
4094 format!("ActorPriorityPresent({}, {})", higher, lower)
4095 }
4096 CompositionInvariantKind::ObservedInputOriginatesFromEffect {
4097 to_machine,
4098 input_variant,
4099 from_machine,
4100 effect_variant,
4101 } => format!(
4102 "ObservedInputOriginatesFromEffect({}, {}, {}, {})",
4103 to_machine, input_variant, from_machine, effect_variant
4104 ),
4105 CompositionInvariantKind::ObservedRouteInputOriginatesFromEffect {
4106 route_name,
4107 to_machine,
4108 input_variant,
4109 from_machine,
4110 effect_variant,
4111 } => format!(
4112 "ObservedRouteInputOriginatesFromEffect({}, {}, {}, {}, {})",
4113 route_name, to_machine, input_variant, from_machine, effect_variant
4114 ),
4115 CompositionInvariantKind::SchedulerRulePresent { rule } => {
4116 format!("SchedulerRulePresent({})", render_scheduler_rule(rule))
4117 }
4118 CompositionInvariantKind::OutcomeHandled {
4119 from_machine,
4120 effect_variant,
4121 required_targets,
4122 } => format!(
4123 "OutcomeHandled({}, {}, {})",
4124 from_machine,
4125 effect_variant,
4126 required_targets
4127 .iter()
4128 .map(|target| format!("{}.{}", target.machine, target.input_variant))
4129 .collect::<Vec<_>>()
4130 .join(" | ")
4131 ),
4132 CompositionInvariantKind::HandoffProtocolCovered {
4133 producer_instance,
4134 effect_variant,
4135 protocol_name,
4136 } => format!(
4137 "HandoffProtocolCovered({}, {}, {})",
4138 producer_instance, effect_variant, protocol_name
4139 ),
4140 }
4141}
4142
4143fn tla_ident(value: impl AsRef<str>) -> String {
4144 value
4145 .as_ref()
4146 .chars()
4147 .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
4148 .collect()
4149}
4150
4151fn tla_string(value: impl AsRef<str>) -> String {
4152 format!("\"{}\"", value.as_ref().replace('"', "\\\""))
4153}
4154
4155#[cfg(test)]
4156mod tests {
4157 use super::render_machine_module;
4158 use meerkat_machine_schema::identity::{
4159 EffectVariantId, EnumVariantId, FieldId, InputVariantId, MachineId, PhaseId, TransitionId,
4160 };
4161 use meerkat_machine_schema::{
4162 EffectEmit, EnumSchema, Expr, FieldInit, FieldSchema, InitSchema, MachineSchema,
4163 RustBinding, StateSchema, TransitionSchema, TriggerMatch, TypeRef, Update, VariantSchema,
4164 };
4165
4166 fn vid(s: &str) -> EnumVariantId {
4167 EnumVariantId::parse(s).expect("valid enum variant slug")
4168 }
4169
4170 fn fid(s: &str) -> FieldId {
4171 FieldId::parse(s).expect("valid field slug")
4172 }
4173
4174 fn pid(s: &str) -> PhaseId {
4175 PhaseId::parse(s).expect("valid phase slug")
4176 }
4177
4178 fn tid(s: &str) -> TransitionId {
4179 TransitionId::parse(s).expect("valid transition slug")
4180 }
4181
4182 fn ivid(s: &str) -> InputVariantId {
4183 InputVariantId::parse(s).expect("valid input variant slug")
4184 }
4185
4186 fn eid(s: &str) -> EffectVariantId {
4187 EffectVariantId::parse(s).expect("valid effect variant slug")
4188 }
4189
4190 fn turn_execution_fixture() -> MachineSchema {
4191 MachineSchema {
4192 machine: MachineId::parse("TurnExecutionMachine").expect("valid machine slug"),
4193 version: 1,
4194 rust: RustBinding {
4195 crate_name: "meerkat-core".to_owned(),
4196 module: "agent::turn_execution".to_owned(),
4197 },
4198 state: StateSchema {
4199 phase: EnumSchema {
4200 name: "TurnExecutionPhase".to_owned(),
4201 variants: vec![
4202 VariantSchema {
4203 name: vid("Idle"),
4204 fields: vec![],
4205 },
4206 VariantSchema {
4207 name: vid("Running"),
4208 fields: vec![],
4209 },
4210 VariantSchema {
4211 name: vid("AwaitingBoundary"),
4212 fields: vec![],
4213 },
4214 VariantSchema {
4215 name: vid("Cancelled"),
4216 fields: vec![],
4217 },
4218 ],
4219 },
4220 fields: vec![FieldSchema {
4221 name: fid("boundary_count"),
4222 ty: TypeRef::U64,
4223 disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
4224 }],
4225 init: InitSchema {
4226 phase: pid("Idle"),
4227 fields: vec![FieldInit {
4228 field: fid("boundary_count"),
4229 expr: Expr::U64(0),
4230 }],
4231 },
4232 terminal_phases: vec![pid("Cancelled")],
4233 },
4234 inputs: EnumSchema {
4235 name: "TurnExecutionInput".to_owned(),
4236 variants: vec![
4237 VariantSchema {
4238 name: vid("StartConversationRun"),
4239 fields: vec![FieldSchema {
4240 name: fid("run_id"),
4241 ty: TypeRef::String,
4242 disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
4243 }],
4244 },
4245 VariantSchema {
4246 name: vid("PrimitiveAppliedConversationTurn"),
4247 fields: vec![FieldSchema {
4248 name: fid("run_id"),
4249 ty: TypeRef::String,
4250 disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
4251 }],
4252 },
4253 VariantSchema {
4254 name: vid("BoundaryComplete"),
4255 fields: vec![],
4256 },
4257 VariantSchema {
4258 name: vid("AcknowledgeTerminalFromCancelled"),
4259 fields: vec![],
4260 },
4261 ],
4262 },
4263 surface_only_inputs: vec![],
4264 runtime_internal_inputs: vec![],
4265 tlc_representative_inputs: vec![],
4266 signals: EnumSchema {
4267 name: "TurnExecutionSignal".to_owned(),
4268 variants: vec![],
4269 },
4270 effects: EnumSchema {
4271 name: "TurnExecutionEffect".to_owned(),
4272 variants: vec![VariantSchema {
4273 name: vid("BoundaryApplied"),
4274 fields: vec![
4275 FieldSchema {
4276 name: fid("run_id"),
4277 ty: TypeRef::String,
4278 disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
4279 },
4280 FieldSchema {
4281 name: fid("boundary_sequence"),
4282 ty: TypeRef::U64,
4283 disclosure: meerkat_machine_schema::FieldDisclosure::Visible,
4284 },
4285 ],
4286 }],
4287 },
4288 helpers: vec![],
4289 derived: vec![],
4290 command_plans: vec![],
4291 invariants: vec![],
4292 transitions: vec![
4293 TransitionSchema {
4294 name: tid("StartConversationRun"),
4295 from: vec![pid("Idle")],
4296 on: TriggerMatch::Input {
4297 variant: ivid("StartConversationRun"),
4298 bindings: vec![fid("run_id")],
4299 },
4300 guards: vec![],
4301 updates: vec![],
4302 to: pid("Running"),
4303 emit: vec![],
4304 },
4305 TransitionSchema {
4306 name: tid("PrimitiveAppliedConversationTurn"),
4307 from: vec![pid("Running")],
4308 on: TriggerMatch::Input {
4309 variant: ivid("PrimitiveAppliedConversationTurn"),
4310 bindings: vec![fid("run_id")],
4311 },
4312 guards: vec![],
4313 updates: vec![Update::Increment {
4314 field: fid("boundary_count"),
4315 amount: 1,
4316 }],
4317 to: pid("AwaitingBoundary"),
4318 emit: vec![EffectEmit {
4319 variant: eid("BoundaryApplied"),
4320 fields: [
4321 (fid("run_id"), Expr::Binding("run_id".to_owned())),
4322 (
4323 fid("boundary_sequence"),
4324 Expr::Add(
4325 Box::new(Expr::Field(fid("boundary_count"))),
4326 Box::new(Expr::U64(1)),
4327 ),
4328 ),
4329 ]
4330 .into_iter()
4331 .collect(),
4332 }],
4333 },
4334 TransitionSchema {
4335 name: tid("BoundaryComplete"),
4336 from: vec![pid("AwaitingBoundary")],
4337 on: TriggerMatch::Input {
4338 variant: ivid("BoundaryComplete"),
4339 bindings: vec![],
4340 },
4341 guards: vec![],
4342 updates: vec![],
4343 to: pid("Cancelled"),
4344 emit: vec![],
4345 },
4346 TransitionSchema {
4347 name: tid("AcknowledgeTerminalFromCancelled"),
4348 from: vec![pid("Cancelled")],
4349 on: TriggerMatch::Input {
4350 variant: ivid("AcknowledgeTerminalFromCancelled"),
4351 bindings: vec![],
4352 },
4353 guards: vec![],
4354 updates: vec![],
4355 to: pid("Cancelled"),
4356 emit: vec![],
4357 },
4358 ],
4359 ci_step_limit: None,
4360 tlc_model: None,
4361 deep_domain_overrides: Default::default(),
4362 input_field_domains: Default::default(),
4363 effect_dispositions: vec![],
4364 named_types: vec![],
4365 }
4366 }
4367
4368 #[test]
4369 fn renders_turn_execution_with_boundary_and_terminal_transitions() {
4370 let rendered = render_machine_module(&turn_execution_fixture());
4371
4372 assert!(rendered.contains("TRANSITIONS\n StartConversationRun"));
4373 assert!(rendered.contains("PrimitiveAppliedConversationTurn"));
4374 assert!(rendered.contains("BoundaryComplete"));
4375 assert!(rendered.contains("AcknowledgeTerminalFromCancelled"));
4376 assert!(rendered.contains(
4377 "BoundaryApplied([run_id |-> run_id, boundary_sequence |-> boundary_count + 1])"
4378 ));
4379 }
4380}