mecha10-core 0.6.5

Mecha10 core runtime and foundational types
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
use crate::{Context, HealthStatus, NodeState, Result};
use async_trait::async_trait;
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};

/// Node health reporting priority
///
/// Determines heartbeat frequency and timeout thresholds based on
/// node criticality. Safety-critical nodes report more frequently.
///
/// # Priority Levels
///
/// | Priority | Interval | TTL | Timeout | Use Case |
/// |----------|----------|-----|---------|----------|
/// | Critical | 1s | 5s | 3s | motor-controller, estop |
/// | Normal | 5s | 60s | 15s | sensors, AI nodes |
/// | Background | 30s | 120s | 90s | logging, diagnostics |
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// // Create config with critical priority
/// let config = HealthReportingConfig::critical();
///
/// // Or specify priority explicitly
/// let config = HealthReportingConfig {
///     priority: HealthPriority::Critical,
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthPriority {
    /// Safety-critical nodes that require immediate failure detection.
    ///
    /// Examples: motor-controller, estop, safety-monitor
    ///
    /// - Interval: 1 second
    /// - TTL: 5 seconds
    /// - Timeout: 3 seconds
    Critical,

    /// Standard operational nodes (default).
    ///
    /// Examples: camera, sensors, simulator
    ///
    /// - Interval: 5 seconds
    /// - TTL: 60 seconds
    /// - Timeout: 15 seconds
    #[default]
    Normal,

    /// Background/auxiliary nodes where delayed detection is acceptable.
    ///
    /// Examples: logging, telemetry, diagnostics
    ///
    /// - Interval: 30 seconds
    /// - TTL: 120 seconds
    /// - Timeout: 90 seconds
    Background,
}

impl HealthPriority {
    /// Per-variant health-monitoring profile: (heartbeat interval, Redis TTL in seconds,
    /// unresponsive timeout). Previously `interval`/`ttl_seconds`/`timeout` each had their own
    /// 3-arm match over `Self`, which cargo-dupes flagged as duplicate match shapes; the
    /// per-variant values are only defined once here, and the public getters below are plain
    /// field projections.
    const fn profile(&self) -> (Duration, u64, Duration) {
        match self {
            Self::Critical => (Duration::from_secs(1), 5, Duration::from_secs(3)),
            Self::Normal => (Duration::from_secs(5), 60, Duration::from_secs(15)),
            Self::Background => (Duration::from_secs(30), 120, Duration::from_secs(90)),
        }
    }

    /// Get the heartbeat interval for this priority level
    pub const fn interval(&self) -> Duration {
        self.profile().0
    }

    /// Get the Redis TTL (time-to-live) in seconds for this priority level
    ///
    /// The TTL should be longer than the interval to allow for some jitter,
    /// but short enough that stale data expires quickly.
    pub const fn ttl_seconds(&self) -> u64 {
        self.profile().1
    }

    /// Get the timeout threshold for monitoring
    ///
    /// A node is considered unresponsive if no health report is received
    /// within this duration.
    pub const fn timeout(&self) -> Duration {
        self.profile().2
    }

    /// Get the timeout in microseconds (for comparison with timestamps)
    pub const fn timeout_micros(&self) -> u64 {
        self.timeout().as_micros() as u64
    }
}

impl std::fmt::Display for HealthPriority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Critical => write!(f, "critical"),
            Self::Normal => write!(f, "normal"),
            Self::Background => write!(f, "background"),
        }
    }
}

/// Configuration for node health reporting
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// // Default config (Normal priority, 5s interval)
/// let config = HealthReportingConfig::default();
///
/// // Critical priority (1s interval)
/// let config = HealthReportingConfig::critical();
///
/// // Background priority (30s interval)
/// let config = HealthReportingConfig::background();
///
/// // Custom config
/// let config = HealthReportingConfig {
///     enabled: true,
///     priority: HealthPriority::Normal,
///     store_history: false, // Disable history for high-frequency nodes
/// };
/// ```
#[derive(Debug, Clone)]
pub struct HealthReportingConfig {
    /// Whether health reporting is enabled (default: true)
    pub enabled: bool,

    /// Priority level determines interval and timeout (default: Normal)
    pub priority: HealthPriority,

    /// Whether to store health history in Redis (default: true)
    ///
    /// Disable for high-frequency critical nodes to reduce Redis load.
    /// History is stored as a sorted set with 24-hour retention.
    pub store_history: bool,
}

