rust-tokio-supervisor 0.1.3

A Rust tokio supervisor with declarative task supervision, restart policy, shutdown coordination, and observability.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! Shared dashboard data model.
//!
//! These structs are the JSON contract shared by target IPC, relay, and the
//! dashboard UI. They intentionally use owned values so callers can serialize,
//! clone, and test messages without borrowing runtime internals.

use crate::control::command::{CommandResult, CurrentState};
use crate::control::outcome::{
    ChildAttemptStatus, ChildControlFailure, ChildControlFailurePhase, ChildControlOperation,
    ChildControlResult as RuntimeChildControlResult, ChildLivenessState, ChildRuntimeRecord,
    ChildStopState, GenerationFenceDecision, GenerationFenceOutcome, GenerationFencePhase,
    PendingRestartSummary, RestartLimitState,
};
use crate::readiness::signal::ReadinessState;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

/// Supported command metadata sent to the relay.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SupportedCommand {
    /// Wire command name.
    pub name: String,
    /// Whether the command can be retried with the same command identifier.
    pub idempotent: bool,
    /// Command timeout in seconds.
    pub timeout_seconds: u64,
}

/// Target process registration payload sent to the relay.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct TargetProcessRegistration {
    /// Stable target process identifier.
    pub target_id: String,
    /// Human-readable display name.
    pub display_name: String,
    /// Local Unix domain socket path exposed by the target.
    pub ipc_path: String,
    /// Lease duration in seconds.
    pub lease_seconds: u64,
    /// Commands supported by this target.
    pub supported_commands: Vec<SupportedCommand>,
}

/// Current registration state for a target process.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RegistrationState {
    /// Registration was accepted and is visible.
    Active,
    /// Registration was rejected.
    Rejected,
    /// Registration lease expired.
    Expired,
}

/// Current relay connection state for a target process.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TargetConnectionState {
    /// Target is registered but no session has bound it.
    Registered,
    /// Relay is connecting to target IPC.
    Connecting,
    /// Relay is connected to target IPC.
    Connected,
    /// Relay is reconnecting to target IPC.
    Reconnecting,
    /// Target IPC is unavailable.
    Unavailable,
    /// Registration lease expired.
    Expired,
}

/// Target identity shown in dashboard state payloads and target lists.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct TargetProcessIdentity {
    /// Stable target process identifier.
    pub target_id: String,
    /// Human-readable display name.
    pub display_name: String,
    /// Current registration state.
    pub registration_state: RegistrationState,
    /// Current relay connection state.
    pub connection_state: TargetConnectionState,
}

/// Complete dashboard state returned when a target is opened or reconnected.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardState {
    /// Target process identity.
    pub target: TargetProcessIdentity,
    /// Supervisor topology.
    pub topology: SupervisorTopology,
    /// Runtime state rows indexed by child path.
    pub runtime_state: Vec<RuntimeState>,
    /// Runtime records returned by the control loop current state.
    pub child_runtime_records: Vec<DashboardChildRuntimeRecord>,
    /// Recent events retained by the target.
    pub recent_events: Vec<EventRecord>,
    /// Recent logs retained by the target.
    pub recent_logs: Vec<LogRecord>,
    /// Number of dropped events.
    pub dropped_event_count: u64,
    /// Number of dropped logs.
    pub dropped_log_count: u64,
    /// Configuration version string.
    pub config_version: String,
    /// Generated time as Unix nanoseconds.
    pub generated_at_unix_nanos: u128,
    /// Monotonic state generation for this target.
    pub state_generation: u64,
}

/// Supervisor graph for dashboard rendering.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SupervisorTopology {
    /// Root supervisor node.
    pub root: SupervisorNode,
    /// All visible nodes including the root.
    pub nodes: Vec<SupervisorNode>,
    /// Parent-child and dependency edges.
    pub edges: Vec<SupervisorEdge>,
    /// Node paths in declaration order.
    pub declaration_order: Vec<String>,
}

