Skip to main content

phoxal_api/
lib.rs

1//! The single API layer (D60/D61/D1).
2//!
3//! This crate is the versioned API contract tree. It depends only on the
4//! [`phoxal-bus`](phoxal_bus) ABI floor (the contract primitive traits and the
5//! typed-topic builders) and the [`phoxal-macros`](phoxal_macros) proc-macros; it
6//! does **not** depend on the `phoxal` engine. A participant depends on both crates
7//! and imports the API tree directly with `use phoxal_api::v1 as api;`, so
8//! `phoxal_api::v1`, `phoxal_api::ApiVersion`, and `phoxal_api::ContractBody`
9//! are the canonical paths.
10//!
11//! # Stable and preview API versions
12//!
13//! An API version is a conventional `vN` module generated by
14//! [`phoxal_api_tree!`]. Each version module carries:
15//!
16//! - a zero-variant marker `enum Api {}` implementing [`ApiVersion`], whose
17//!   [`ApiVersion::ID`] is the module name (`"v1"` or `"v2"`);
18//! - the version-local wire bodies, one `pub mod` per contract node holding plain
19//!   serde structs/enums and their [`ContractBody`] impls;
20//! - an api-local `topic` builder rooted at `topic::new()`.
21//!
22//! `v1` is the current production surface and may change in place while the
23//! pre-stability topology is simplified. `v2` is the single preview surface for
24//! contracts that have not entered production. Preview work does not mint a new
25//! public version for each change.
26//! `v2` is authored as `preview version v2 { … }` and is available when the
27//! `preview-v2` Cargo feature is enabled. [`ApiVersion::IS_PREVIEW`] records the
28//! lifecycle without changing topics or wire bytes.
29//!
30//! [`Api`]: v1::Api
31//!
32//! # Per-field versions and per-contract identity
33//!
34//! A participant declares its bus surface with a companion
35//! `#[derive(phoxal::Api)]` handle struct.
36//! Each handle field names its own version-qualified contract type, so one
37//! participant may freely mix fields from modules such as `v1` and
38//! `v2`.
39//! The derive records each field's resolved [`ContractBody::VERSION`] and
40//! [`ContractBody::CONTRACT`] in the participant's embedded metadata and does
41//! not declare a participant-wide API version.
42//! Across the graph, compatibility is **name identity** (D1) - two participants
43//! interoperate on a contract iff they use the exact same version-qualified name
44//! (`v1::drive::Target`), which is real on the wire because the version
45//! is folded into the key ([`ContractBody::TOPIC`]). There is no `schema_id`: a
46//! stable contract type is immutable, so the name alone is the whole identity.
47//!
48//! # Plain serde wire bodies, provenance in metadata
49//!
50//! A wire body is just its serde encoding - there is no `{"v":…}` envelope or any
51//! other version tag inside the payload (D62). Identity lives entirely in the
52//! Zenoh key (the version-qualified [`ContractBody::TOPIC`]); the bus metadata
53//! alongside the encoded body carries only provenance (source + logical time) and
54//! the codec that produced the bytes - never schema/family/version. Keeping
55//! identity out of both the payload and the metadata means the body bytes for an
56//! unchanged contract are identical across codecs, and a receiver's per-key
57//! subscription is the whole fast-reject.
58//!
59//! # Topic
60//!
61//! [`ContractBody::TOPIC`] is derived from the contract node's path in the tree,
62//! never written by hand: the version, then the `/`-joined node path plus the
63//! topic leaf, with each dynamic node contributing a `{var}` placeholder, e.g.
64//! `v1/component/{instance}/motor/{capability}/command`. A fully static path
65//! has a literal key (`v1/drive/state`). Folding the version into the key
66//! (D1) is what makes two differently-versioned contracts physically distinct
67//! Zenoh keys - they cannot collide, so there is no `SCHEMA_ID`/`FAMILY` needed to
68//! disambiguate them.
69//!
70//! # The api-local topic builder
71//!
72//! Each version module exposes a `topic` builder that mirrors the node tree:
73//! `api::topic::new()` returns a root, one method per top-level node walks down the
74//! tree, a dynamic node's method takes its variable as `impl Display`, and a leaf
75//! method binds the topic's side-branded kind to its version-local body. For
76//! example `api::topic::new().drive().state()` yields a
77//! `Topic<Subscribe<drive::State>>` (the CLIENT observes the owner's `state`) over
78//! the version-qualified key `v1/drive/state`, and
79//! `api::topic::new().component("base").motor("left").command()` fills the dynamic
80//! segments to produce `v1/component/base/motor/left/command`. Because the
81//! builder is generated from the same tree as `TOPIC`, the built key and the
82//! documented key stay in lockstep.
83//!
84//! ## Owner side: `topic::internal`
85//!
86//! The PUBLIC `topic::new()...` chain above is the **client** side. The matching
87//! **owner** side lives at `api::topic::internal::new(cap)...` (L1 + L2, plan #00):
88//! the same node tree and keys, but the leaf brands flip so the owner gets the side
89//! it must take - `api::topic::internal::new(cap).drive().state()` is
90//! `Topic<Publish<drive::State>>` (the owner publishes its telemetry), and
91//! `api::topic::internal::new(cap).drive().target()` is `Topic<Subscribe<drive::Target>>`
92//! (the owner reads its command input). A query owner reaches its `ServeQuery`
93//! brand the same way. The `internal` chain is the deliberate, greppable owner
94//! opt-in; a participant acquires the topics of its OWN node through it and everything
95//! it consumes through the public chain.
96//!
97//! The `internal::new` entry requires the runner-minted owner capability
98//! ([`OwnerCap`](phoxal_bus::OwnerCap), Layer 2): a participant obtains it from
99//! `phoxal::SetupContext::owner_capability()` and passes it in. On the documented
100//! surface, owning a topic therefore cannot happen by accident - only with a
101//! capability the runner mints.
102
103use phoxal_macros::phoxal_api_tree;
104
105/// The contract primitive traits, re-exported from the `phoxal-bus` crate (the
106/// ABI floor) so they stay addressable at `phoxal_api::ApiVersion` /
107/// `phoxal_api::ContractBody`.
108///
109/// - [`ApiVersion`] is the marker trait identifying one API version (D60),
110///   implemented only by the zero-variant `enum Api {}` that [`phoxal_api_tree!`]
111///   generates inside each version module; its `ID` is the module name (`"v1"`).
112///   Its `IS_PREVIEW` const is lifecycle metadata only.
113/// - [`ContractBody`] is a version-local wire body (D61): a plain serde type
114///   bound to exactly one [`ApiVersion`] and one contract topic. Every body
115///   declared inside a [`phoxal_api_tree!`] node gets a generated impl; handles,
116///   `SetupContext` builders, and the `Service`/`Driver` derive assertions key
117///   off its `Api`/`TOPIC`. `TOPIC` is version-qualified (D1) and *is* the
118///   compatibility key - there is no `SCHEMA_ID`/`FAMILY`; its serde encoding
119///   *is* the wire payload, with no version envelope (D62).
120pub use phoxal_bus::{ApiVersion, ContractBody};
121
122phoxal_api_tree! {
123    version v1 {
124        drive {
125            /// Why actuation authority is in its current state.
126            enum StopReason {
127                NoTarget,
128                TargetStale,
129                TargetFromFuture,
130                TargetNotFinite,
131                ActuatorCommandNotFinite,
132                Inactive,
133                EmergencyStop,
134                Fault,
135            }
136
137            /// Whether the drive is actively commanding the actuators.
138            enum ActuatorAuthority {
139                Active,
140                Stopped,
141            }
142
143            /// A requested or limited planar velocity.
144            struct Target {
145                linear_x_mps: f32,
146                angular_z_radps: f32,
147                curvature_limit_radpm: Option<f32>,
148            }
149
150            /// The drive participant's published control state.
151            struct State {
152                target: Target,
153                limited_target: Target,
154                actuator_authority: ActuatorAuthority,
155                stop_reason: Option<StopReason>,
156                target_age_ns: Option<u64>,
157            }
158
159            topic target: command Target;
160            topic state: state State;
161        }
162
163        joint(joint) {
164            /// Per-joint position/velocity (and optional effort) on a dynamic
165            /// per-joint key.
166            struct JointState {
167                position_rad: f64,
168                velocity_radps: f64,
169                effort_nm: Option<f64>,
170            }
171
172            topic state: state JointState;
173        }
174
175        frame {
176            /// A parent → child rigid transform (translation + xyzw quaternion).
177            struct FrameTransform {
178                parent_frame_id: String,
179                child_frame_id: String,
180                translation_m: [f64; 3],
181                rotation_quat_xyzw: [f64; 4],
182                stamp_ns: Option<u64>,
183            }
184
185            /// Transforms that do not change over time.
186            struct StaticTransforms {
187                transforms: Vec<FrameTransform>,
188            }
189
190            /// The current transform tree.
191            struct Tree {
192                transforms: Vec<FrameTransform>,
193            }
194
195            /// Ask for the transform between two frames, optionally at a time.
196            struct LookupRequest {
197                target_frame_id: String,
198                source_frame_id: String,
199                at_ns: Option<u64>,
200            }
201
202            /// The resolved transform, or `None` if it is not available.
203            struct LookupResponse {
204                transform: Option<FrameTransform>,
205            }
206
207            topic tree: state Tree;
208            topic static_transforms: state StaticTransforms;
209            topic lookup: query LookupRequest => LookupResponse;
210        }
211
212        power {
213            /// A platform power command.
214            #[derive(Copy, Eq)]
215            enum Command {
216                Reboot,
217                Shutdown,
218            }
219
220            /// Where the power participant is in handling a command.
221            #[derive(Copy, Eq)]
222            enum Status {
223                Idle,
224                Rebooting,
225                ShuttingDown,
226                Failed,
227            }
228
229            /// Why a power command was rejected outright.
230            #[derive(Copy, Eq)]
231            #[serde(rename_all = "snake_case")]
232            enum RejectedReason {
233                HostIntegrationUnavailable,
234                CommandRejected,
235            }
236
237            /// Why an accepted power command later failed.
238            #[derive(Copy, Eq)]
239            #[serde(rename_all = "snake_case")]
240            enum FailedReason {
241                HostCommandFailed,
242            }
243
244            /// The power participant's published state.
245            struct State {
246                status: Status,
247                detail: Option<String>,
248            }
249
250            topic command: command Command;
251            topic state: state State;
252        }
253
254        motion {
255            struct Target {
256                linear_x_mps: f32,
257                angular_z_radps: f32,
258                curvature_limit_radpm: Option<f32>,
259            }
260
261            #[derive(Copy, Eq)]
262            #[serde(rename_all = "snake_case")]
263            enum Source {
264                Manual,
265                Navigation,
266                EmergencyStop,
267            }
268
269            #[derive(Copy, Eq)]
270            #[serde(rename_all = "snake_case")]
271            enum ZeroReason {
272                NoCandidate,
273                ManualCandidateStale,
274                NavigationCandidateStale,
275                ManualCandidateFromFuture,
276                NavigationCandidateFromFuture,
277                ManualCandidateNotFinite,
278                NavigationCandidateNotFinite,
279                EmergencyStopEngaged,
280                SafetyConstraintsUnavailable,
281                SafetyProtectiveStop,
282            }
283
284            #[derive(Copy, Eq)]
285            #[serde(rename_all = "snake_case")]
286            enum SafetyRuntime {
287                Absent,
288                Present,
289            }
290
291            struct ManualCommand {
292                linear_x_mps: f64,
293                angular_z_radps: f64,
294            }
295
296            #[derive(Eq)]
297            struct EmergencyStopRequest {
298                engaged: bool,
299            }
300
301            struct State {
302                manual_candidate_age_ns: Option<u64>,
303                autonomous_candidate_age_ns: Option<u64>,
304                safety_constraints_age_ns: Option<u64>,
305                selected_source: Option<Source>,
306                final_target: Target,
307                zero_reason: Option<ZeroReason>,
308                safety_runtime: SafetyRuntime,
309                software_estop_engaged: bool,
310                component_estop_blocked: bool,
311                active_safety_constraints: Vec<super::safety::Constraint>,
312            }
313
314            topic manual: command ManualCommand;
315            topic estop: command EmergencyStopRequest;
316            topic state: state State;
317        }
318
319        safety {
320            /// Why safety is stopping or limiting body motion.
321            #[derive(Copy, Eq)]
322            #[serde(rename_all = "snake_case")]
323            enum ConstraintReason {
324                WorldUnavailable,
325                MapUnavailable,
326                DrivableSpaceUnavailable,
327                LocalizationUnavailable,
328                LocalizationUncertain,
329                ObstacleProximity,
330                RangeSensorFault,
331                DriveFault,
332                BatteryLow,
333                BatteryCritical,
334                SpeedZone,
335                OperatorPolicy,
336            }
337
338            /// Typed origin of one constraint, suitable for operator diagnosis.
339            #[derive(Copy, Eq)]
340            #[serde(rename_all = "snake_case")]
341            enum ConstraintSourceKind {
342                WorldModel,
343                Map,
344                Localization,
345                Range,
346                Drive,
347                Battery,
348                Operator,
349            }
350
351            struct ConstraintSource {
352                kind: ConstraintSourceKind,
353                participant_id: String,
354                component_id: Option<String>,
355                capability_id: Option<String>,
356            }
357
358            struct Constraint {
359                reason: ConstraintReason,
360                source: ConstraintSource,
361                stop: bool,
362                max_linear_speed_mps: Option<f32>,
363                max_angular_speed_radps: Option<f32>,
364                observed_value: Option<f32>,
365                valid_from_ns: u64,
366                expires_at_ns: u64,
367            }
368
369            /// The sole safety-to-motion control product. Motion accepts it only
370            /// in the same epoch and before `expires_at_ns`.
371            struct MotionConstraints {
372                sequence: u64,
373                stop: bool,
374                max_linear_speed_mps: Option<f32>,
375                max_angular_speed_radps: Option<f32>,
376                constraints: Vec<Constraint>,
377                expires_at_ns: u64,
378            }
379
380            /// Operator-facing state mirrors the exact product consumed by motion.
381            struct State {
382                clear: bool,
383                motion: MotionConstraints,
384            }
385
386            topic constraints: state MotionConstraints;
387            topic state: state State;
388        }
389
390        navigation {
391            #[derive(Eq)]
392            struct RequestId {
393                value: String,
394            }
395
396            struct Pose {
397                x_m: f64,
398                y_m: f64,
399                yaw_rad: Option<f64>,
400            }
401
402            struct Path {
403                poses: Vec<Pose>,
404                map_revision: Option<u64>,
405            }
406
407            enum RequestKind {
408                GotoPose(Pose),
409                FollowPath(Path),
410                Cancel(RequestId),
411            }
412
413            struct Request {
414                request_id: RequestId,
415                kind: RequestKind,
416            }
417
418            enum State {
419                Idle,
420                Accepted(RequestId),
421                Running(RequestId),
422            }
423
424            #[derive(Copy, Eq)]
425            #[serde(rename_all = "snake_case")]
426            enum FailureReason {
427                LocalizationUnavailable,
428                MapUnavailable,
429                MapChanged,
430                NoPath,
431                Blocked,
432                Internal,
433            }
434
435            #[derive(Copy, Eq)]
436            #[serde(rename_all = "snake_case")]
437            enum RefusalReason {
438                Busy,
439                InvalidRequest,
440                Unsupported,
441            }
442
443            enum Outcome {
444                Succeeded,
445                Failed(FailureReason),
446                Refused(RefusalReason),
447                Cancelled,
448                TimedOut,
449            }
450
451            struct Progress {
452                request_id: RequestId,
453                distance_remaining_m: f64,
454                path_index: u32,
455            }
456
457            struct Result {
458                request_id: RequestId,
459                outcome: Outcome,
460            }
461
462            struct Candidate {
463                request_id: RequestId,
464                linear_x_mps: f32,
465                angular_z_radps: f32,
466            }
467
468            struct FrontierRequest {
469                map_revision: Option<u64>,
470            }
471
472            struct Frontier {
473                x_m: f64,
474                y_m: f64,
475                score: f32,
476                size: u32,
477            }
478
479            struct FrontierResponse {
480                frontier: Option<Frontier>,
481                map_revision: Option<u64>,
482            }
483
484            topic request: command Request;
485            topic state: state State;
486            topic progress: state Progress;
487            topic result: state Result;
488            topic candidate: state Candidate;
489            topic next_frontier: query FrontierRequest => FrontierResponse;
490        }
491
492        behavior {
493            #[derive(Eq)]
494            struct RequestId {
495                value: String,
496            }
497
498            #[derive(Copy, Eq)]
499            #[serde(rename_all = "snake_case")]
500            enum ConflictPolicy {
501                Reject,
502                Queue,
503                Interrupt,
504            }
505
506            enum Value {
507                Bool(bool),
508                Integer(i64),
509                Number(f64),
510                String(String),
511                Pose(super::navigation::Pose),
512            }
513
514            struct Request {
515                request_id: RequestId,
516                behavior_id: String,
517                args: ::std::collections::BTreeMap<String, Value>,
518                priority: u8,
519                conflict_policy: ConflictPolicy,
520            }
521
522            enum Command {
523                Pause,
524                Resume,
525                Cancel,
526            }
527
528            #[derive(Copy, Eq)]
529            #[serde(rename_all = "snake_case")]
530            enum ExecutionStatus {
531                Idle,
532                Running,
533                Paused,
534                Succeeded,
535                Failed,
536                Cancelled,
537                Abandoned,
538            }
539
540            #[derive(Copy, Eq)]
541            #[serde(rename_all = "snake_case")]
542            enum NodeStatus {
543                Idle,
544                Running,
545                Succeeded,
546                Failed,
547                Skipped,
548                Waiting,
549                Cancelling,
550            }
551
552            #[derive(Copy, Eq)]
553            #[serde(rename_all = "snake_case")]
554            enum FailureReason {
555                MissingCapability,
556                ActionRefused,
557                ActionFailed,
558                ActionTimedOut,
559                ActionCancelled,
560                ConditionFailed,
561                SafetyStopped,
562                EmergencyStopped,
563                ResourceConflict,
564                InvalidArgument,
565                InvalidBlackboardValue,
566                SubtreeFailed,
567                ExecutionAbandoned,
568                InternalError,
569            }
570
571            struct Failure {
572                reason: FailureReason,
573                detail: Option<String>,
574                node_path: Option<String>,
575                action_id: Option<String>,
576            }
577
578            struct DefinitionRef {
579                id: String,
580                version: String,
581                content_hash: String,
582            }
583
584            struct State {
585                execution_id: Option<String>,
586                root_behavior_id: Option<String>,
587                active_request_id: Option<RequestId>,
588                active_behavior_id: Option<String>,
589                status: ExecutionStatus,
590                active_node_path: Option<String>,
591                failure: Option<Failure>,
592            }
593
594            struct Snapshot {
595                execution_id: Option<String>,
596                root: Option<DefinitionRef>,
597                definition_stack: Vec<DefinitionRef>,
598                active_request_id: Option<RequestId>,
599                active_behavior_id: Option<String>,
600                status: ExecutionStatus,
601                node_statuses: ::std::collections::BTreeMap<String, NodeStatus>,
602                active_node_path: Option<String>,
603                blackboard: ::std::collections::BTreeMap<String, Value>,
604                args: ::std::collections::BTreeMap<String, Value>,
605                started_at_ns: Option<u64>,
606                updated_at_ns: u64,
607                failure: Option<Failure>,
608            }
609
610            enum EventKind {
611                ExecutionStarted,
612                ExecutionPaused,
613                ExecutionResumed,
614                ExecutionCompleted,
615                ExecutionCancelled,
616                ExecutionAbandoned,
617                NodeTransition(NodeStatus),
618                RequestAccepted,
619                RequestCompleted(ExecutionStatus),
620                RequestRejected(FailureReason),
621            }
622
623            struct Event {
624                sequence: u64,
625                execution_id: Option<String>,
626                request_id: Option<RequestId>,
627                behavior_id: Option<String>,
628                content_hash: Option<String>,
629                node_path: Option<String>,
630                kind: EventKind,
631                failure: Option<Failure>,
632                participant_id: String,
633                logical_time_ns: u64,
634            }
635
636            topic command: command Command;
637            topic request: command Request;
638            topic state: state State;
639            topic snapshot: state Snapshot;
640            topic event: state Event;
641        }
642
643        logs(participant_id) {
644            /// Wall-clock timestamp carried by a structured bus log event.
645            struct Timestamp {
646                unix_seconds: i64,
647                nanos: u32,
648            }
649
650            /// The severity level of a structured bus log event.
651            #[derive(Copy, Eq)]
652            #[serde(rename_all = "snake_case")]
653            enum Level {
654                Error,
655                Warn,
656                Info,
657                Debug,
658                Trace,
659            }
660
661            /// A scalar tracing field value captured from a log event.
662            #[serde(untagged)]
663            enum LogValue {
664                Bool(bool),
665                I64(i64),
666                U64(u64),
667                F64(f64),
668                String(String),
669            }
670
671            /// One structured runner log event published out-of-band.
672            struct Event {
673                seq: u64,
674                time: Timestamp,
675                level: Level,
676                target: String,
677                message: String,
678                fields: ::std::collections::BTreeMap<String, LogValue>,
679                /// Complete records lost before publication because a bounded
680                /// queue or publish attempt was saturated.
681                dropped: u32,
682                /// Values or fields truncated inside this published record to
683                /// keep its wire representation bounded.
684                #[serde(default)]
685                truncated: u32,
686            }
687
688            topic self: state Event;
689        }
690
691        bus {
692            uplink {
693                /// Observable state of the router's optional upstream connection.
694                #[derive(Copy, Eq)]
695                #[serde(rename_all = "snake_case")]
696                enum UplinkPhase {
697                    Disabled,
698                    Connecting,
699                    Connected,
700                    /// Reserved for future retry telemetry. The router currently
701                    /// reports `Connecting` while Zenoh retries internally.
702                    Retrying,
703                }
704
705                /// Router-owned out-of-band state for the optional site uplink.
706                struct State {
707                    phase: UplinkPhase,
708                    connect: Option<String>,
709                    /// Reserved for future retry telemetry. This is currently
710                    /// always zero because Zenoh does not expose its attempt count.
711                    retry_attempt: u32,
712                    /// Optional human-readable diagnostic while not connected,
713                    /// such as DNS failure or waiting for the configured remote
714                    /// link. Invalid endpoints fail configuration before startup.
715                    detail: Option<String>,
716                }
717
718                topic state: state State;
719            }
720        }
721
722
723
724
725        perception {
726            /// A single detected object: class, confidence, and pose in a frame.
727            struct Detection {
728                class_id: String,
729                confidence: f32,
730                position_m: [f64; 3],
731                frame_id: String,
732                track_id: Option<u64>,
733            }
734
735            /// A batch of detections from one perception cycle.
736            struct Detections {
737                detections: Vec<Detection>,
738                stamp_ns: Option<u64>,
739            }
740
741            /// The perception participant's published health.
742            struct State {
743                healthy: bool,
744                detector: String,
745            }
746
747            topic detections: state Detections;
748            topic state: state State;
749        }
750
751        video {
752            /// Ask to open a video stream for a capability at an optional size.
753            struct OpenRequest {
754                capability: String,
755                width_px: Option<u32>,
756                height_px: Option<u32>,
757            }
758
759            /// The id of the stream that was opened.
760            struct OpenResponse {
761                stream_id: String,
762            }
763
764            topic open: query OpenRequest => OpenResponse;
765
766            stream(stream) {
767                /// Where one open video stream is in its lifecycle.
768                #[derive(Copy, Eq)]
769                #[serde(rename_all = "snake_case")]
770                enum StreamPhase {
771                    Starting,
772                    Active,
773                    Stopped,
774                }
775
776                /// The published state of one video stream: its lifecycle phase
777                /// and the number of source frames seen so far. The video participant
778                /// publishes it per stream; clients subscribe, hence `state`.
779                struct StreamState {
780                    phase: StreamPhase,
781                    frames_seen: u64,
782                }
783
784                topic state: state StreamState;
785            }
786        }
787
788        simulation {
789            /// The simulator clock: current time and whether it is advancing.
790            struct Clock {
791                now_ns: u64,
792                running: bool,
793            }
794
795            /// A command to the simulator's run loop.
796            #[derive(Copy, Eq)]
797            enum Control {
798                Pause,
799                Resume,
800                Reset,
801            }
802
803            /// The simulated robot's ground-truth planar pose.
804            struct RobotPose {
805                x_m: f64,
806                y_m: f64,
807                yaw_rad: f64,
808            }
809
810            /// Whether the simulated robot is in contact, with optional detail.
811            struct Contact {
812                in_contact: bool,
813                detail: Option<String>,
814            }
815
816            topic clock: state Clock;
817            topic control: command Control;
818            topic robot_pose: state RobotPose;
819            topic contact: state Contact;
820        }
821
822        // Per-instance component capabilities (D17/D38: framework participant / driver
823        // territory). `component(instance)` selects a manifest-declared component;
824        // each child `kind(capability)` is a self-contained node whose key is
825        // `component/{instance}/<kind>/{capability}/<leaf>`. Nodes duplicate any
826        // types they share by design - the node path disambiguates, so the names
827        // are path-local.
828        component(instance) {
829            motor(capability) {
830                /// A per-actuator command.
831                enum Command {
832                    Velocity(f32),
833                    Torque(f32),
834                    Stop,
835                }
836
837                topic command: command Command;
838            }
839
840            encoder(capability) {
841                /// Per-encoder sample on a dynamic per-instance key.
842                struct Sample {
843                    position_rad: f64,
844                    velocity_radps: f32,
845                }
846
847                topic sample: state Sample;
848            }
849
850            accelerometer(capability) {
851                /// Raw accelerometer sample in the sensor-local frame in m/s^2.
852                struct Sample {
853                    linear_acceleration: [f32; 3],
854                }
855
856                topic sample: state Sample;
857            }
858
859            gyroscope(capability) {
860                /// Raw angular velocity sample in the sensor-local frame in rad/s.
861                struct Sample {
862                    angular_velocity: [f32; 3],
863                }
864
865                topic sample: state Sample;
866            }
867
868            magnetometer(capability) {
869                /// Raw magnetic-field sample in the sensor-local frame.
870                struct Sample {
871                    magnetic_field: [f32; 3],
872                }
873
874                topic sample: state Sample;
875            }
876
877            imu(capability) {
878                #[derive(Copy, Eq)]
879                #[serde(rename_all = "snake_case")]
880                enum SensorHealth {
881                    Nominal,
882                    Degraded,
883                    Fault,
884                }
885
886                #[derive(Copy)]
887                struct Bias {
888                    angular_velocity_radps: [f32; 3],
889                    linear_acceleration_mps2: [f32; 3],
890                }
891
892                struct Sample {
893                    orientation: Option<[f32; 4]>,
894                    angular_velocity_radps: [f32; 3],
895                    linear_acceleration_mps2: [f32; 3],
896                    covariance: Option<[f32; 9]>,
897                    noise_density: Option<[f32; 3]>,
898                    sensor_frame_id: Option<String>,
899                    measured_at_ns: Option<u64>,
900                    health: SensorHealth,
901                    bias: Option<Bias>,
902                }
903
904                topic sample: state Sample;
905            }
906
907            range(capability) {
908                #[derive(Copy, Eq)]
909                #[serde(rename_all = "snake_case")]
910                enum SensorHealth {
911                    Nominal,
912                    Degraded,
913                    Fault,
914                }
915
916                #[derive(Copy)]
917                struct Limits {
918                    min_m: f32,
919                    max_m: f32,
920                }
921
922                #[derive(Copy)]
923                struct SampleQuality {
924                    valid: bool,
925                    confidence: Option<f32>,
926                }
927
928                struct Sample {
929                    distance_m: f32,
930                    limits: Option<Limits>,
931                    measured_at_ns: Option<u64>,
932                    quality: Option<SampleQuality>,
933                    health: SensorHealth,
934                }
935
936                topic sample: state Sample;
937            }
938
939            gnss(capability) {
940                /// A GNSS fix: geodetic position plus a 3x3 position covariance.
941                struct Sample {
942                    latitude: f64,
943                    longitude: f64,
944                    altitude: f64,
945                    position_covariance: [f64; 9],
946                }
947
948                topic sample: state Sample;
949            }
950
951            camera(capability) {
952                #[derive(Copy, Eq)]
953                #[serde(rename_all = "snake_case")]
954                enum Encoding {
955                    Jpeg,
956                    Png,
957                    L8,
958                    Rgb8,
959                    Rgba8,
960                }
961
962                #[derive(Copy)]
963                struct Intrinsics {
964                    fx: f32,
965                    fy: f32,
966                    cx: f32,
967                    cy: f32,
968                }
969
970                struct Distortion {
971                    model: String,
972                    coefficients: Vec<f32>,
973                }
974
975                #[derive(Copy)]
976                struct ExposureTiming {
977                    exposure_start_ns: Option<u64>,
978                    exposure_duration_ns: Option<u64>,
979                }
980
981                struct CalibrationIdentity {
982                    id: String,
983                    version: String,
984                }
985
986                /// One camera frame: encoded pixel bytes plus optional calibration
987                /// and timing metadata.
988                struct Frame {
989                    width: u32,
990                    height: u32,
991                    encoding: Encoding,
992                    intrinsics: Option<Intrinsics>,
993                    distortion: Option<Distortion>,
994                    exposure: Option<ExposureTiming>,
995                    measured_at_ns: Option<u64>,
996                    calibration: Option<CalibrationIdentity>,
997                    #[serde(with = "serde_bytes")]
998                    data: Vec<u8>,
999                }
1000
1001                topic frame: state Frame;
1002            }
1003
1004            depth(capability) {
1005                #[derive(Copy, Eq)]
1006                #[serde(rename_all = "snake_case")]
1007                enum Encoding {
1008                    U16Millimeters,
1009                }
1010
1011                #[derive(Copy, Eq)]
1012                #[serde(rename_all = "snake_case")]
1013                enum InvalidSamplePolicy {
1014                    ZeroIsInvalid,
1015                    NonFiniteIsInvalid,
1016                }
1017
1018                #[derive(Copy)]
1019                struct Intrinsics {
1020                    fx: f32,
1021                    fy: f32,
1022                    cx: f32,
1023                    cy: f32,
1024                }
1025
1026                struct Distortion {
1027                    model: String,
1028                    coefficients: Vec<f32>,
1029                }
1030
1031                #[derive(Copy)]
1032                struct ExposureTiming {
1033                    exposure_start_ns: Option<u64>,
1034                    exposure_duration_ns: Option<u64>,
1035                }
1036
1037                struct CalibrationIdentity {
1038                    id: String,
1039                    version: String,
1040                }
1041
1042                /// One depth frame: per-pixel millimetre samples plus optional
1043                /// calibration and timing metadata.
1044                struct Frame {
1045                    samples_mm: Vec<u16>,
1046                    encoding: Encoding,
1047                    invalid_sample_policy: InvalidSamplePolicy,
1048                    width: Option<u32>,
1049                    height: Option<u32>,
1050                    intrinsics: Option<Intrinsics>,
1051                    distortion: Option<Distortion>,
1052                    exposure: Option<ExposureTiming>,
1053                    measured_at_ns: Option<u64>,
1054                    calibration: Option<CalibrationIdentity>,
1055                }
1056
1057                topic frame: state Frame;
1058            }
1059
1060            lidar(capability) {
1061                #[derive(Copy, Eq)]
1062                #[serde(rename_all = "snake_case")]
1063                enum SensorHealth {
1064                    Nominal,
1065                    Degraded,
1066                    Fault,
1067                }
1068
1069                #[derive(Copy)]
1070                struct ScanGeometry {
1071                    angle_min_rad: f32,
1072                    angle_increment_rad: f32,
1073                }
1074
1075                #[derive(Copy)]
1076                struct RangeLimits {
1077                    min_m: f32,
1078                    max_m: f32,
1079                }
1080
1081                #[derive(Copy)]
1082                struct ScanQuality {
1083                    valid_points: u32,
1084                }
1085
1086                struct Ranges {
1087                    ranges: Vec<f32>,
1088                    geometry: Option<ScanGeometry>,
1089                    limits: Option<RangeLimits>,
1090                    measured_at_ns: Option<u64>,
1091                    quality: Option<ScanQuality>,
1092                    health: SensorHealth,
1093                }
1094
1095                struct Points {
1096                    points: Vec<[f32; 3]>,
1097                    limits: Option<RangeLimits>,
1098                    measured_at_ns: Option<u64>,
1099                    quality: Option<ScanQuality>,
1100                    health: SensorHealth,
1101                }
1102
1103                /// One lidar scan, either as polar ranges or as cartesian points.
1104                #[serde(tag = "kind", rename_all = "snake_case")]
1105                enum Scan {
1106                    Ranges(Ranges),
1107                    Points(Points),
1108                }
1109
1110                topic scan: state Scan;
1111            }
1112
1113            mmwave(capability) {
1114                /// One mmWave radar detection: position, velocity, and SNR.
1115                #[derive(Copy)]
1116                struct Detection {
1117                    position: [f32; 3],
1118                    velocity: [f32; 3],
1119                    snr: f32,
1120                }
1121
1122                /// One mmWave radar scan as a set of detections.
1123                struct Scan {
1124                    detections: Vec<Detection>,
1125                }
1126
1127                topic scan: state Scan;
1128            }
1129
1130            microphone(capability) {
1131                /// One audio frame as raw encoded bytes.
1132                struct Frame {
1133                    data: Vec<u8>,
1134                }
1135
1136                topic frame: state Frame;
1137            }
1138
1139            led(capability) {
1140                /// A per-LED on/off command.
1141                #[derive(Copy, Eq)]
1142                enum Command {
1143                    On,
1144                    Off,
1145                }
1146
1147                topic command: command Command;
1148            }
1149
1150            emergency_stop(capability) {
1151                /// Per-instance emergency-stop state.
1152                #[derive(Eq)]
1153                struct State {
1154                    engaged: bool,
1155                }
1156
1157                topic state: state State;
1158            }
1159        }
1160
1161        odometry {
1162            /// A planar pose + twist estimate in the odometry frame.
1163            struct State {
1164                x_m: f64,
1165                y_m: f64,
1166                yaw_rad: f64,
1167                linear_x_mps: f32,
1168                angular_z_radps: f32,
1169            }
1170
1171            topic state: state State;
1172        }
1173
1174        localize {
1175            /// A planar localization estimate in the map frame.
1176            struct LocalizationState {
1177                x_m: f64,
1178                y_m: f64,
1179                yaw_rad: f64,
1180                confidence: f32,
1181            }
1182
1183            topic state: state LocalizationState;
1184        }
1185
1186        presence {
1187            /// Per-participant liveness + readiness beacon.
1188            enum Readiness {
1189                NotStarted,
1190                Initializing,
1191                Ready,
1192                Degraded,
1193                Failed,
1194            }
1195
1196            /// A single participant's liveness beacon. Participants publish their
1197            /// own heartbeat; the presence participant subscribes them as its control
1198            /// input, hence the `command` role.
1199            struct Heartbeat {
1200                participant: String,
1201                readiness: Readiness,
1202            }
1203
1204            /// The presence participant's aggregate readiness across all participants.
1205            /// Presence publishes it; clients subscribe, hence the `state` role.
1206            struct State {
1207                readiness: Readiness,
1208            }
1209
1210            topic heartbeat: command Heartbeat;
1211            topic state: state State;
1212        }
1213
1214        map {
1215            /// A published map revision marker.
1216            struct Revision {
1217                revision: u64,
1218                resolution_m: f32,
1219            }
1220
1221            /// Request a rectangular submap window (map-frame metres).
1222            struct SubmapRequest {
1223                min_x_m: f64,
1224                min_y_m: f64,
1225                max_x_m: f64,
1226                max_y_m: f64,
1227            }
1228
1229            /// An occupancy-grid window: row-major cells, 0..=100 + 255 = unknown.
1230            struct SubmapResponse {
1231                width: u32,
1232                height: u32,
1233                resolution_m: f32,
1234                cells: Vec<u8>,
1235            }
1236
1237            topic revision: state Revision;
1238            topic submap: query SubmapRequest => SubmapResponse;
1239        }
1240
1241        asset {
1242            /// Fetch a stored asset by path.
1243            struct GetRequest {
1244                path: String,
1245            }
1246
1247            /// The asset bytes, a not-found marker, or a rejected path.
1248            enum GetResponse {
1249                Found { bytes: Vec<u8> },
1250                Missing,
1251                InvalidPath,
1252            }
1253
1254            topic get: query GetRequest => GetResponse;
1255        }
1256    }
1257
1258    // v2 is the one evolving preview surface. New and changed contracts are
1259    // edited here until the complete version is ready to freeze; preview work
1260    // does not mint another public API namespace for each implementation batch.
1261    preview version v2 {
1262        battery {
1263            /// Battery state remains preview while hardware ownership evolves.
1264            struct State {
1265                voltage_v: f32,
1266                current_a: f32,
1267                charge_ratio: f32,
1268            }
1269
1270            topic state: state State;
1271        }
1272
1273        simulation {
1274            /// One robot node that the simulator spawn authority should import.
1275            struct RobotSpawn {
1276                robot_id: String,
1277                node_string: String,
1278            }
1279
1280            /// Requests the current complete robot spawn set.
1281            ///
1282            /// `known_revision` lets a future responder distinguish initial
1283            /// bootstrap from refreshes after a runtime join. Responders may
1284            /// still return the current set when the revision is unchanged.
1285            struct SpawnRequest {
1286                known_revision: Option<u64>,
1287            }
1288
1289            /// The complete robot spawn set for one simulation world.
1290            struct SpawnSet {
1291                revision: u64,
1292                robots: Vec<RobotSpawn>,
1293            }
1294
1295            /// The authoritative advancing simulation clock. Publication means
1296            /// the world advanced; silence means it did not.
1297            struct Clock {
1298                now_ns: u64,
1299                step: u64,
1300            }
1301
1302            topic spawn: query SpawnRequest => SpawnSet;
1303            topic clock: state Clock;
1304        }
1305
1306        router {
1307            /// One topic-producer pair's measured ingress over the sample
1308            /// window. Row identity is `(topic, from_participant)`;
1309            /// `from_participant == ""` means the sample had no decodable
1310            /// Phoxal producer envelope. Quiet rows disappear after a short
1311            /// grace period and are then evicted, so
1312            /// `count` is cumulative only for the current observed lifetime
1313            /// and may restart from zero if that pair later returns. The
1314            /// sentinel `topic == "" && from_participant == ""` aggregates
1315            /// traffic omitted when the bounded detailed table is full or the
1316            /// router's non-blocking observation queue drops a burst or an
1317            /// observation has oversized identity metadata. Those
1318            /// drops never apply backpressure to robot traffic. Once emitted,
1319            /// the sentinel remains present for the session so consumers do
1320            /// not lose the fact that earlier traffic was unattributed; its
1321            /// window rate may be zero in later snapshots.
1322            struct TopicMetric {
1323                topic: String,
1324                from_participant: String,
1325                ingress_rate_hz: f32,
1326                count: u64,
1327            }
1328
1329            /// This robot bus root's measured message-flow snapshot; traffic
1330            /// transited for other robot roots is intentionally excluded.
1331            /// `window_ns` is the measurement interval LENGTH (not a timestamp;
1332            /// production time is the envelope `publish_at`, per the guide's
1333            /// logical-time discipline). Total throughput remains complete when
1334            /// the bounded per-topic table emits its documented aggregate
1335            /// sentinel row.
1336            struct Metrics {
1337                topics: Vec<TopicMetric>,
1338                throughput_msg_s: f32,
1339                window_ns: u64,
1340            }
1341
1342            topic metrics: state Metrics;
1343        }
1344
1345        telemetry {
1346            /// One real mounted filesystem in a host resource sample.
1347            /// A publisher that must truncate the inventory appends one
1348            /// aggregate sentinel with an empty `mount_point` and a
1349            /// `file_system` value of `+N omitted`.
1350            struct Disk {
1351                mount_point: String,
1352                file_system: String,
1353                used_bytes: u64,
1354                total_bytes: u64,
1355            }
1356
1357            /// Host OS resource sample (published by the new tool-telemetry).
1358            struct Host {
1359                cpu_pct: f32,
1360                ram_used_bytes: u64,
1361                ram_total_bytes: u64,
1362                swap_used_bytes: u64,
1363                swap_total_bytes: u64,
1364                load_1m: f32,
1365                load_5m: f32,
1366                load_15m: f32,
1367                uptime_s: Option<u64>,
1368                disks: Vec<Disk>,
1369                window_ns: u64,
1370            }
1371
1372            /// One participant's OWN process resource sample (published by the
1373            /// runner off the heartbeat loop). Subscriber demuxes by envelope
1374            /// source, like `presence::Heartbeat`.
1375            struct Process {
1376                cpu_pct: f32,
1377                rss_bytes: u64,
1378                window_ns: u64,
1379            }
1380
1381            topic host: state Host;
1382            topic process: state Process;
1383        }
1384
1385        joypad {
1386            /// Whether an observed controller is ready for the fixed manual
1387            /// input preset, disconnected, or connected without a compatible
1388            /// control mapping.
1389            enum DeviceStatus {
1390                Ready,
1391                Disconnected,
1392                Unsupported,
1393            }
1394
1395            /// One gamepad the tool can see. `id` is a STABLE wire id the tool
1396            /// assigns (name/guid-derived) - NOT a process-local gilrs id.
1397            struct Device {
1398                id: String,
1399                name: String,
1400                status: DeviceStatus,
1401            }
1402
1403            /// The joypad tool's published device state.
1404            struct Devices {
1405                available: Vec<Device>,
1406                selected: Option<String>,
1407                enabled: bool,
1408                /// Structural reason manual input cannot be enabled in this
1409                /// session (for example robot-model or backend limitations),
1410                /// independent of transient device/request errors.
1411                unavailable_reason: Option<String>,
1412                /// One-shot acknowledgement of a failed select/enable/rescan
1413                /// request. Event-driven consumers may show it once; periodic
1414                /// state heartbeats omit it. The tool also writes the failure
1415                /// to its log stream for durable diagnostics.
1416                last_error: Option<String>,
1417            }
1418
1419            /// Client asks the tool to select a device by its stable id.
1420            struct Select {
1421                id: String,
1422            }
1423
1424            /// Client asks the tool to enable or disable manual input.
1425            struct SetEnabled {
1426                enabled: bool,
1427            }
1428
1429            /// Client asks the tool to re-enumerate devices.
1430            struct Rescan {}
1431
1432            topic devices: state Devices;
1433            topic select: command Select;
1434            topic set_enabled: command SetEnabled;
1435            topic rescan: command Rescan;
1436        }
1437    }
1438}
1439
1440#[cfg(test)]
1441mod tests;