// duplicate: false positive — matches `InternalMotorState::default`
// (packages/drivers/motor/src/l298n/driver.rs) purely on the struct-literal-of-default-values
// AST shape; unrelated domains (node health-reporting cadence vs. an L298N motor driver's
// internal state) with no shared behavior to extract - matches the
// SecretsConfig::default/RedisConfig::default precedent in .dupes-ignore.toml.
impl Default for HealthReportingConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            priority: HealthPriority::Normal,
            store_history: true,
        }
    }
}

impl HealthReportingConfig {
    /// Shared constructor behind the `critical`/`background` presets, which are always
    /// enabled and only differ in priority and whether history is stored.
    fn with_priority(priority: HealthPriority, store_history: bool) -> Self {
        Self {
            enabled: true,
            priority,
            store_history,
        }
    }

    /// Create config for critical priority nodes (1s interval)
    pub fn critical() -> Self {
        Self::with_priority(HealthPriority::Critical, false)
    }

    /// Create config for normal priority nodes (5s interval)
    pub fn normal() -> Self {
        Self::default()
    }

    /// Create config for background priority nodes (30s interval)
    pub fn background() -> Self {
        Self::with_priority(HealthPriority::Background, true)
    }

    /// Get the effective interval based on priority
    pub fn interval(&self) -> Duration {
        self.priority.interval()
    }

    /// Get the effective TTL based on priority
    pub fn ttl_seconds(&self) -> u64 {
        self.priority.ttl_seconds()
    }
}

/// Trait for node configurations that specify an update rate
///
/// This trait provides a standard interface for nodes that publish at a fixed rate.
/// Implement this trait on your node's config struct to enable convenient rate-based
/// interval creation.
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// pub struct CameraConfig {
///     pub fps: f32,
///     pub width: u32,
///     pub height: u32,
/// }
///
/// impl RateConfig for CameraConfig {
///     fn rate_hz(&self) -> f32 {
///         self.fps
///     }
/// }
///
/// // Now you can use the config to create intervals easily:
/// # async fn example(config: CameraConfig) {
/// let mut interval = config.create_interval();
/// loop {
///     interval.tick().await;
///     // Publish at configured rate
/// }
/// # }
/// ```
pub trait RateConfig {
    /// Get the update rate in Hertz (cycles per second)
    fn rate_hz(&self) -> f32;

    /// Create a tokio interval from the configured rate
    ///
    /// This is a convenience method that converts the rate to a Duration
    /// and creates a tokio::time::Interval.
    fn create_interval(&self) -> tokio::time::Interval {
        let duration = Duration::from_secs_f32(1.0 / self.rate_hz());
        tokio::time::interval(duration)
    }

    /// Get the period (time between updates) as a Duration
    fn period(&self) -> Duration {
        Duration::from_secs_f32(1.0 / self.rate_hz())
    }
}

/// Helper methods for creating HealthStatus instances
pub trait HealthStatusExt {
    /// Create a healthy status
    fn healthy(message: impl Into<String>) -> Self;
    /// Create an unhealthy status
    fn unhealthy(message: impl Into<String>) -> Self;
}

impl HealthStatus {
    /// Shared constructor backing both [`HealthStatusExt::healthy`] and
    /// [`HealthStatusExt::unhealthy`] — the two only ever differed in the `healthy` flag and
    /// the default `failure_count` that goes with it.
    fn with_check(healthy: bool, failure_count: u32, message: impl Into<String>) -> Self {
        Self {
            healthy,
            last_check: crate::prelude::now_micros(),
            failure_count,
            message: Some(message.into()),
        }
    }
}

impl HealthStatusExt for HealthStatus {
    fn healthy(message: impl Into<String>) -> Self {
        Self::with_check(true, 0, message)
    }

    fn unhealthy(message: impl Into<String>) -> Self {
        Self::with_check(false, 1, message)
    }
}