/// Node kind visible in the topology.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SupervisorNodeKind {
    /// Root supervisor node.
    RootSupervisor,
    /// Child task node.
    ChildTask,
}

/// Criticality shown by dashboard nodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardCriticality {
    /// Critical child.
    Critical,
    /// Standard child.
    Standard,
    /// Best-effort child.
    BestEffort,
}

/// Node displayed in the supervisor topology.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SupervisorNode {
    /// Stable node identifier.
    pub node_id: String,
    /// Optional child identifier.
    pub child_id: Option<String>,
    /// Absolute child path.
    pub path: String,
    /// Human-readable node name.
    pub name: String,
    /// Node kind.
    pub kind: SupervisorNodeKind,
    /// Low-cardinality tags.
    pub tags: Vec<String>,
    /// Node criticality.
    pub criticality: DashboardCriticality,
    /// Current state summary.
    pub state_summary: String,
    /// Key diagnostic fields.
    pub diagnostics: BTreeMap<String, String>,
}

/// Edge kind visible in the topology.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SupervisorEdgeKind {
    /// Parent-child edge.
    ParentChild,
    /// Dependency edge.
    Dependency,
}

/// Edge displayed in the supervisor topology.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SupervisorEdge {
    /// Stable edge identifier.
    pub edge_id: String,
    /// Source node path.
    pub source_path: String,
    /// Target node path.
    pub target_path: String,
    /// Edge kind.
    pub kind: SupervisorEdgeKind,
    /// Declaration or dependency order.
    pub order: usize,
}

/// Runtime state shown for one child.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RuntimeState {
    /// Child path.
    pub child_path: String,
    /// Lifecycle state label.
    pub lifecycle_state: String,
    /// Health status label.
    pub health: String,
    /// Readiness status label.
    pub readiness: String,
    /// Child generation.
    pub generation: u64,
    /// Child child_start_count.
    pub child_start_count: u64,
    /// Restart count.
    pub restart_count: u64,
    /// Optional last failure summary.
    pub last_failure: Option<String>,
    /// Optional last policy decision summary.
    pub last_policy_decision: Option<String>,
    /// Supervisor shutdown state label.
    pub shutdown_state: String,
}

/// Managed child state derived for dashboard display.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardManagedChildState {
    /// Child is active and should be displayed as running.
    Running,
    /// Child is paused.
    Paused,
    /// Child is quarantined.
    Quarantined,
    /// Child is removed.
    Removed,
}

impl From<ChildControlOperation> for DashboardManagedChildState {
    /// Converts a runtime control operation into a dashboard managed state.
    fn from(value: ChildControlOperation) -> Self {
        match value {
            ChildControlOperation::Active => Self::Running,
            ChildControlOperation::Paused => Self::Paused,
            ChildControlOperation::Quarantined => Self::Quarantined,
            ChildControlOperation::Removed => Self::Removed,
        }
    }
}

impl DashboardManagedChildState {
    /// Returns the stable dashboard label.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns the lifecycle label used by runtime rows.
    pub fn as_label(&self) -> &'static str {
        match self {
            Self::Running => "running",
            Self::Paused => "paused",
            Self::Quarantined => "quarantined",
            Self::Removed => "removed",
        }
    }
}

/// Child control operation label for dashboard payloads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardChildControlOperation {
    /// Runtime state remains active.
    Active,
    /// Runtime state is paused.
    Paused,
    /// Runtime state is quarantined.
    Quarantined,
    /// Runtime state is removed or waiting for removal.
    Removed,
}

impl From<ChildControlOperation> for DashboardChildControlOperation {
    /// Converts a runtime control operation into a dashboard operation.
    fn from(value: ChildControlOperation) -> Self {
        match value {
            ChildControlOperation::Active => Self::Active,
            ChildControlOperation::Paused => Self::Paused,
            ChildControlOperation::Quarantined => Self::Quarantined,
            ChildControlOperation::Removed => Self::Removed,
        }
    }
}

