phoxal 0.35.0

Phoxal - production-oriented autonomous robot framework: the runtime engine and model (the api contract tree lives in phoxal-api, the typed bus in phoxal-bus).
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
//! `ParticipantLaunch` - the clap/env process launch contract.
//!
//! Participant binaries share one common `--flag` set with matching `PHOXAL_*`
//! env fallbacks. Clocked services and drivers additionally accept `--clock` /
//! `PHOXAL_CLOCK`; tools and simulators do not expose either input. Supervisors
//! and systemd units use env, while humans can use flags for bench runs. Flags
//! win over env through clap's native precedence, and `--help` is the
//! user-facing contract documentation.

use std::path::PathBuf;

use anyhow::Context;
use clap::{CommandFactory, FromArgMatches};
use serde::{Deserialize, Serialize};

/// Default bounded shutdown grace, in milliseconds.
pub const DEFAULT_SHUTDOWN_GRACE_MS: u64 = 2000;

/// Public env variable names for the participant launch contract.
pub mod env {
    /// Bus-unique participant id.
    pub const PARTICIPANT_ID: &str = "PHOXAL_PARTICIPANT_ID";
    /// Robot id for the transport root.
    pub const ROBOT_ID: &str = "PHOXAL_ROBOT_ID";
    /// Bus namespace for the transport root.
    pub const NAMESPACE: &str = "PHOXAL_NAMESPACE";
    /// Root directory containing the resolved robot model.
    pub const ROBOT_ROOT: &str = "PHOXAL_ROBOT_ROOT";
    /// Component instance id for driver launches.
    pub const COMPONENT_INSTANCE: &str = "PHOXAL_COMPONENT_INSTANCE";
    /// Comma-separated Zenoh connect endpoints.
    pub const CONNECT: &str = "PHOXAL_CONNECT";
    /// Inline JSON participant config block.
    pub const CONFIG: &str = "PHOXAL_CONFIG";
    /// Clock mode for services and drivers: real or simulation.
    pub const CLOCK: &str = "PHOXAL_CLOCK";

    /// All env names in contract order.
    pub const ALL: &[&str] = &[
        PARTICIPANT_ID,
        ROBOT_ID,
        NAMESPACE,
        ROBOT_ROOT,
        COMPONENT_INSTANCE,
        CONNECT,
        CONFIG,
        CLOCK,
    ];
}

/// One participant's launch record.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParticipantLaunch {
    /// The bus-unique participant id (never the static participant/artifact id, D53).
    pub participant_id: String,
    /// The bus namespace (`robot.namespace`).
    pub namespace: String,
    /// The robot id (`robot.id`).
    pub robot_id: String,
    /// The resolved bus profile.
    #[serde(default)]
    pub bus: BusProfile,
    /// The robot clock mode. Tool and simulator launch policies never read this
    /// field; their scheduling is structurally host-driven.
    #[serde(default)]
    pub clock: ClockMode,
    /// The participant's typed config block (`services.<id>.config`), if any.
    #[serde(default)]
    pub config: Option<serde_json::Value>,
    /// The root that holds the robot model (`robot.yaml` + components + structure).
    /// Official participants read it via `SetupContext::robot()`; absent for a bare
    /// local run with no model.
    #[serde(default)]
    pub robot_root: Option<PathBuf>,
    /// The `robot.components` entry this participant drives (D47/D53). A
    /// component driver is launched once per instance, each with a distinct
    /// `participant_id` and its own `component_instance`; read via
    /// `SetupContext::component()`. Absent for non-driver participants.
    #[serde(default)]
    pub component_instance: Option<String>,
    /// Bounded shutdown grace, in milliseconds.
    #[serde(default = "default_grace")]
    pub shutdown_grace_ms: u64,
}

fn default_grace() -> u64 {
    DEFAULT_SHUTDOWN_GRACE_MS
}