/// Built-in node kind.
///
/// This is a deliberately *closed* set -- it drives 1:1 config-schema
/// resolution in `mecha10-schema-registry` (a node has exactly one config
/// struct), so it can't also double as an open-ended "what kind of thing is
/// this" label for custom/project-local nodes. See [`NodeImpl::NODE_TYPE`]
/// and the "Node type and tags" section of the Node Management doc
/// (<https://linear.app/laboratory-one/document/node-management-1b7f4324db40>)
/// for the full design rationale.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum NodeType {
    Imu,
    Camera,
    ImageClassifier,
    ObjectDetector,
    BehaviorExecutor,
    LlmCommand,
    Teleop,
    Motor,
    WebsocketBridge,
    VideoStreamer,
    Simulator,
    Speaker,
    Listener,
    Rl,
}

impl NodeType {
    /// Every built-in node type, in declaration order.
    ///
    /// `mecha10-schema-registry`'s `BUILTIN_NODE_TYPES` derives from this
    /// instead of maintaining its own parallel `&[&str]` list.
    pub const ALL: &'static [NodeType] = &[
        NodeType::Imu,
        NodeType::Camera,
        NodeType::ImageClassifier,
        NodeType::ObjectDetector,
        NodeType::BehaviorExecutor,
        NodeType::LlmCommand,
        NodeType::Teleop,
        NodeType::Motor,
        NodeType::WebsocketBridge,
        NodeType::VideoStreamer,
        NodeType::Simulator,
        NodeType::Speaker,
        NodeType::Listener,
        NodeType::Rl,
    ];

    /// The kebab-case wire identifier for this type, e.g. `"image-classifier"`.
    ///
    /// This is exactly the string `serde` would produce via
    /// `#[serde(rename_all = "kebab-case")]`, exposed as a plain `&str` for
    /// callers (like `mecha10-schema-registry`) that work with node-type
    /// identifiers as strings rather than JSON values.
    pub fn as_str(&self) -> &'static str {
        match self {
            NodeType::Imu => "imu",
            NodeType::Camera => "camera",
            NodeType::ImageClassifier => "image-classifier",
            NodeType::ObjectDetector => "object-detector",
            NodeType::BehaviorExecutor => "behavior-executor",
            NodeType::LlmCommand => "llm-command",
            NodeType::Teleop => "teleop",
            NodeType::Motor => "motor",
            NodeType::WebsocketBridge => "websocket-bridge",
            NodeType::VideoStreamer => "video-streamer",
            NodeType::Simulator => "simulator",
            NodeType::Speaker => "speaker",
            NodeType::Listener => "listener",
            NodeType::Rl => "rl",
        }
    }
}

impl std::fmt::Display for NodeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Capability tag describing something specific a node *does*.
///
/// Unlike [`NodeType`], this is meant to be usable by custom/project-local
/// nodes too -- see [`NodeImpl::NODE_TAGS`]. Each variant names a concrete
/// capability (never a structural/meta label like "publishes messages",
/// which is true of nearly every node and carries no routing information).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum NodeTag {
    Sensor,
    Inertial,
    Capture,
    Ai,
    Classifier,
    Detector,
    Vision,
    Planner,
    Control,
    Nlp,
    Input,
    Actuator,
    Motion,
    Relay,
    Websocket,
    Streamer,
    Video,
    Simulator,
    Logger,
}