/// Attempt status label for dashboard payloads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardChildAttemptStatus {
    /// Child attempt is starting.
    Starting,
    /// Child attempt is running.
    Running,
    /// Child attempt is ready.
    Ready,
    /// Child attempt is cancelling.
    Cancelling,
    /// Child attempt has stopped.
    Stopped,
}

impl From<ChildAttemptStatus> for DashboardChildAttemptStatus {
    /// Converts a runtime attempt status into a dashboard attempt status.
    fn from(value: ChildAttemptStatus) -> Self {
        match value {
            ChildAttemptStatus::Starting => Self::Starting,
            ChildAttemptStatus::Running => Self::Running,
            ChildAttemptStatus::Ready => Self::Ready,
            ChildAttemptStatus::Cancelling => Self::Cancelling,
            ChildAttemptStatus::Stopped => Self::Stopped,
        }
    }
}

/// Stop state label for dashboard payloads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardChildStopState {
    /// No stop action is in progress.
    Idle,
    /// No active attempt exists.
    NoActiveAttempt,
    /// Cancellation was delivered.
    CancelDelivered,
    /// Stop completed.
    Completed,
    /// Stop failed.
    Failed,
}

impl From<ChildStopState> for DashboardChildStopState {
    /// Converts a runtime stop state into a dashboard stop state.
    fn from(value: ChildStopState) -> Self {
        match value {
            ChildStopState::Idle => Self::Idle,
            ChildStopState::NoActiveAttempt => Self::NoActiveAttempt,
            ChildStopState::CancelDelivered => Self::CancelDelivered,
            ChildStopState::Completed => Self::Completed,
            ChildStopState::Failed => Self::Failed,
        }
    }
}

/// Readiness state label for dashboard payloads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardReadinessState {
    /// Readiness has not been reported.
    Unreported,
    /// Child reported readiness.
    Ready,
    /// Child reported that it is not ready.
    NotReady,
}

impl From<ReadinessState> for DashboardReadinessState {
    /// Converts a runtime readiness state into a dashboard readiness state.
    fn from(value: ReadinessState) -> Self {
        match value {
            ReadinessState::Unreported => Self::Unreported,
            ReadinessState::Ready => Self::Ready,
            ReadinessState::NotReady => Self::NotReady,
        }
    }
}

impl DashboardReadinessState {
    /// Returns the stable dashboard label.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns the readiness label used by runtime rows.
    pub fn as_label(&self) -> &'static str {
        match self {
            Self::Unreported => "unreported",
            Self::Ready => "ready",
            Self::NotReady => "not_ready",
        }
    }
}

/// Failure phase label for dashboard payloads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardChildControlFailurePhase {
    /// Waiting for completion failed.
    WaitCompletion,
}

impl From<ChildControlFailurePhase> for DashboardChildControlFailurePhase {
    /// Converts a runtime failure phase into a dashboard failure phase.
    fn from(value: ChildControlFailurePhase) -> Self {
        match value {
            ChildControlFailurePhase::WaitCompletion => Self::WaitCompletion,
        }
    }
}

/// Liveness facts shown by dashboard runtime records.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardChildLivenessState {
    /// Last heartbeat as Unix nanoseconds.
    pub last_heartbeat_at_unix_nanos: Option<u128>,
    /// Whether the heartbeat is stale.
    pub heartbeat_stale: bool,
    /// Latest readiness state.
    pub readiness: DashboardReadinessState,
}

impl DashboardChildLivenessState {
    /// Converts runtime liveness into a dashboard liveness model.
    ///
    /// # Arguments
    ///
    /// - `value`: Runtime liveness state.
    ///
    /// # Returns
    ///
    /// Returns a dashboard liveness state.
    pub fn from_liveness(value: &ChildLivenessState) -> Self {
        Self {
            last_heartbeat_at_unix_nanos: value.last_heartbeat_at_unix_nanos,
            heartbeat_stale: value.heartbeat_stale,
            readiness: DashboardReadinessState::from(value.readiness),
        }
    }
}