impl ParticipantLaunch {
    /// A default launch for local runs: in-process bus, real clock, the given
    /// participant id (defaulting the namespace to `dev`, D38).
    pub fn local(participant_id: impl Into<String>, robot_id: impl Into<String>) -> Self {
        ParticipantLaunch {
            participant_id: participant_id.into(),
            namespace: "dev".to_string(),
            robot_id: robot_id.into(),
            bus: BusProfile::default(),
            clock: ClockMode::Real,
            config: None,
            robot_root: None,
            component_instance: None,
            shutdown_grace_ms: DEFAULT_SHUTDOWN_GRACE_MS,
        }
    }

    /// Set the robot model root for this launch.
    pub fn with_robot_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.robot_root = Some(root.into());
        self
    }

    /// Set the component instance this participant drives (driver launch, D47/D53).
    pub fn with_component_instance(mut self, instance: impl Into<String>) -> Self {
        self.component_instance = Some(instance.into());
        self
    }
}

/// The clap-derived launch fields shared by every participant binary.
#[derive(Debug, clap::Args)]
struct CommonLaunchCli {
    /// Bus-unique participant id. Defaults to the compiled participant artifact id.
    #[arg(
        long,
        env = env::PARTICIPANT_ID,
        hide_env_values = true,
        value_name = "ID"
    )]
    participant_id: Option<String>,

    /// Robot id for the transport root. Defaults to `robot` for local runs.
    #[arg(long, env = env::ROBOT_ID, hide_env_values = true, value_name = "ID")]
    robot_id: Option<String>,

    /// Bus namespace for the transport root.
    #[arg(
        long,
        env = env::NAMESPACE,
        hide_env_values = true,
        value_name = "NAMESPACE",
        default_value = "dev"
    )]
    namespace: Option<String>,

    /// Root directory containing the resolved robot model.
    #[arg(
        long,
        env = env::ROBOT_ROOT,
        hide_env_values = true,
        value_name = "DIR"
    )]
    robot_root: Option<PathBuf>,

    /// Component instance id for driver launches.
    #[arg(
        long,
        env = env::COMPONENT_INSTANCE,
        hide_env_values = true,
        value_name = "ID"
    )]
    component_instance: Option<String>,

    /// Comma-separated Zenoh connect endpoints. Empty means in-process.
    #[arg(
        long,
        env = env::CONNECT,
        hide_env_values = true,
        value_name = "ENDPOINTS"
    )]
    connect: Option<String>,

    /// Inline JSON participant config block.
    #[arg(
        long,
        env = env::CONFIG,
        hide_env_values = true,
        value_name = "JSON"
    )]
    config: Option<String>,
}

/// Launch contract for clock-selectable services and drivers.
#[derive(Debug, clap::Parser)]
#[command(
    name = "phoxal-participant",
    about = "Run a Phoxal participant.",
    long_about = None
)]
struct ClockedLaunchCli {
    #[command(flatten)]
    common: CommonLaunchCli,

    /// Clock mode for robot-state execution.
    #[arg(
        long,
        env = env::CLOCK,
        hide_env_values = true,
        value_enum,
        default_value_t = ClockMode::Real
    )]
    clock: ClockMode,
}

/// Launch contract for host/event-driven tools. It intentionally has no clock
/// flag or environment binding.
#[derive(Debug, clap::Parser)]
#[command(
    name = "phoxal-tool",
    about = "Run a Phoxal tool.",
    long_about = None
)]
struct ToolLaunchCli {
    #[command(flatten)]
    common: CommonLaunchCli,
}

/// Launch contract for host/Webots-driven simulators. It intentionally has no
/// clock flag or environment binding: a simulator produces or observes the
/// semantic simulation clock, but never schedules itself from that feed.
#[derive(Debug, clap::Parser)]
#[command(
    name = "phoxal-simulator",
    about = "Run a Phoxal simulator.",
    long_about = None
)]
struct SimulatorLaunchCli {
    #[command(flatten)]
    common: CommonLaunchCli,
}