/// Core trait that all Mecha10 nodes must implement.
///
/// This trait defines the lifecycle of a node:
/// 1. `init()` - Initialize the node with configuration
/// 2. `run()` - Main execution loop
/// 3. `shutdown()` - Graceful shutdown
/// 4. `health_check()` - Report health status
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// #[derive(Debug)]
/// struct MyNode {
///     config: MyConfig,
/// }
///
/// #[derive(Debug, Deserialize)]
/// struct MyConfig {
///     rate: f32,
/// }
///
/// #[async_trait]
/// impl NodeImpl for MyNode {
///     type Config = MyConfig;
///
///     async fn init(config: Self::Config) -> Result<Self> {
///         info!("Initializing node with rate: {}", config.rate);
///         Ok(Self { config })
///     }
///
///     async fn run(&mut self, ctx: &Context) -> Result<()> {
///         let mut images = ctx.subscribe(sensor::CAMERA_RGB).await?;
///
///         while let Some(image) = images.recv().await {
///             // Process image
///             info!("Received image: {}x{}", image.width, image.height);
///         }
///
///         Ok(())
///     }
/// }
/// ```
#[async_trait]
pub trait NodeImpl: Send + Sync + Debug + 'static {
    /// Configuration type for this node
    type Config: DeserializeOwned + Send + Sync + Debug;

    /// Built-in node type, if this is one of the framework-provided node
    /// kinds. `None` for custom/project-local nodes -- `NodeType` is
    /// deliberately closed (it drives 1:1 config-schema resolution in
    /// `mecha10-schema-registry`), so a custom node correctly stays `None`
    /// here rather than being forced to misrepresent itself as one of the
    /// built-in variants. This matches
    /// `mecha10-schema-registry::resolve_node_type`'s existing `None` ->
    /// generic-schema-fallback behavior for anything unrecognized.
    const NODE_TYPE: Option<NodeType> = None;

    /// Capability tags. Empty by default. Unlike `NODE_TYPE`,
    /// custom/project-local nodes are encouraged to set this -- tagging e.g.
    /// a custom lidar node `NodeTag::Sensor` lets it be picked up by any
    /// dashboard widget that requires that tag, without needing an entry in
    /// `mecha10-schema-registry` at all.
    const NODE_TAGS: &'static [NodeTag] = &[];

    /// Initialize the node with the given configuration.
    ///
    /// This is called once when the node starts. Use this to:
    /// - Load configuration
    /// - Initialize resources (models, connections, etc.)
    /// - Validate prerequisites
    ///
    /// # Errors
    ///
    /// Return an error if initialization fails. The node will not start.
    async fn init(config: Self::Config) -> Result<Self>
    where
        Self: Sized;

    /// Main execution loop for the node.
    ///
    /// This is where your node's business logic lives. Typical patterns:
    /// - Subscribe to topics and process messages
    /// - Run periodic tasks
    /// - Publish results
    ///
    /// This method should run indefinitely until:
    /// - The context is cancelled (shutdown requested)
    /// - An unrecoverable error occurs
    ///
    /// # Errors
    ///
    /// Return an error if the node encounters an unrecoverable error.
    /// The node will transition to Error state and shutdown.
    async fn run(&mut self, ctx: &Context) -> Result<()>;

    /// Graceful shutdown hook.
    ///
    /// Called when the node is shutting down. Use this to:
    /// - Close connections
    /// - Flush buffers
    /// - Save state
    /// - Release resources
    ///
    /// The default implementation does nothing.
    ///
    /// # Errors
    ///
    /// Errors during shutdown are logged but don't prevent shutdown.
    async fn shutdown(&mut self) -> Result<()> {
        Ok(())
    }

    /// Health check for monitoring.
    ///
    /// Called periodically to check node health. Use this to:
    /// - Report current state
    /// - Check resource usage
    /// - Validate connections
    ///
    /// The default implementation returns healthy status.
    async fn health_check(&self) -> HealthStatus {
        HealthStatus {
            healthy: true,
            last_check: crate::prelude::now_micros(),
            failure_count: 0,
            message: Some("Node is running".to_string()),
        }
    }

    /// Node-specific pre-run content check.
    ///
    /// This is the "prerun" layer that catches a bad node config *before* the
    /// node's main loop starts, rather than crashing deep inside `run()` -- e.g.
    /// a camera device path that doesn't exist, a model file that was never
    /// downloaded, or two GPIO pins wired to the same physical pin.
    ///
    /// Called once, after `init()` has already produced a fully-typed (and, per
    /// [`crate::config::Validate`], schema/shape-validated) `Self`, and before
    /// `run()` starts. Unlike `Validate::validate()` -- which only sees the raw
    /// deserialized config and runs during config loading -- `preflight()` runs
    /// on the initialized node, so it can also check state derived during
    /// `init()` (e.g. a resolved file path) rather than just raw config fields.
    ///
    /// The default implementation does nothing, so opting in is non-breaking for
    /// every existing `NodeImpl`.
    ///
    /// # Errors
    ///
    /// Return an error with an actionable message (see `node-runner`'s
    /// `preflight.rs` for the established convention: a `❌` header naming what
    /// failed, followed by numbered remediation steps) if the node should not
    /// start. The node will not run.
    fn preflight(&self) -> Result<()> {
        Ok(())
    }
}