/// Restart limit facts shown by dashboard runtime records.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardRestartLimitState {
    /// Restart accounting window in milliseconds.
    pub window_millis: u128,
    /// Restart limit inside the window.
    pub limit: u32,
    /// Restart count used so far.
    pub used: u32,
    /// Remaining restart count.
    pub remaining: u32,
    /// Whether the restart limit is exhausted.
    pub exhausted: bool,
    /// Last update timestamp in Unix nanoseconds.
    pub updated_at_unix_nanos: u128,
}

impl DashboardRestartLimitState {
    /// Converts runtime restart limit into a dashboard restart limit model.
    ///
    /// # Arguments
    ///
    /// - `value`: Runtime restart limit state.
    ///
    /// # Returns
    ///
    /// Returns a dashboard restart limit state.
    pub fn from_restart_limit(value: &RestartLimitState) -> Self {
        Self {
            window_millis: value.window.as_millis(),
            limit: value.limit,
            used: value.used,
            remaining: value.remaining,
            exhausted: value.exhausted,
            updated_at_unix_nanos: value.updated_at_unix_nanos,
        }
    }
}

/// Structured control failure shown by dashboard payloads.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardChildControlFailure {
    /// Failure phase.
    pub phase: DashboardChildControlFailurePhase,
    /// Human-readable failure reason.
    pub reason: String,
    /// Whether callers can retry.
    pub recoverable: bool,
}

impl DashboardChildControlFailure {
    /// Converts a runtime control failure into a dashboard failure model.
    ///
    /// # Arguments
    ///
    /// - `value`: Runtime control failure.
    ///
    /// # Returns
    ///
    /// Returns a dashboard control failure.
    pub fn from_failure(value: &ChildControlFailure) -> Self {
        Self {
            phase: DashboardChildControlFailurePhase::from(value.phase),
            reason: value.reason.clone(),
            recoverable: value.recoverable,
        }
    }
}

/// Dashboard projection for generation fencing phases.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardGenerationFencePhase {
    /// No fencing wait state.
    Open,
    /// Restart accepted; waiting for the old attempt to stop.
    WaitingForOldStop,
    /// Abort escalated against the outdated attempt.
    AbortingOld,
    /// Fence cleared; eligible to spawn the queued generation when other gates permit.
    ReadyToStart,
    /// Record removed or fencing closed due to supervisor shutdown semantics.
    Closed,
}

impl From<GenerationFencePhase> for DashboardGenerationFencePhase {
    /// Mirrors the runtime enumeration into dashboard JSON payloads.
    fn from(value: GenerationFencePhase) -> Self {
        match value {
            GenerationFencePhase::Open => Self::Open,
            GenerationFencePhase::WaitingForOldStop => Self::WaitingForOldStop,
            GenerationFencePhase::AbortingOld => Self::AbortingOld,
            GenerationFencePhase::ReadyToStart => Self::ReadyToStart,
            GenerationFencePhase::Closed => Self::Closed,
        }
    }
}

/// Dashboard projection for generation fencing decisions tied to restart commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DashboardGenerationFenceDecision {
    /// Immediately spawned due to lacking an active attempt.
    StartedImmediately,
    /// Queued until an active attempt observes stop semantics.
    QueuedAfterStop,
    /// Duplicate restart merged onto the existing pending fence request.
    AlreadyPending,
    /// Supervisor shutdown prevents further restart progress.
    BlockedByShutdown,
    /// Structured rejection surfaced through dashboard conflicts.
    Rejected,
}

impl From<GenerationFenceDecision> for DashboardGenerationFenceDecision {
    /// Maps runtime restart fence decisions onto dashboard labels.
    fn from(value: GenerationFenceDecision) -> Self {
        match value {
            GenerationFenceDecision::StartedImmediately => Self::StartedImmediately,
            GenerationFenceDecision::QueuedAfterStop => Self::QueuedAfterStop,
            GenerationFenceDecision::AlreadyPending => Self::AlreadyPending,
            GenerationFenceDecision::BlockedByShutdown => Self::BlockedByShutdown,
            GenerationFenceDecision::Rejected => Self::Rejected,
        }
    }
}