impl CommonLaunchCli {
    fn into_launch(
        self,
        default_participant_id: &'static str,
        default_robot_id: &'static str,
    ) -> crate::Result<ParticipantLaunch> {
        let participant_id =
            nonempty_or(self.participant_id, || default_participant_id.to_string());
        let robot_id = nonempty_or(self.robot_id, || default_robot_id.to_string());
        let mut launch = ParticipantLaunch::local(participant_id, robot_id);
        launch.namespace = nonempty_or(self.namespace, || "dev".to_string());
        launch.robot_root = self.robot_root.filter(|path| !path.as_os_str().is_empty());
        launch.component_instance = self
            .component_instance
            .filter(|instance| !instance.is_empty());
        if let Some(endpoints) = self.connect.filter(|endpoints| !endpoints.is_empty()) {
            launch.bus.connect_endpoints = endpoints
                .split(',')
                .map(|endpoint| endpoint.trim().to_string())
                .filter(|endpoint| !endpoint.is_empty())
                .collect();
        }
        if let Some(config) = self.config.filter(|config| !config.is_empty()) {
            launch.config = Some(
                serde_json::from_str(&config)
                    .context("PHOXAL_CONFIG must be valid JSON for the participant config")?,
            );
        }
        Ok(launch)
    }
}

fn command_for<C: CommandFactory>(
    default_participant_id: &'static str,
    default_robot_id: &'static str,
) -> clap::Command {
    C::command()
        .mut_arg("participant_id", |arg| {
            arg.default_value(default_participant_id)
        })
        .mut_arg("robot_id", |arg| arg.default_value(default_robot_id))
}

/// Type-level launch contract emitted by the participant macros.
#[doc(hidden)]
pub trait ParticipantLaunchPolicy: Send + Sync + 'static {
    fn from_cli(
        default_participant_id: &'static str,
        default_robot_id: &'static str,
    ) -> crate::Result<ParticipantLaunch>;

    fn clock_mode(launch: &ParticipantLaunch) -> ClockMode;
}

/// Clock-selectable launch policy for services and drivers.
#[doc(hidden)]
pub struct ClockedParticipantLaunch;

impl ParticipantLaunchPolicy for ClockedParticipantLaunch {
    fn from_cli(
        default_participant_id: &'static str,
        default_robot_id: &'static str,
    ) -> crate::Result<ParticipantLaunch> {
        let matches =
            command_for::<ClockedLaunchCli>(default_participant_id, default_robot_id).get_matches();
        let cli = ClockedLaunchCli::from_arg_matches(&matches)?;
        let mut launch = cli
            .common
            .into_launch(default_participant_id, default_robot_id)?;
        launch.clock = cli.clock;
        Ok(launch)
    }

    fn clock_mode(launch: &ParticipantLaunch) -> ClockMode {
        launch.clock
    }
}

/// Clockless launch policy for tools.
#[doc(hidden)]
pub struct ToolParticipantLaunch;

impl ParticipantLaunchPolicy for ToolParticipantLaunch {
    fn from_cli(
        default_participant_id: &'static str,
        default_robot_id: &'static str,
    ) -> crate::Result<ParticipantLaunch> {
        let matches =
            command_for::<ToolLaunchCli>(default_participant_id, default_robot_id).get_matches();
        let cli = ToolLaunchCli::from_arg_matches(&matches)?;
        cli.common
            .into_launch(default_participant_id, default_robot_id)
    }

    fn clock_mode(_launch: &ParticipantLaunch) -> ClockMode {
        ClockMode::Real
    }
}

/// Clockless launch policy for host/Webots-driven simulators.
#[doc(hidden)]
pub struct SimulatorParticipantLaunch;

impl ParticipantLaunchPolicy for SimulatorParticipantLaunch {
    fn from_cli(
        default_participant_id: &'static str,
        default_robot_id: &'static str,
    ) -> crate::Result<ParticipantLaunch> {
        let matches = command_for::<SimulatorLaunchCli>(default_participant_id, default_robot_id)
            .get_matches();
        let cli = SimulatorLaunchCli::from_arg_matches(&matches)?;
        cli.common
            .into_launch(default_participant_id, default_robot_id)
    }