/// Formats a `Debug` impl for a node whose controller field is a trait
/// object that can't derive `Debug` (e.g. `Box<dyn SomeController>`).
///
/// Shared by node types that expose `config`, a controller identified by
/// `controller_name` (typically `self.controller.name()`), and an
/// `update_counter` field.
pub fn fmt_node_with_controller(
    f: &mut std::fmt::Formatter<'_>,
    struct_name: &str,
    config: &impl Debug,
    controller_name: &str,
    update_counter: u64,
) -> std::fmt::Result {
    f.debug_struct(struct_name)
        .field("config", config)
        .field("controller", &controller_name)
        .field("update_counter", &update_counter)
        .finish()
}

/// Wrapper that manages the lifecycle of a NodeImpl.
///
/// This provides:
/// - State management
/// - Lifecycle orchestration
/// - Error handling
/// - Health monitoring
#[derive(Clone)]
pub struct Node<T: NodeImpl> {
    node: Arc<Mutex<T>>,
    state: Arc<Mutex<NodeState>>,
}

impl<T: NodeImpl> Node<T> {
    /// Create a new node from a configuration.
    ///
    /// This calls `NodeImpl::init()` and wraps the result in a Node.
    ///
    /// # Errors
    ///
    /// Returns an error if initialization fails.
    pub async fn from_config(config: T::Config) -> Result<Self> {
        info!("Initializing node");

        let node = T::init(config).await?;

        Ok(Self {
            node: Arc::new(Mutex::new(node)),
            state: Arc::new(Mutex::new(NodeState::Starting)),
        })
    }

    /// Start the node with the given context.
    ///
    /// This orchestrates the full lifecycle:
    /// 1. Run `preflight()` node-content checks
    /// 2. Transition to Running state
    /// 3. Call `run()`
    /// 4. Call `shutdown()` on completion or error
    /// 5. Transition to final state
    ///
    /// # Errors
    ///
    /// Returns an error if `preflight()` rejects the node's config, or if the
    /// node fails during execution.
    pub async fn start(&self, ctx: Context) -> Result<()> {
        {
            let node = self.node.lock().await;
            node.preflight()?;
        }

        {
            let mut state = self.state.lock().await;
            *state = NodeState::Running;
            info!("Node transitioned to Running state");
        }

        let result = {
            let mut node = self.node.lock().await;
            debug!("Starting node execution");
            node.run(&ctx).await
        };

        match result {
            Ok(()) => {
                info!("Node completed successfully");
                self.shutdown().await?;
            }
            Err(e) => {
                error!("Node failed with error: {}", e);
                {
                    let mut state = self.state.lock().await;
                    *state = NodeState::Crashed;
                }
                self.shutdown().await?;
                return Err(e);
            }
        }

        Ok(())
    }

    /// Gracefully shutdown the node.
    ///
    /// This calls `shutdown()` and transitions to Stopped state.
    pub async fn shutdown(&self) -> Result<()> {
        info!("Shutting down node");

        {
            let mut state = self.state.lock().await;
            *state = NodeState::Stopping;
        }

        let result = {
            let mut node = self.node.lock().await;
            node.shutdown().await
        };

        {
            let mut state = self.state.lock().await;
            *state = NodeState::Stopped;
            info!("Node stopped");
        }

        if let Err(e) = result {
            warn!("Error during shutdown: {}", e);
            return Err(e);
        }

        Ok(())
    }

    /// Get the current state of the node.
    pub async fn state(&self) -> NodeState {
        self.state.lock().await.clone()
    }

    /// Perform a health check on the node.
    pub async fn health_check(&self) -> HealthStatus {
        let node = self.node.lock().await;
        node.health_check().await
    }

    /// Check if the node is healthy.
    pub async fn is_healthy(&self) -> bool {
        matches!(self.state().await, NodeState::Running | NodeState::Starting)
    }
}