/// Dashboard projection covering optional pending restart fingerprints.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardPendingRestartSummary {
    /// Old generation locked during the queued restart handshake.
    pub old_generation: u64,
    /// Old attempt locked during the queued restart handshake.
    pub old_attempt: u64,
    /// Target generation that should start after cleanup completes.
    pub target_generation: u64,
}

impl From<&PendingRestartSummary> for DashboardPendingRestartSummary {
    /// Converts numeric runtime identifiers into wire-friendly dashboard fields.
    fn from(value: &PendingRestartSummary) -> Self {
        Self {
            old_generation: value.old_generation.value,
            old_attempt: value.old_attempt.value,
            target_generation: value.target_generation.value,
        }
    }
}

/// Dashboard projection of structured generation fencing command outcomes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardGenerationFenceOutcome {
    /// High-level fencing decision surfaced to operators.
    pub decision: DashboardGenerationFenceDecision,
    /// Serialized old generation counterpart when meaningful.
    pub old_generation: Option<u64>,
    /// Serialized old attempt counterpart when meaningful.
    pub old_attempt: Option<u64>,
    /// Serialized queued target generation counterpart when meaningful.
    pub target_generation: Option<u64>,
    /// Mirrors runtime cancel delivery semantics during restart flows.
    pub cancel_delivered: bool,
    /// Mirrors runtime abort delivery semantics during restart flows.
    pub abort_requested: bool,
    /// Optional structured failure propagated when decisions reject restart work.
    pub conflict: Option<DashboardChildControlFailure>,
}

impl From<&GenerationFenceOutcome> for DashboardGenerationFenceOutcome {
    /// Converts nested runtime payloads into serialized dashboard equivalents.
    fn from(outcome: &GenerationFenceOutcome) -> Self {
        Self {
            decision: outcome.decision.into(),
            old_generation: outcome.old_generation.map(|generation| generation.value),
            old_attempt: outcome.old_attempt.map(|attempt| attempt.value),
            target_generation: outcome.target_generation.map(|generation| generation.value),
            cancel_delivered: outcome.cancel_delivered,
            abort_requested: outcome.abort_requested,
            conflict: outcome
                .conflict
                .as_ref()
                .map(DashboardChildControlFailure::from_failure),
        }
    }
}

/// Dashboard projection of one child runtime record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardChildRuntimeRecord {
    /// Stable child identifier.
    pub child_id: String,
    /// Child path in the supervisor tree.
    pub child_path: String,
    /// Current active generation.
    pub generation: Option<u64>,
    /// Current active attempt.
    pub attempt: Option<u64>,
    /// Current attempt status.
    pub status: Option<DashboardChildAttemptStatus>,
    /// Current control operation.
    pub operation: DashboardChildControlOperation,
    /// Managed child state derived from operation.
    pub managed_child_state: DashboardManagedChildState,
    /// Current liveness state.
    pub liveness: DashboardChildLivenessState,
    /// Current restart limit state.
    pub restart_limit: DashboardRestartLimitState,
    /// Current stop progress.
    pub stop_state: DashboardChildStopState,
    /// Most recent control failure.
    pub failure: Option<DashboardChildControlFailure>,
    /// Generation fencing phase mirroring runtime projection.
    pub generation_fence_phase: DashboardGenerationFencePhase,
    /// Pending restart summary when the runtime still waits on the old attempt.
    pub pending_restart: Option<DashboardPendingRestartSummary>,
}