    fn clock_mode(_launch: &ParticipantLaunch) -> ClockMode {
        ClockMode::Real
    }
}

fn nonempty_or(value: Option<String>, default: impl FnOnce() -> String) -> String {
    value
        .filter(|value| !value.is_empty())
        .unwrap_or_else(default)
}

/// A resolved bus profile: where to connect. Empty endpoints = in-process.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct BusProfile {
    /// Zenoh connect endpoints; empty means in-process (local sim / tests).
    #[serde(default)]
    pub connect_endpoints: Vec<String>,
}

/// The clock mode the runner uses.
///
/// [`ClockMode::Real`] drives scheduled steps from wall time. [`ClockMode::Simulation`]
/// selects the logical-time step scheduler, but the live `simulation/clock`
/// bus feed is still future work; until that feed is wired, scheduled steps
/// wait for logical time to advance.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum ClockMode {
    /// Host-monotonic real time.
    #[default]
    Real,
    /// Drive scheduled steps from the authoritative `simulation/clock` feed.
    Simulation,
}

impl std::fmt::Display for ClockMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ClockMode::Real => f.write_str("real"),
            ClockMode::Simulation => f.write_str("simulation"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::error::ErrorKind;
    use serial_test::serial;

    fn clear_env() {
        // SAFETY: tests touching process env are `#[serial]`, so no other thread
        // reads/writes these vars concurrently.
        for key in env::ALL {
            unsafe { std::env::remove_var(key) };
        }
    }

    fn parse_clocked_from(args: &[&str]) -> crate::Result<ParticipantLaunch> {
        let matches = command_for::<ClockedLaunchCli>("default-id", "robot")
            .try_get_matches_from(args)
            .map_err(anyhow::Error::from)?;
        let cli = ClockedLaunchCli::from_arg_matches(&matches).map_err(anyhow::Error::from)?;
        let mut launch = cli.common.into_launch("default-id", "robot")?;
        launch.clock = cli.clock;
        Ok(launch)
    }

    fn parse_tool_from(args: &[&str]) -> crate::Result<ParticipantLaunch> {
        let matches = command_for::<ToolLaunchCli>("default-id", "robot")
            .try_get_matches_from(args)
            .map_err(anyhow::Error::from)?;
        let cli = ToolLaunchCli::from_arg_matches(&matches).map_err(anyhow::Error::from)?;
        cli.common.into_launch("default-id", "robot")
    }

    fn parse_simulator_from(args: &[&str]) -> crate::Result<ParticipantLaunch> {
        let matches = command_for::<SimulatorLaunchCli>("default-id", "robot")
            .try_get_matches_from(args)
            .map_err(anyhow::Error::from)?;
        let cli = SimulatorLaunchCli::from_arg_matches(&matches).map_err(anyhow::Error::from)?;
        cli.common.into_launch("default-id", "robot")
    }

    #[test]
    #[serial]
    fn cli_with_nothing_set_matches_local_defaults() {
        clear_env();
        let launch = parse_clocked_from(&["participant-bin"]).unwrap();
        assert_eq!(launch.participant_id, "default-id");
        assert_eq!(launch.robot_id, "robot");
        assert_eq!(launch.namespace, "dev");
        assert_eq!(launch.robot_root, None);
        assert_eq!(launch.config, None);
        assert!(launch.bus.connect_endpoints.is_empty());
        assert_eq!(launch.clock, ClockMode::Real);
    }

    #[test]
    #[serial]
    fn env_overrides_each_launch_field() {
        clear_env();
        // SAFETY: serialized test; see clear_env.
        unsafe {
            std::env::set_var(env::PARTICIPANT_ID, "tof-3");
            std::env::set_var(env::ROBOT_ID, "robot-a");
            std::env::set_var(env::NAMESPACE, "lab");
            std::env::set_var(env::ROBOT_ROOT, "/robot");
            std::env::set_var(env::COMPONENT_INSTANCE, "tof_front");
            std::env::set_var(env::CONNECT, "tcp/127.0.0.1:7447, tcp/127.0.0.1:7448");
            std::env::set_var(env::CONFIG, r#"{"rate_hz":10}"#);
            std::env::set_var(env::CLOCK, "simulation");
        }
        let launch = parse_clocked_from(&["participant-bin"]).unwrap();
        assert_eq!(launch.participant_id, "tof-3");
        assert_eq!(launch.robot_id, "robot-a");
        assert_eq!(launch.namespace, "lab");
        assert_eq!(
            launch.robot_root.as_deref(),
            Some(std::path::Path::new("/robot"))
        );
        assert_eq!(launch.component_instance.as_deref(), Some("tof_front"));
        assert_eq!(
            launch.bus.connect_endpoints,
            vec![
                "tcp/127.0.0.1:7447".to_string(),
                "tcp/127.0.0.1:7448".to_string()
            ]
        );
        assert_eq!(launch.config, Some(serde_json::json!({"rate_hz": 10})));
        assert_eq!(launch.clock, ClockMode::Simulation);
        clear_env();
    }

    #[test]
    #[serial]
    fn flags_take_precedence_over_env() {
        clear_env();
        // SAFETY: serialized test; see clear_env.
        unsafe {
            std::env::set_var(env::PARTICIPANT_ID, "env-participant");
            std::env::set_var(env::ROBOT_ID, "env-robot");
            std::env::set_var(env::NAMESPACE, "env-ns");
            std::env::set_var(env::ROBOT_ROOT, "/env-robot");
            std::env::set_var(env::COMPONENT_INSTANCE, "env-component");
            std::env::set_var(env::CONNECT, "tcp/env:7447");
            std::env::set_var(env::CONFIG, r#"{"source":"env"}"#);
            std::env::set_var(env::CLOCK, "simulation");
        }

        let launch = parse_clocked_from(&[
            "participant-bin",
            "--participant-id",
            "flag-participant",
            "--robot-id",
            "flag-robot",
            "--namespace",
            "flag-ns",
            "--robot-root",
            "/flag-robot",
            "--component-instance",
            "flag-component",
            "--connect",
            "tcp/flag:7447",
            "--config",
            r#"{"source":"flag"}"#,
            "--clock",
            "real",
        ])
        .unwrap();

        assert_eq!(launch.participant_id, "flag-participant");
        assert_eq!(launch.robot_id, "flag-robot");
        assert_eq!(launch.namespace, "flag-ns");
        assert_eq!(
            launch.robot_root.as_deref(),
            Some(std::path::Path::new("/flag-robot"))
        );
        assert_eq!(launch.component_instance.as_deref(), Some("flag-component"));
        assert_eq!(launch.bus.connect_endpoints, vec!["tcp/flag:7447"]);
        assert_eq!(launch.config, Some(serde_json::json!({"source": "flag"})));
        assert_eq!(launch.clock, ClockMode::Real);
        clear_env();
    }

    #[test]
    #[serial]
    fn rejects_invalid_config_json_and_clock() {
        clear_env();
        // SAFETY: serialized test; see clear_env.
        unsafe { std::env::set_var(env::CONFIG, "not json") };
        assert!(parse_clocked_from(&["participant-bin"]).is_err());
        unsafe {
            std::env::remove_var(env::CONFIG);
            std::env::set_var(env::CLOCK, "wallclock");
        }
        let err = command_for::<ClockedLaunchCli>("default-id", "robot")
            .try_get_matches_from(["participant-bin"])
            .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidValue);
        clear_env();
    }

    #[test]
    #[serial]
    fn help_lists_contract_env_names_without_values() {
        clear_env();
        // SAFETY: serialized test; see clear_env.
        unsafe { std::env::set_var(env::CONFIG, r#"{"secret":"do-not-print"}"#) };

        let mut help = Vec::new();
        command_for::<ClockedLaunchCli>("default-id", "robot")
            .write_long_help(&mut help)
            .unwrap();
        let help = String::from_utf8(help).unwrap();

        for (flag, env_name) in [
            ("--participant-id", env::PARTICIPANT_ID),
            ("--robot-id", env::ROBOT_ID),
            ("--namespace", env::NAMESPACE),
            ("--robot-root", env::ROBOT_ROOT),
            ("--component-instance", env::COMPONENT_INSTANCE),
            ("--connect", env::CONNECT),
            ("--config", env::CONFIG),
            ("--clock", env::CLOCK),
        ] {
            assert!(help.contains(flag), "help should list {flag}");
            assert!(help.contains(env_name), "help should list {env_name}");
        }
        assert!(!help.contains("do-not-print"));
        clear_env();
    }

    #[test]
    #[serial]
    fn tool_cli_has_no_clock_input() {
        clear_env();
        // A generic supervisor setting is invisible to the tool launch parser.
        // SAFETY: serialized test; see clear_env.
        unsafe { std::env::set_var(env::CLOCK, "simulation") };
        let launch = parse_tool_from(&["tool-bin"]).unwrap();
        assert_eq!(launch.clock, ClockMode::Real);

        let mut help = Vec::new();
        command_for::<ToolLaunchCli>("default-id", "robot")
            .write_long_help(&mut help)
            .unwrap();
        let help = String::from_utf8(help).unwrap();
        assert!(!help.contains("--clock"));
        assert!(!help.contains(env::CLOCK));

        for arguments in [
            vec!["tool-bin", "--clock", "simulation"],
            vec!["tool-bin", "--simulation"],
        ] {
            let error = command_for::<ToolLaunchCli>("default-id", "robot")
                .try_get_matches_from(arguments)
                .unwrap_err();
            assert_eq!(error.kind(), ErrorKind::UnknownArgument);
        }

        let mut programmatic = ParticipantLaunch::local("tool", "robot");
        programmatic.clock = ClockMode::Simulation;
        assert_eq!(
            ToolParticipantLaunch::clock_mode(&programmatic),
            ClockMode::Real
        );
        assert_eq!(
            ClockedParticipantLaunch::clock_mode(&programmatic),
            ClockMode::Simulation
        );
        clear_env();
    }

    #[test]
    #[serial]
    fn simulator_cli_has_no_clock_input() {
        clear_env();
        // A generic orchestrator setting is invisible to the simulator launch
        // parser. Simulators are always host/Webots driven.
        // SAFETY: serialized test; see clear_env.
        unsafe { std::env::set_var(env::CLOCK, "simulation") };
        let launch = parse_simulator_from(&["simulator-bin"]).unwrap();
        assert_eq!(launch.clock, ClockMode::Real);

        let mut help = Vec::new();
        command_for::<SimulatorLaunchCli>("default-id", "robot")
            .write_long_help(&mut help)
            .unwrap();
        let help = String::from_utf8(help).unwrap();
        assert!(!help.contains("--clock"));
        assert!(!help.contains(env::CLOCK));

        for arguments in [
            vec!["simulator-bin", "--clock", "simulation"],
            vec!["simulator-bin", "--simulation"],
        ] {
            let error = command_for::<SimulatorLaunchCli>("default-id", "robot")
                .try_get_matches_from(arguments)
                .unwrap_err();
            assert_eq!(error.kind(), ErrorKind::UnknownArgument);
        }

        let mut programmatic = ParticipantLaunch::local("simulator", "robot");
        programmatic.clock = ClockMode::Simulation;
        assert_eq!(
            SimulatorParticipantLaunch::clock_mode(&programmatic),
            ClockMode::Real
        );
        assert_eq!(
            ClockedParticipantLaunch::clock_mode(&programmatic),
            ClockMode::Simulation
        );
        clear_env();
    }
}