/// Run a node with the given configuration and context.
///
/// This is a convenience function that:
/// 1. Initializes the node from config
/// 2. Starts the node with the context
/// 3. Handles errors
///
/// # Arguments
///
/// * `config` - Node-specific configuration
/// * `ctx` - Execution context
/// * `health_config` - Health reporting configuration
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let config = MyConfig { rate: 10.0 };
///     let ctx = Context::new("my_node");
///
///     // Use default health reporting (Normal priority, 5s interval)
///     run_node::<MyNode>(config, ctx, HealthReportingConfig::default()).await?;
///
///     // Critical priority for safety-critical nodes (1s interval)
///     run_node::<MyNode>(config, ctx, HealthReportingConfig::critical()).await?;
///
///     // Background priority for auxiliary nodes (30s interval)
///     run_node::<MyNode>(config, ctx, HealthReportingConfig::background()).await?;
///
///     Ok(())
/// }
/// ```
pub async fn run_node<T: NodeImpl>(
    config: T::Config,
    ctx: Context,
    health_config: HealthReportingConfig,
) -> Result<()> {
    crate::prelude::init_logging();

    #[cfg(feature = "messaging")]
    crate::log_publisher::attach(ctx.node_id(), ctx.clone());

    let node = Node::<T>::from_config(config).await?;

    #[cfg(feature = "messaging")]
    {
        if health_config.enabled {
            let node_for_health = node.node.clone();
            let ctx_for_health = ctx.clone();
            let priority = health_config.priority;
            let report_interval = health_config.interval();
            let ttl_seconds = health_config.ttl_seconds();
            let store_history = health_config.store_history;

            tokio::spawn(async move {
                use crate::health::HealthReporter;

                let reporter = match HealthReporter::with_config_and_type_tags(
                    &ctx_for_health,
                    priority,
                    ttl_seconds,
                    store_history,
                    T::NODE_TYPE,
                    T::NODE_TAGS,
                )
                .await
                {
                    Ok(r) => r,
                    Err(e) => {
                        warn!("Health reporting disabled: {}", e);
                        return;
                    }
                };

                debug!(
                    "Health reporting enabled: priority={}, interval={:?}, ttl={}s, history={}",
                    priority, report_interval, ttl_seconds, store_history
                );

                let mut interval = tokio::time::interval(report_interval);

                loop {
                    interval.tick().await;
                    debug!("Health tick - checking node health");

                    let msg_status = match node_for_health.try_lock() {
                        Ok(node) => {
                            let status = node.health_check().await;
                            crate::messages::system::HealthStatus {
                                timestamp: status.last_check,
                                level: if status.healthy {
                                    crate::messages::system::HealthLevel::Ok
                                } else {
                                    crate::messages::system::HealthLevel::Error
                                },
                                message: status.message.unwrap_or_else(|| "No message".to_string()),
                                diagnostics: None,
                            }
                        }
                        Err(_) => {
                            debug!("Node busy, reporting as healthy");
                            crate::messages::system::HealthStatus {
                                timestamp: crate::prelude::now_micros(),
                                level: crate::messages::system::HealthLevel::Ok,
                                message: "Node running (busy)".to_string(),
                                diagnostics: None,
                            }
                        }
                    };

                    if let Err(e) = reporter.report(msg_status).await {
                        warn!("Failed to report health: {}", e);
                    } else {
                        tracing::trace!("Health report sent successfully");
                    }
                }
            });
        } else {
            info!("Health reporting disabled");
        }
    }
    #[cfg(not(feature = "messaging"))]
    let _ = &health_config;

    node.start(ctx).await
}

#[cfg(all(test, not(feature = "messaging")))]
mod tests {
    use super::*;
    use crate::error::Mecha10Error;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc as StdArc;

    #[derive(Debug, Default, serde::Deserialize)]
    struct FakeConfig;

    #[derive(Debug)]
    struct OkNode {
        ran: StdArc<AtomicBool>,
    }

    // duplicate: false positive — OkNode/RejectingPreflightNode are test-only fixtures whose
    // `init`/`run` bodies coincidentally match (both just flip the same `ran` flag on a fresh
    // `Self`); the module's `#[cfg(all(test, not(feature = "messaging")))]` attribute isn't a
    // bare `cfg(test)`, so it isn't stripped by dupes.toml's `exclude_tests`. The interesting
    // difference between the two fixtures is `preflight`, not `init`/`run`.
    #[async_trait]
    impl NodeImpl for OkNode {
        type Config = FakeConfig;

        async fn init(_config: Self::Config) -> Result<Self> {
            Ok(Self {
                ran: StdArc::new(AtomicBool::new(false)),
            })
        }

        async fn run(&mut self, _ctx: &Context) -> Result<()> {
            self.ran.store(true, Ordering::SeqCst);
            Ok(())
        }
    }

    #[derive(Debug)]
    struct RejectingPreflightNode {
        ran: StdArc<AtomicBool>,
    }

    // duplicate: false positive — see the note on `impl NodeImpl for OkNode` above.
    #[async_trait]
    impl NodeImpl for RejectingPreflightNode {
        type Config = FakeConfig;