impl DashboardChildRuntimeRecord {
    /// Converts a runtime record into a dashboard runtime record.
    ///
    /// # Arguments
    ///
    /// - `record`: Runtime child record returned by current state.
    ///
    /// # Returns
    ///
    /// Returns a dashboard runtime record.
    pub fn from_runtime_record(record: &ChildRuntimeRecord) -> Self {
        Self {
            child_id: record.child_id.to_string(),
            child_path: record.path.to_string(),
            generation: record.generation.map(|generation| generation.value),
            attempt: record.attempt.map(|attempt| attempt.value),
            status: record.status.map(DashboardChildAttemptStatus::from),
            operation: DashboardChildControlOperation::from(record.operation),
            managed_child_state: DashboardManagedChildState::from(record.operation),
            liveness: DashboardChildLivenessState::from_liveness(&record.liveness),
            restart_limit: DashboardRestartLimitState::from_restart_limit(&record.restart_limit),
            stop_state: DashboardChildStopState::from(record.stop_state),
            failure: record
                .failure
                .as_ref()
                .map(DashboardChildControlFailure::from_failure),
            generation_fence_phase: record.generation_fence_phase.into(),
            pending_restart: record
                .pending_restart
                .as_ref()
                .map(DashboardPendingRestartSummary::from),
        }
    }
}

/// Dashboard projection of a runtime current state result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardCurrentState {
    /// Number of children known to the control loop.
    pub child_count: usize,
    /// Whether tree shutdown has completed.
    pub shutdown_completed: bool,
    /// Runtime state records for declared children.
    pub child_runtime_records: Vec<DashboardChildRuntimeRecord>,
}

impl DashboardCurrentState {
    /// Converts a runtime current state into a dashboard current state.
    ///
    /// # Arguments
    ///
    /// - `state`: Runtime current state.
    ///
    /// # Returns
    ///
    /// Returns a dashboard current state.
    pub fn from_current_state(state: &CurrentState) -> Self {
        Self {
            child_count: state.child_count,
            shutdown_completed: state.shutdown_completed,
            child_runtime_records: state
                .child_runtime_records
                .iter()
                .map(DashboardChildRuntimeRecord::from_runtime_record)
                .collect(),
        }
    }
}

/// Dashboard projection of a child control command result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DashboardChildControlResult {
    /// Stable child identifier.
    pub child_id: String,
    /// Active attempt targeted by the command.
    pub attempt: Option<u64>,
    /// Active generation targeted by the command.
    pub generation: Option<u64>,
    /// Control operation before command handling.
    pub operation_before: DashboardChildControlOperation,
    /// Control operation after command handling.
    pub operation_after: DashboardChildControlOperation,
    /// Managed child state before command handling.
    pub managed_child_state_before: DashboardManagedChildState,
    /// Managed child state after command handling.
    pub managed_child_state_after: DashboardManagedChildState,
    /// Current attempt status.
    pub status: Option<DashboardChildAttemptStatus>,
    /// Whether this command delivered cancellation.
    pub cancel_delivered: bool,
    /// Stop progress after command handling.
    pub stop_state: DashboardChildStopState,
    /// Current restart limit state.
    pub restart_limit: DashboardRestartLimitState,
    /// Current liveness state.
    pub liveness: DashboardChildLivenessState,
    /// Whether this command reused existing state idempotently.
    pub idempotent: bool,
    /// Current failure reason.
    pub failure: Option<DashboardChildControlFailure>,
    /// Optional serialized generation fence outcome for restart-style commands.
    pub generation_fence: Option<DashboardGenerationFenceOutcome>,
}