        async fn init(_config: Self::Config) -> Result<Self> {
            Ok(Self {
                ran: StdArc::new(AtomicBool::new(false)),
            })
        }

        async fn run(&mut self, _ctx: &Context) -> Result<()> {
            self.ran.store(true, Ordering::SeqCst);
            Ok(())
        }

        fn preflight(&self) -> Result<()> {
            Err(Mecha10Error::Configuration("boom: bad node content".to_string()))
        }
    }

    #[tokio::test]
    async fn default_preflight_is_a_noop_and_run_still_executes() {
        let node = Node::<OkNode>::from_config(FakeConfig).await.unwrap();
        let ctx = Context::new("test-node-ok").await.unwrap();

        let ran_handle = { node.node.lock().await.ran.clone() };

        node.start(ctx).await.unwrap();

        assert!(ran_handle.load(Ordering::SeqCst), "run() should have executed");
    }

    #[tokio::test]
    async fn start_fails_fast_when_preflight_rejects_config_and_never_calls_run() {
        let node = Node::<RejectingPreflightNode>::from_config(FakeConfig).await.unwrap();
        let ctx = Context::new("test-node-rejecting").await.unwrap();

        let ran_handle = { node.node.lock().await.ran.clone() };

        let result = node.start(ctx).await;

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("boom: bad node content"));
        assert!(
            !ran_handle.load(Ordering::SeqCst),
            "run() must not execute when preflight() rejects the node"
        );
    }

    #[test]
    fn node_type_kebab_case_matches_existing_builtin_node_types_strings() {
        let expected: &[(NodeType, &str)] = &[
            (NodeType::Imu, "imu"),
            (NodeType::Camera, "camera"),
            (NodeType::ImageClassifier, "image-classifier"),
            (NodeType::ObjectDetector, "object-detector"),
            (NodeType::BehaviorExecutor, "behavior-executor"),
            (NodeType::LlmCommand, "llm-command"),
            (NodeType::Teleop, "teleop"),
            (NodeType::Motor, "motor"),
            (NodeType::WebsocketBridge, "websocket-bridge"),
            (NodeType::VideoStreamer, "video-streamer"),
            (NodeType::Simulator, "simulator"),
            (NodeType::Speaker, "speaker"),
            (NodeType::Listener, "listener"),
            (NodeType::Rl, "rl"),
        ];

        assert_eq!(expected.len(), NodeType::ALL.len());

        for (variant, kebab) in expected {
            let json = serde_json::to_string(variant).unwrap();
            assert_eq!(json, format!("\"{}\"", kebab));
            assert_eq!(variant.as_str(), *kebab);

            let round_tripped: NodeType = serde_json::from_str(&json).unwrap();
            assert_eq!(round_tripped, *variant);
        }
    }

    #[test]
    fn node_tag_kebab_case_matches_expected_strings() {
        let expected: &[(NodeTag, &str)] = &[
            (NodeTag::Sensor, "sensor"),
            (NodeTag::Inertial, "inertial"),
            (NodeTag::Capture, "capture"),
            (NodeTag::Ai, "ai"),
            (NodeTag::Classifier, "classifier"),
            (NodeTag::Detector, "detector"),
            (NodeTag::Vision, "vision"),
            (NodeTag::Planner, "planner"),
            (NodeTag::Control, "control"),
            (NodeTag::Nlp, "nlp"),
            (NodeTag::Input, "input"),
            (NodeTag::Actuator, "actuator"),
            (NodeTag::Motion, "motion"),
            (NodeTag::Relay, "relay"),
            (NodeTag::Websocket, "websocket"),
            (NodeTag::Streamer, "streamer"),
            (NodeTag::Video, "video"),
            (NodeTag::Simulator, "simulator"),
            (NodeTag::Logger, "logger"),
        ];

        for (variant, kebab) in expected {
            let json = serde_json::to_string(variant).unwrap();
            assert_eq!(json, format!("\"{}\"", kebab));

            let round_tripped: NodeTag = serde_json::from_str(&json).unwrap();
            assert_eq!(round_tripped, *variant);
        }
    }

    #[test]
    fn node_impl_defaults_node_type_to_none_and_tags_to_empty() {
        assert_eq!(OkNode::NODE_TYPE, None);
        assert!(OkNode::NODE_TAGS.is_empty());
    }
}