impl DashboardChildControlResult {
    /// Converts a runtime child control result into a dashboard control result.
    ///
    /// # Arguments
    ///
    /// - `outcome`: Runtime child control result.
    ///
    /// # Returns
    ///
    /// Returns a dashboard child control result.
    pub fn from_child_control_result(outcome: &RuntimeChildControlResult) -> Self {
        Self {
            child_id: outcome.child_id.to_string(),
            attempt: outcome.attempt.map(|attempt| attempt.value),
            generation: outcome.generation.map(|generation| generation.value),
            operation_before: DashboardChildControlOperation::from(outcome.operation_before),
            operation_after: DashboardChildControlOperation::from(outcome.operation_after),
            managed_child_state_before: DashboardManagedChildState::from(outcome.operation_before),
            managed_child_state_after: DashboardManagedChildState::from(outcome.operation_after),
            status: outcome.status.map(DashboardChildAttemptStatus::from),
            cancel_delivered: outcome.cancel_delivered,
            stop_state: DashboardChildStopState::from(outcome.stop_state),
            restart_limit: DashboardRestartLimitState::from_restart_limit(&outcome.restart_limit),
            liveness: DashboardChildLivenessState::from_liveness(&outcome.liveness),
            idempotent: outcome.idempotent,
            failure: outcome
                .failure
                .as_ref()
                .map(DashboardChildControlFailure::from_failure),
            generation_fence: outcome
                .generation_fence
                .as_ref()
                .map(DashboardGenerationFenceOutcome::from),
        }
    }
}

/// Command result shape returned through dashboard state deltas.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DashboardCommandResult {
    /// Child was accepted by the control loop.
    ChildAdded {
        /// Child manifest stored by the runtime.
        child_manifest: String,
    },
    /// Child control result after a command.
    ChildControl {
        /// Dashboard child control result.
        outcome: DashboardChildControlResult,
    },
    /// Current state query result.
    CurrentState {
        /// Runtime current state.
        state: DashboardCurrentState,
    },
    /// Shutdown command result.
    Shutdown {
        /// Shutdown result serialized by the shutdown module.
        result: Value,
    },
}

impl DashboardCommandResult {
    /// Converts a runtime command result into a dashboard command result.
    ///
    /// # Arguments
    ///
    /// - `result`: Runtime command result.
    ///
    /// # Returns
    ///
    /// Returns a dashboard command result.
    pub fn from_command_result(result: &CommandResult) -> Result<Self, serde_json::Error> {
        match result {
            CommandResult::ChildAdded { child_manifest } => Ok(Self::ChildAdded {
                child_manifest: child_manifest.clone(),
            }),
            CommandResult::ChildControl { outcome } => Ok(Self::ChildControl {
                outcome: DashboardChildControlResult::from_child_control_result(outcome),
            }),
            CommandResult::CurrentState { state } => Ok(Self::CurrentState {
                state: DashboardCurrentState::from_current_state(state),
            }),
            CommandResult::Shutdown { result } => Ok(Self::Shutdown {
                result: serde_json::to_value(result)?,
            }),
        }
    }
}

/// Serializes a runtime command result using the dashboard return model.
///
/// # Arguments
///
/// - `result`: Runtime command result.
///
/// # Returns
///
/// Returns a JSON value with the dashboard command result shape.
pub fn dashboard_command_result_value(result: &CommandResult) -> Result<Value, serde_json::Error> {
    serde_json::to_value(DashboardCommandResult::from_command_result(result)?)
}

/// Derives the managed child state that corresponds to an operation.
///
/// # Arguments
///
/// - `operation`: Runtime control operation.
///
/// Converts a child runtime record into the existing dashboard runtime row.
///
/// # Arguments
///
/// - `record`: Runtime child record returned by current state.
/// - `shutdown_completed`: Whether the supervisor shutdown has completed.
///
/// # Returns
///
/// Returns a dashboard runtime row that preserves the existing UI list shape.
pub fn runtime_state_from_child_runtime_record(
    record: &ChildRuntimeRecord,
    shutdown_completed: bool,
) -> RuntimeState {
    let managed_child_state = DashboardManagedChildState::from(record.operation);
    let readiness = DashboardReadinessState::from(record.liveness.readiness);
    RuntimeState {
        child_path: record.path.to_string(),
        lifecycle_state: managed_child_state.as_label().to_owned(),
        health: if record.liveness.heartbeat_stale {
            "stale".to_owned()
        } else {
            "healthy".to_owned()
        },
        readiness: readiness.as_label().to_owned(),
        generation: record
            .generation
            .map(|generation| generation.value)
            .unwrap_or(0),
        child_start_count: record.attempt.map(|attempt| attempt.value).unwrap_or(0),
        restart_count: u64::from(record.restart_limit.used),
        last_failure: record
            .failure
            .as_ref()
            .map(|failure| failure.reason.clone()),
        last_policy_decision: Some(format!(
            "restart_limit_remaining={}",
            record.restart_limit.remaining
        )),
        shutdown_state: if shutdown_completed {
            "completed".to_owned()
        } else {
            "running".to_owned()
        },
    }
}

/// Event record streamed from a target process.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct EventRecord {
    /// Target process identifier.
    pub target_id: String,
    /// Target-local monotonic sequence.
    pub sequence: u64,
    /// Correlation identifier.
    pub correlation_id: String,
    /// Event type label.
    pub event_type: String,
    /// Severity label.
    pub severity: String,
    /// Target path.
    pub target_path: String,
    /// Optional child identifier.
    pub child_id: Option<String>,
    /// Occurred time as Unix nanoseconds.
    pub occurred_at_unix_nanos: u128,
    /// Configuration version.
    pub config_version: String,
    /// Event payload.
    pub payload: Value,
}

/// Log record streamed from a target process.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct LogRecord {
    /// Target process identifier.
    pub target_id: String,
    /// Optional target-local sequence.
    pub sequence: Option<u64>,
    /// Optional correlation identifier.
    pub correlation_id: Option<String>,
    /// Severity label.
    pub severity: String,
    /// Log message.
    pub message: String,
    /// Structured log fields.
    pub fields: BTreeMap<String, String>,
    /// Occurred time as Unix nanoseconds.
    pub occurred_at_unix_nanos: u128,
}

/// Supported control command names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ControlCommandKind {
    /// Restart a child.
    RestartChild,
    /// Pause a child.
    PauseChild,
    /// Resume a child.
    ResumeChild,
    /// Quarantine a child.
    QuarantineChild,
    /// Remove a child.
    RemoveChild,
    /// Add a child.
    AddChild,
    /// Shut down the whole tree.
    ShutdownTree,
}

/// Target selector for a control command.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ControlCommandTarget {
    /// Optional child path for child-scoped commands.
    pub child_path: Option<String>,
    /// Optional child manifest for add-child commands.
    pub child_manifest: Option<String>,
}

/// Control command request forwarded by relay to target IPC.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ControlCommandRequest {
    /// Command identifier.
    pub command_id: String,
    /// Target process identifier.
    pub target_id: String,
    /// Command kind.
    pub command: ControlCommandKind,
    /// Command target.
    pub target: ControlCommandTarget,
    /// Non-empty reason.
    pub reason: String,
    /// Authenticated requester derived by relay.
    pub requested_by: String,
    /// Whether dangerous command confirmation is present.
    pub confirmed: bool,
    /// Request time as Unix nanoseconds.
    pub requested_at_unix_nanos: u128,
}

/// Control command result returned by target IPC.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ControlCommandResult {
    /// Command identifier.
    pub command_id: String,
    /// Target process identifier.
    pub target_id: String,
    /// Whether target accepted the command.
    pub accepted: bool,
    /// Status label.
    pub status: String,
    /// Optional structured error.
    pub error: Option<crate::dashboard::error::DashboardError>,
    /// Optional state delta.
    pub state_delta: Option<Value>,
    /// Completion time as Unix nanoseconds.
    pub completed_at_unix_nanos: Option<u128>,
}

/// Audit event emitted for accepted, rejected, and completed commands.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct AuditEvent {
    /// Audit event identifier.
    pub audit_id: String,
    /// Remote identity summary.
    pub identity: String,
    /// Target process identifier.
    pub target_id: String,
    /// Command identifier.
    pub command_id: String,
    /// Command kind.
    pub command: ControlCommandKind,
    /// Command target.
    pub target: ControlCommandTarget,
    /// Operator-provided reason.
    pub reason: String,
    /// Result summary.
    pub result: String,
    /// Occurred time as Unix nanoseconds.
    pub occurred_at_unix_nanos: u128,
}