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. Normal participants import the
7//! train-selected facade with `use phoxal::api`; concrete modules such as
8//! `phoxal_api::v0_1` remain available to compatibility adapters.
9//!
10//! # Concrete API revisions
11//!
12//! An API revision is a conventional `vM_N` module generated by
13//! [`phoxal_api_tree!`]. Each version module carries:
14//!
15//! - a zero-variant marker `enum Api {}` implementing [`ApiVersion`], whose
16//!   [`ApiVersion::ID`] is the concrete wire identity (for example `"v0.1"`);
17//! - the version-local wire bodies, one `pub mod` per contract node holding plain
18//!   serde structs/enums and their [`ContractBody`] impls;
19//! - an api-local `topic` builder rooted at `topic::client()`.
20//!
21//! From 1.0, published concrete revisions are immutable. Before 1.0 the
22//! framework may make an approved in-place breaking edit without adding a shim
23//! or a new revision; every participant on a robot must move as one train
24//! because mixed pre-1.0 framework trains are unsupported. A child may extend
25//! one earlier revision; the generator materializes the complete child tree
26//! with its own identity. Exactly one `latest` alias is selected for each
27//! framework train.
28//!
29//! [`Api`]: v0_1::Api
30//!
31//! # Train-selected revision and per-contract identity
32//!
33//! A participant creates typed bus handles during
34//! `phoxal::Participant::setup`. Official participants
35//! name contract types through the complete train-selected facade. Embedded
36//! participant metadata carries `{id, config_schema}`.
37//! Across the graph, compatibility is **name identity** (D1) - two participants
38//! interoperate on a contract iff they use the exact same version-qualified name
39//! (`v0.1::drive::Target`), which is real on the wire because the revision
40//! is folded into the key ([`ContractBody::TOPIC`]). From 1.0 onward a stable
41//! contract type is immutable, so the name is the whole identity. Before 1.0,
42//! that identity is train-scoped and an in-place edit requires the whole robot
43//! graph to upgrade together.
44//!
45//! # Plain serde wire bodies, provenance in metadata
46//!
47//! A wire body is just its serde encoding - there is no `{"v":…}` envelope or any
48//! other version tag inside the payload (D62). Identity lives entirely in the
49//! Zenoh key (the version-qualified [`ContractBody::TOPIC`]); the bus metadata
50//! alongside the encoded body carries only provenance (source + logical time) and
51//! the codec that produced the bytes - never schema/family/version. Keeping
52//! identity out of both the payload and the metadata means the body bytes for an
53//! unchanged contract are identical across codecs, and a receiver's per-key
54//! subscription is the whole fast-reject.
55//!
56//! # Topic
57//!
58//! [`ContractBody::TOPIC`] is derived from the contract node's path in the tree,
59//! never written by hand: the version, then the `/`-joined node path plus the
60//! topic leaf, with each dynamic node contributing a `{var}` placeholder, e.g.
61//! `v0.1/component/{instance}/motor/{capability}/command`. A fully static path
62//! has a literal key (`v0.1/drive/state`). Folding the revision into the key
63//! (D1) is what makes two differently-versioned contracts physically distinct
64//! Zenoh keys, so they cannot collide.
65//!
66//! # The api-local topic builder
67//!
68//! Each version module exposes a `topic` builder that mirrors the node tree:
69//! `api::topic::client()` returns a root, one method per top-level node walks down the
70//! tree, a dynamic node's method takes its variable as `impl Display`, and a leaf
71//! method binds the topic's side-branded kind to its version-local body. For
72//! example `api::topic::client().drive().state()` yields a
73//! `Topic<Subscribe<drive::State>>` (the CLIENT observes the owner's `state`) over
74//! the version-qualified key `v0.1/drive/state`, and
75//! `api::topic::client().component("base").motor("left").command()` fills the dynamic
76//! segments to produce `v0.1/component/base/motor/left/command`. Because the
77//! builder is generated from the same tree as `TOPIC`, the built key and the
78//! documented key stay in lockstep.
79//!
80//! ## Owner side: `topic::owner`
81//!
82//! The PUBLIC `topic::client()...` chain above is the **client** side. The matching
83//! **owner** side lives at `api::topic::owner()...`:
84//! the same node tree and keys, but the leaf brands flip so the owner gets the side
85//! it must take - `api::topic::owner().drive().state()` is
86//! `Topic<Publish<drive::State>>` (the owner publishes its telemetry), and
87//! `api::topic::owner().drive().target()` is `Topic<Subscribe<drive::Target>>`
88//! (the owner reads its command input). A query owner reaches its `ServeQuery`
89//! brand the same way. The owner chain makes that ownership explicit; a
90//! participant acquires the topics of its OWN node through it and everything it
91//! consumes through the client chain.
92
93use phoxal_macros::phoxal_api_tree;
94
95/// The contract primitive traits, re-exported from the `phoxal-bus` crate (the
96/// ABI floor) so they stay addressable at `phoxal_api::ApiVersion` /
97/// `phoxal_api::ContractBody`.
98///
99/// - [`ApiVersion`] is the marker trait identifying one API version (D60),
100///   implemented only by the zero-variant `enum Api {}` that [`phoxal_api_tree!`]
101///   generates inside each revision module; its `ID` is the concrete dotted
102///   wire identity (for example `"v0.1"`).
103/// - [`ContractBody`] is a version-local wire body (D61): a plain serde type
104///   bound to exactly one [`ApiVersion`] and one contract topic. Every body
105///   declared inside a [`phoxal_api_tree!`] node gets a generated impl; handles,
106///   `SetupContext` builders, and the `Service`/`Driver` derive assertions key
107///   off its `Api`/`TOPIC`. `TOPIC` is version-qualified (D1) and is the
108///   compatibility key; its serde encoding is the wire payload, with no version
109///   envelope (D62).
110pub use phoxal_bus::{ApiVersion, ContractBody};
111
112phoxal_api_tree! {
113    version v0_1 {
114        drive {
115            /// Why actuation authority is in its current state.
116            enum StopReason {
117                /// Nothing is live: no target has been accepted, the producer
118                /// has gone silent past the host deadline, or the held command
119                /// exceeded its logical hold horizon. All three are the same
120                /// fact to a consumer - the drive is not being commanded.
121                TargetStale,
122                TargetNotFinite,
123                ActuatorCommandNotFinite,
124                Inactive,
125                EmergencyStop,
126                Fault,
127            }
128
129            /// Whether the drive is actively commanding the actuators.
130            enum ActuatorAuthority {
131                Active,
132                Stopped,
133            }
134
135            /// A requested or limited planar velocity.
136            struct Target {
137                linear_x_mps: f32,
138                angular_z_radps: f32,
139                curvature_limit_radpm: Option<f32>,
140            }
141
142            /// The drive participant's published control state.
143            struct State {
144                target: Target,
145                limited_target: Target,
146                actuator_authority: ActuatorAuthority,
147                stop_reason: Option<StopReason>,
148            }
149
150            topic target: command Target;
151            topic state: state State;
152        }
153
154        joint(joint) {
155            /// Per-joint position/velocity (and optional effort) on a dynamic
156            /// per-joint key.
157            struct JointState {
158                position_rad: f64,
159                velocity_radps: f64,
160                effort_nm: Option<f64>,
161            }
162
163            topic state: state JointState;
164        }
165
166        frame {
167            /// A parent → child rigid transform (translation + xyzw quaternion).
168            struct FrameTransform {
169                parent_frame_id: String,
170                child_frame_id: String,
171                translation_m: [f64; 3],
172                rotation_quat_xyzw: [f64; 4],
173                /// When this transform was observed. Absent for a static
174                /// transform, which is configuration rather than observation.
175                stamp: Option<::phoxal_bus::RobotInstant>,
176            }
177
178            /// Transforms that do not change over time.
179            struct StaticTransforms {
180                transforms: Vec<FrameTransform>,
181            }
182
183            /// The current transform tree.
184            struct Tree {
185                transforms: Vec<FrameTransform>,
186            }
187
188            /// Ask for the transform between two frames, optionally at a time.
189            struct LookupRequest {
190                target_frame_id: String,
191                source_frame_id: String,
192                /// The instant to resolve at. Absent asks for the latest.
193                at: Option<::phoxal_bus::RobotInstant>,
194            }
195
196            /// The resolved transform, or `None` if it is not available.
197            struct LookupResponse {
198                transform: Option<FrameTransform>,
199            }
200
201            topic tree: state Tree;
202            topic static_transforms: state StaticTransforms;
203            topic lookup: query LookupRequest => LookupResponse;
204        }
205
206        power {
207            /// A platform power command.
208            #[derive(Copy, Eq)]
209            enum Command {
210                Reboot,
211                Shutdown,
212            }
213
214            /// Where the power participant is in handling a command.
215            #[derive(Copy, Eq)]
216            enum Status {
217                Idle,
218                Rebooting,
219                ShuttingDown,
220                Failed,
221            }
222
223            /// Why a power command was rejected outright.
224            #[derive(Copy, Eq)]
225            #[serde(rename_all = "snake_case")]
226            enum RejectedReason {
227                HostIntegrationUnavailable,
228                CommandRejected,
229            }
230
231            /// Why an accepted power command later failed.
232            #[derive(Copy, Eq)]
233            #[serde(rename_all = "snake_case")]
234            enum FailedReason {
235                HostCommandFailed,
236            }
237
238            /// The power participant's published state.
239            struct State {
240                status: Status,
241                detail: Option<String>,
242            }
243
244            topic command: command Command;
245            topic state: state State;
246        }
247
248        motion {
249            struct Target {
250                linear_x_mps: f32,
251                angular_z_radps: f32,
252                curvature_limit_radpm: Option<f32>,
253            }
254
255            #[derive(Copy, Eq)]
256            #[serde(rename_all = "snake_case")]
257            enum Source {
258                Manual,
259                Navigation,
260                EmergencyStop,
261            }
262
263            #[derive(Copy, Eq)]
264            #[serde(rename_all = "snake_case")]
265            enum ZeroReason {
266                NoCandidate,
267                NavigationCandidateStale,
268                ManualCandidateNotFinite,
269                NavigationCandidateNotFinite,
270                EmergencyStopEngaged,
271                SafetyConstraintsUnavailable,
272                SafetyProtectiveStop,
273            }
274
275            #[derive(Copy, Eq)]
276            #[serde(rename_all = "snake_case")]
277            enum SafetyRuntime {
278                Absent,
279                Present,
280            }
281
282            struct ManualCommand {
283                linear_x_mps: f64,
284                angular_z_radps: f64,
285            }
286
287            struct State {
288                /// How long ago motion observed the live manual command, on
289                /// its own host clock. `None` when no manual command is live.
290                manual_observed_age_ns: Option<u64>,
291                autonomous_candidate_age_ns: Option<u64>,
292                safety_constraints_age_ns: Option<u64>,
293                selected_source: Option<Source>,
294                final_target: Target,
295                zero_reason: Option<ZeroReason>,
296                safety_runtime: SafetyRuntime,
297                component_estop_blocked: bool,
298                active_safety_constraints: Vec<super::safety::Constraint>,
299            }
300
301            topic manual: command ManualCommand;
302            topic state: state State;
303        }
304
305        safety {
306            /// Why safety is stopping or limiting body motion.
307            #[derive(Copy, Eq)]
308            #[serde(rename_all = "snake_case")]
309            enum ConstraintReason {
310                WorldUnavailable,
311                MapUnavailable,
312                DrivableSpaceUnavailable,
313                LocalizationUnavailable,
314                LocalizationUncertain,
315                ObstacleProximity,
316                RangeSensorFault,
317                DriveFault,
318                BatteryLow,
319                BatteryCritical,
320                SpeedZone,
321                OperatorPolicy,
322            }
323
324            /// Typed origin of one constraint, suitable for operator diagnosis.
325            #[derive(Copy, Eq)]
326            #[serde(rename_all = "snake_case")]
327            enum ConstraintSourceKind {
328                WorldModel,
329                Map,
330                Localization,
331                Range,
332                Drive,
333                Battery,
334                Operator,
335            }
336
337            struct ConstraintSource {
338                kind: ConstraintSourceKind,
339                participant_id: String,
340                component_id: Option<String>,
341                capability_id: Option<String>,
342            }
343
344            struct Constraint {
345                reason: ConstraintReason,
346                source: ConstraintSource,
347                stop: bool,
348                max_linear_speed_mps: Option<f32>,
349                max_angular_speed_radps: Option<f32>,
350                observed_value: Option<f32>,
351                /// The instant this constraint starts applying, on the
352                /// publisher's timeline. A consumer on another timeline gets a
353                /// checked error, never a silently wrong comparison.
354                valid_from: ::phoxal_bus::RobotInstant,
355                /// The instant this constraint stops applying.
356                expires_at: ::phoxal_bus::RobotInstant,
357            }
358
359            /// The sole safety-to-motion control product. Motion accepts it only
360            /// on the same timeline and before `expires_at`.
361            struct MotionConstraints {
362                sequence: u64,
363                stop: bool,
364                max_linear_speed_mps: Option<f32>,
365                max_angular_speed_radps: Option<f32>,
366                constraints: Vec<Constraint>,
367                expires_at: ::phoxal_bus::RobotInstant,
368            }
369
370            /// Operator-facing state mirrors the exact product consumed by motion.
371            struct State {
372                clear: bool,
373                motion: MotionConstraints,
374            }
375
376            topic constraints: state MotionConstraints;
377            topic state: state State;
378        }
379
380        navigation {
381            #[derive(Eq)]
382            struct RequestId {
383                value: String,
384            }
385
386            struct Pose {
387                x_m: f64,
388                y_m: f64,
389                yaw_rad: Option<f64>,
390            }
391
392            struct Path {
393                poses: Vec<Pose>,
394                map_revision: Option<u64>,
395            }
396
397            enum RequestKind {
398                GotoPose(Pose),
399                FollowPath(Path),
400                Cancel(RequestId),
401            }
402
403            struct Request {
404                request_id: RequestId,
405                kind: RequestKind,
406            }
407
408            enum State {
409                Idle,
410                Accepted(RequestId),
411                Running(RequestId),
412            }
413
414            #[derive(Copy, Eq)]
415            #[serde(rename_all = "snake_case")]
416            enum FailureReason {
417                LocalizationUnavailable,
418                MapUnavailable,
419                MapChanged,
420                NoPath,
421                Blocked,
422                Internal,
423            }
424
425            #[derive(Copy, Eq)]
426            #[serde(rename_all = "snake_case")]
427            enum RefusalReason {
428                Busy,
429                InvalidRequest,
430                Unsupported,
431            }
432
433            enum Outcome {
434                Succeeded,
435                Failed(FailureReason),
436                Refused(RefusalReason),
437                Cancelled,
438                TimedOut,
439            }
440
441            struct Progress {
442                request_id: RequestId,
443                distance_remaining_m: f64,
444                path_index: u32,
445            }
446
447            struct Result {
448                request_id: RequestId,
449                outcome: Outcome,
450            }
451
452            struct Candidate {
453                request_id: RequestId,
454                linear_x_mps: f32,
455                angular_z_radps: f32,
456            }
457
458            struct FrontierRequest {
459                map_revision: Option<u64>,
460            }
461
462            struct Frontier {
463                x_m: f64,
464                y_m: f64,
465                score: f32,
466                size: u32,
467            }
468
469            struct FrontierResponse {
470                frontier: Option<Frontier>,
471                map_revision: Option<u64>,
472            }
473
474            topic request: command Request;
475            topic state: state State;
476            topic progress: state Progress;
477            topic result: state Result;
478            topic candidate: state Candidate;
479            topic next_frontier: query FrontierRequest => FrontierResponse;
480        }
481
482        behavior {
483            #[derive(Eq)]
484            struct RequestId {
485                value: String,
486            }
487
488            #[derive(Copy, Eq)]
489            #[serde(rename_all = "snake_case")]
490            enum ConflictPolicy {
491                Reject,
492                Queue,
493                Interrupt,
494            }
495
496            enum Value {
497                Bool(bool),
498                Integer(i64),
499                Number(f64),
500                String(String),
501                Pose(super::navigation::Pose),
502            }
503
504            struct Request {
505                request_id: RequestId,
506                behavior_id: String,
507                args: ::std::collections::BTreeMap<String, Value>,
508                priority: u8,
509                conflict_policy: ConflictPolicy,
510            }
511
512            enum Command {
513                Pause,
514                Resume,
515                Cancel,
516            }
517
518            #[derive(Copy, Eq)]
519            #[serde(rename_all = "snake_case")]
520            enum ExecutionStatus {
521                Idle,
522                Running,
523                Paused,
524                Succeeded,
525                Failed,
526                Cancelled,
527                Abandoned,
528            }
529
530            #[derive(Copy, Eq)]
531            #[serde(rename_all = "snake_case")]
532            enum NodeStatus {
533                Idle,
534                Running,
535                Succeeded,
536                Failed,
537                Skipped,
538                Waiting,
539                Cancelling,
540            }
541
542            #[derive(Copy, Eq)]
543            #[serde(rename_all = "snake_case")]
544            enum FailureReason {
545                MissingCapability,
546                ActionRefused,
547                ActionFailed,
548                ActionTimedOut,
549                ActionCancelled,
550                ConditionFailed,
551                SafetyStopped,
552                EmergencyStopped,
553                ResourceConflict,
554                InvalidArgument,
555                InvalidBlackboardValue,
556                SubtreeFailed,
557                ExecutionAbandoned,
558                InternalError,
559            }
560
561            struct Failure {
562                reason: FailureReason,
563                detail: Option<String>,
564                node_path: Option<String>,
565                action_id: Option<String>,
566            }
567
568            struct DefinitionRef {
569                id: String,
570                version: String,
571                content_hash: String,
572            }
573
574            struct State {
575                execution_id: Option<String>,
576                root_behavior_id: Option<String>,
577                active_request_id: Option<RequestId>,
578                active_behavior_id: Option<String>,
579                status: ExecutionStatus,
580                active_node_path: Option<String>,
581                failure: Option<Failure>,
582            }
583
584            struct Snapshot {
585                execution_id: Option<String>,
586                root: Option<DefinitionRef>,
587                definition_stack: Vec<DefinitionRef>,
588                active_request_id: Option<RequestId>,
589                active_behavior_id: Option<String>,
590                status: ExecutionStatus,
591                node_statuses: ::std::collections::BTreeMap<String, NodeStatus>,
592                active_node_path: Option<String>,
593                blackboard: ::std::collections::BTreeMap<String, Value>,
594                args: ::std::collections::BTreeMap<String, Value>,
595                /// When the active execution started, on the publisher's
596                /// timeline. The envelope carries when this snapshot was
597                /// produced; that instant is never duplicated here.
598                started_at: Option<::phoxal_bus::RobotInstant>,
599                failure: Option<Failure>,
600            }
601
602            enum EventKind {
603                ExecutionStarted,
604                ExecutionPaused,
605                ExecutionResumed,
606                ExecutionCompleted,
607                ExecutionCancelled,
608                ExecutionAbandoned,
609                NodeTransition(NodeStatus),
610                RequestAccepted,
611                RequestCompleted(ExecutionStatus),
612                RequestRejected(FailureReason),
613            }
614
615            struct Event {
616                sequence: u64,
617                execution_id: Option<String>,
618                request_id: Option<RequestId>,
619                behavior_id: Option<String>,
620                content_hash: Option<String>,
621                node_path: Option<String>,
622                kind: EventKind,
623                failure: Option<Failure>,
624                participant_id: String,
625            }
626
627            topic command: command Command;
628            topic request: command Request;
629            topic state: state State;
630            topic snapshot: state Snapshot;
631            topic event: state Event;
632        }
633
634        logs(participant_id) {
635            /// Wall-clock timestamp carried by a structured bus log event.
636            struct Timestamp {
637                unix_seconds: i64,
638                nanos: u32,
639            }
640
641            /// The severity level of a structured bus log event.
642            #[derive(Copy, Eq)]
643            #[serde(rename_all = "snake_case")]
644            enum Level {
645                Error,
646                Warn,
647                Info,
648                Debug,
649                Trace,
650            }
651
652            /// A scalar tracing field value captured from a log event.
653            #[serde(untagged)]
654            enum LogValue {
655                Bool(bool),
656                I64(i64),
657                U64(u64),
658                F64(f64),
659                String(String),
660            }
661
662            /// One structured runner log event published out-of-band.
663            struct Event {
664                seq: u64,
665                time: Timestamp,
666                level: Level,
667                target: String,
668                message: String,
669                fields: ::std::collections::BTreeMap<String, LogValue>,
670                /// Complete records lost before publication because a bounded
671                /// queue or publish attempt was saturated.
672                dropped: u32,
673                /// Values or fields truncated inside this published record to
674                /// keep its wire representation bounded.
675                #[serde(default)]
676                truncated: u32,
677            }
678
679            topic self: diagnostic Event;
680        }
681
682
683
684
685
686
687        perception {
688            /// A single detected object: class, confidence, and pose in a frame.
689            struct Detection {
690                class_id: String,
691                confidence: f32,
692                position_m: [f64; 3],
693                frame_id: String,
694                track_id: Option<u64>,
695            }
696
697            /// A batch of detections from one perception cycle.
698            struct Detections {
699                detections: Vec<Detection>,
700                /// The frame instant these detections were derived from.
701                stamp: Option<::phoxal_bus::RobotInstant>,
702            }
703
704            /// The perception participant's published health.
705            struct State {
706                healthy: bool,
707                detector: String,
708            }
709
710            topic detections: state Detections;
711            topic state: state State;
712        }
713
714        video {
715            /// Ask to open a video stream for a capability at an optional size.
716            struct OpenRequest {
717                capability: String,
718                width_px: Option<u32>,
719                height_px: Option<u32>,
720            }
721
722            /// The id of the stream that was opened.
723            struct OpenResponse {
724                stream_id: String,
725            }
726
727            topic open: query OpenRequest => OpenResponse;
728
729            stream(stream) {
730                /// Where one open video stream is in its lifecycle.
731                #[derive(Copy, Eq)]
732                #[serde(rename_all = "snake_case")]
733                enum StreamPhase {
734                    Starting,
735                    Active,
736                    Stopped,
737                }
738
739                /// The published state of one video stream: its lifecycle phase
740                /// and the number of source frames seen so far. The video participant
741                /// publishes it per stream; clients subscribe, hence `state`.
742                struct StreamState {
743                    phase: StreamPhase,
744                    frames_seen: u64,
745                }
746
747                topic state: state StreamState;
748            }
749        }
750
751        simulation {
752            /// The authoritative advancing simulation clock. Publication means
753            /// the world advanced; silence means it did not.
754            ///
755            /// The timeline and instant ride in the envelope, like every other
756            /// `state`-shaped publication - the world authority stamps them with
757            /// a world step token. The body carries only the step counter, which
758            /// is not derivable from the envelope.
759            struct Clock {
760                step: u64,
761            }
762
763            // `world_clock`, not `state`: only the world-authority participant
764            // (`#[phoxal::simulator]`) may publish it, enforced at compile time
765            // by the disjoint `WorldClockContract` this role generates instead
766            // of `StateContract`; see
767            // `phoxal_bus::contract::WorldClockContract`'s docs.
768            topic clock: world_clock Clock;
769        }
770
771        // Per-instance component capabilities (D17/D38: framework participant / driver
772        // territory). `component(instance)` selects a manifest-declared component;
773        // each child `kind(capability)` is a self-contained node whose key is
774        // `component/{instance}/<kind>/{capability}/<leaf>`. Nodes duplicate any
775        // types they share by design - the node path disambiguates, so the names
776        // are path-local.
777        component(instance) {
778            motor(capability) {
779                /// A per-actuator command.
780                enum Command {
781                    Velocity(f32),
782                    Torque(f32),
783                    Stop,
784                }
785
786                topic command: command Command;
787            }
788
789            encoder(capability) {
790                /// Per-encoder sample on a dynamic per-instance key.
791                struct Sample {
792                    position_rad: f64,
793                    velocity_radps: f32,
794                }
795
796                topic sample: measurement Sample;
797            }
798
799            accelerometer(capability) {
800                /// Raw accelerometer sample in the sensor-local frame in m/s^2.
801                struct Sample {
802                    linear_acceleration: [f32; 3],
803                }
804
805                topic sample: measurement Sample;
806            }
807
808            gyroscope(capability) {
809                /// Raw angular velocity sample in the sensor-local frame in rad/s.
810                struct Sample {
811                    angular_velocity: [f32; 3],
812                }
813
814                topic sample: measurement Sample;
815            }
816
817            magnetometer(capability) {
818                /// Raw magnetic-field sample in the sensor-local frame.
819                struct Sample {
820                    magnetic_field: [f32; 3],
821                }
822
823                topic sample: measurement Sample;
824            }
825
826            imu(capability) {
827                #[derive(Copy, Eq)]
828                #[serde(rename_all = "snake_case")]
829                enum SensorHealth {
830                    Nominal,
831                    Degraded,
832                    Fault,
833                }
834
835                #[derive(Copy)]
836                struct Bias {
837                    angular_velocity_radps: [f32; 3],
838                    linear_acceleration_mps2: [f32; 3],
839                }
840
841                struct Sample {
842                    orientation: Option<[f32; 4]>,
843                    angular_velocity_radps: [f32; 3],
844                    linear_acceleration_mps2: [f32; 3],
845                    covariance: Option<[f32; 9]>,
846                    noise_density: Option<[f32; 3]>,
847                    sensor_frame_id: Option<String>,
848                    health: SensorHealth,
849                    bias: Option<Bias>,
850                }
851
852                topic sample: measurement Sample;
853            }
854
855            range(capability) {
856                #[derive(Copy, Eq)]
857                #[serde(rename_all = "snake_case")]
858                enum SensorHealth {
859                    Nominal,
860                    Degraded,
861                    Fault,
862                }
863
864                #[derive(Copy)]
865                struct Limits {
866                    min_m: f32,
867                    max_m: f32,
868                }
869
870                #[derive(Copy)]
871                struct SampleQuality {
872                    valid: bool,
873                    confidence: Option<f32>,
874                }
875
876                struct Sample {
877                    distance_m: f32,
878                    limits: Option<Limits>,
879                    quality: Option<SampleQuality>,
880                    health: SensorHealth,
881                }
882
883                topic sample: measurement Sample;
884            }
885
886            gnss(capability) {
887                /// A GNSS fix: geodetic position plus a 3x3 position covariance.
888                struct Sample {
889                    latitude: f64,
890                    longitude: f64,
891                    altitude: f64,
892                    position_covariance: [f64; 9],
893                }
894
895                topic sample: measurement Sample;
896            }
897
898            camera(capability) {
899                #[derive(Copy, Eq)]
900                #[serde(rename_all = "snake_case")]
901                enum Encoding {
902                    Jpeg,
903                    Png,
904                    L8,
905                    Rgb8,
906                    Rgba8,
907                }
908
909                #[derive(Copy)]
910                struct Intrinsics {
911                    fx: f32,
912                    fy: f32,
913                    cx: f32,
914                    cy: f32,
915                }
916
917                struct Distortion {
918                    model: String,
919                    coefficients: Vec<f32>,
920                }
921
922                #[derive(Copy)]
923                struct ExposureTiming {
924                    exposure_start_ns: Option<u64>,
925                    exposure_duration_ns: Option<u64>,
926                }
927
928                struct CalibrationIdentity {
929                    id: String,
930                    version: String,
931                }
932
933                /// One camera frame: encoded pixel bytes plus optional calibration
934                /// and timing metadata.
935                struct Frame {
936                    width: u32,
937                    height: u32,
938                    encoding: Encoding,
939                    intrinsics: Option<Intrinsics>,
940                    distortion: Option<Distortion>,
941                    exposure: Option<ExposureTiming>,
942                    calibration: Option<CalibrationIdentity>,
943                    #[serde(with = "serde_bytes")]
944                    data: Vec<u8>,
945                }
946
947                topic frame: measurement Frame;
948            }
949
950            depth(capability) {
951                #[derive(Copy, Eq)]
952                #[serde(rename_all = "snake_case")]
953                enum Encoding {
954                    U16Millimeters,
955                }
956
957                #[derive(Copy, Eq)]
958                #[serde(rename_all = "snake_case")]
959                enum InvalidSamplePolicy {
960                    ZeroIsInvalid,
961                    NonFiniteIsInvalid,
962                }
963
964                #[derive(Copy)]
965                struct Intrinsics {
966                    fx: f32,
967                    fy: f32,
968                    cx: f32,
969                    cy: f32,
970                }
971
972                struct Distortion {
973                    model: String,
974                    coefficients: Vec<f32>,
975                }
976
977                #[derive(Copy)]
978                struct ExposureTiming {
979                    exposure_start_ns: Option<u64>,
980                    exposure_duration_ns: Option<u64>,
981                }
982
983                struct CalibrationIdentity {
984                    id: String,
985                    version: String,
986                }
987
988                /// One depth frame: per-pixel millimetre samples plus optional
989                /// calibration and timing metadata.
990                struct Frame {
991                    samples_mm: Vec<u16>,
992                    encoding: Encoding,
993                    invalid_sample_policy: InvalidSamplePolicy,
994                    width: Option<u32>,
995                    height: Option<u32>,
996                    intrinsics: Option<Intrinsics>,
997                    distortion: Option<Distortion>,
998                    exposure: Option<ExposureTiming>,
999                    calibration: Option<CalibrationIdentity>,
1000                }
1001
1002                topic frame: measurement Frame;
1003            }
1004
1005            lidar(capability) {
1006                #[derive(Copy, Eq)]
1007                #[serde(rename_all = "snake_case")]
1008                enum SensorHealth {
1009                    Nominal,
1010                    Degraded,
1011                    Fault,
1012                }
1013
1014                #[derive(Copy)]
1015                struct ScanGeometry {
1016                    angle_min_rad: f32,
1017                    angle_increment_rad: f32,
1018                }
1019
1020                #[derive(Copy)]
1021                struct RangeLimits {
1022                    min_m: f32,
1023                    max_m: f32,
1024                }
1025
1026                #[derive(Copy)]
1027                struct ScanQuality {
1028                    valid_points: u32,
1029                }
1030
1031                struct Ranges {
1032                    ranges: Vec<f32>,
1033                    geometry: Option<ScanGeometry>,
1034                    limits: Option<RangeLimits>,
1035                    quality: Option<ScanQuality>,
1036                    health: SensorHealth,
1037                }
1038
1039                struct Points {
1040                    points: Vec<[f32; 3]>,
1041                    limits: Option<RangeLimits>,
1042                    quality: Option<ScanQuality>,
1043                    health: SensorHealth,
1044                }
1045
1046                /// One lidar scan, either as polar ranges or as cartesian points.
1047                #[serde(tag = "kind", rename_all = "snake_case")]
1048                enum Scan {
1049                    Ranges(Ranges),
1050                    Points(Points),
1051                }
1052
1053                topic scan: measurement Scan;
1054            }
1055
1056            mmwave(capability) {
1057                /// One mmWave radar detection: position, velocity, and SNR.
1058                #[derive(Copy)]
1059                struct Detection {
1060                    position: [f32; 3],
1061                    velocity: [f32; 3],
1062                    snr: f32,
1063                }
1064
1065                /// One mmWave radar scan as a set of detections.
1066                struct Scan {
1067                    detections: Vec<Detection>,
1068                }
1069
1070                topic scan: measurement Scan;
1071            }
1072
1073            microphone(capability) {
1074                /// One audio frame as raw encoded bytes.
1075                struct Frame {
1076                    data: Vec<u8>,
1077                }
1078
1079                topic frame: measurement Frame;
1080            }
1081
1082            led(capability) {
1083                /// A per-LED on/off command.
1084                #[derive(Copy, Eq)]
1085                enum Command {
1086                    On,
1087                    Off,
1088                }
1089
1090                topic command: command Command;
1091            }
1092
1093            speaker(capability) {
1094                /// One chunk of an audio stream to play on this speaker.
1095                ///
1096                /// `Some(bytes)` carries WAV-coded audio: the first chunk of a
1097                /// stream starts with the standard WAV header, later chunks
1098                /// continue its data. `None` ends the stream and is what tells
1099                /// the owner the sound is complete.
1100                struct Chunk {
1101                    stream: Option<Vec<u8>>,
1102                }
1103
1104                topic stream: command Chunk;
1105            }
1106
1107            battery(capability) {
1108                /// Battery state reported by the pack's owner - the simulator
1109                /// backing this capability, or the real driver.
1110                struct State {
1111                    voltage_v: f32,
1112                    current_a: f32,
1113                    charge_ratio: f32,
1114                }
1115
1116                topic state: state State;
1117            }
1118
1119            emergency_stop(capability) {
1120                /// Per-instance emergency-stop state.
1121                #[derive(Eq)]
1122                struct State {
1123                    engaged: bool,
1124                }
1125
1126                topic state: state State;
1127            }
1128        }
1129
1130        odometry {
1131            /// A planar pose + twist estimate in the odometry frame.
1132            struct State {
1133                x_m: f64,
1134                y_m: f64,
1135                yaw_rad: f64,
1136                linear_x_mps: f32,
1137                angular_z_radps: f32,
1138            }
1139
1140            topic state: state State;
1141        }
1142
1143        localize {
1144            /// A planar localization estimate in the map frame.
1145            struct LocalizationState {
1146                x_m: f64,
1147                y_m: f64,
1148                yaw_rad: f64,
1149                confidence: f32,
1150            }
1151
1152            topic state: state LocalizationState;
1153        }
1154
1155        map {
1156            /// A published map revision marker.
1157            struct Revision {
1158                revision: u64,
1159                resolution_m: f32,
1160            }
1161
1162            /// Request a rectangular submap window (map-frame metres).
1163            struct SubmapRequest {
1164                min_x_m: f64,
1165                min_y_m: f64,
1166                max_x_m: f64,
1167                max_y_m: f64,
1168            }
1169
1170            /// An occupancy-grid window: row-major cells, 0..=100 + 255 = unknown.
1171            struct SubmapResponse {
1172                width: u32,
1173                height: u32,
1174                resolution_m: f32,
1175                cells: Vec<u8>,
1176            }
1177
1178            topic revision: state Revision;
1179            topic submap: query SubmapRequest => SubmapResponse;
1180        }
1181
1182        // Contracts the supervisor itself answers. The node is part of the
1183        // wire key, so a reader can tell from the key alone that the supervisor
1184        // is the authority - and a stale participant sitting on an old key
1185        // physically cannot answer one of these (organization#978).
1186        supervisor {
1187            /// Opaque identity for one supervisor collector together with a
1188            /// position in its completed follow stream. A snapshot cursor
1189            /// covers the retained completed items; a bus snapshot's optional
1190            /// `current` window deliberately has the next sequence. Consumers
1191            /// compare `generation` for equality only and must never parse or
1192            /// order it.
1193            #[derive(Eq)]
1194            struct Cursor {
1195                generation: String,
1196                sequence: u64,
1197            }
1198
1199            /// Which side of one participant-local bus buffer a runtime row
1200            /// measures. The version-qualified `topic` field remains the wire
1201            /// identity; direction is never inferred from its spelling.
1202            #[derive(Copy, Eq, Ord, PartialOrd)]
1203            #[serde(rename_all = "snake_case")]
1204            enum RuntimeDirection {
1205                Publish,
1206                Subscribe,
1207                /// Used only by the bounded overflow row, which may combine
1208                /// omitted rows from both directions.
1209                Mixed,
1210            }
1211
1212            /// The concrete bounded buffer whose pressure a runtime row
1213            /// measures.
1214            #[derive(Copy, Eq, Ord, PartialOrd)]
1215            #[serde(rename_all = "snake_case")]
1216            enum RuntimeBufferKind {
1217                /// Per-topic view of the one shared process outbound queue.
1218                /// Its sample capacity is repeated on each row and must not be
1219                /// summed; the queue's separate byte pressure is not in v0.1.
1220                Outbound,
1221                /// Keep-last slot. Depth `1` means occupied, never backlog.
1222                Latest,
1223                Subscriber,
1224                /// Used only by the bounded overflow row.
1225                Mixed,
1226            }
1227
1228            /// Host-monotonic scheduled-step work completed during one rollup
1229            /// window. An unscheduled participant reports `None` instead.
1230            struct RuntimeStep {
1231                target_period_ns: u64,
1232                completed: u64,
1233                errors: u64,
1234                mean_duration_ns: u64,
1235                max_duration_ns: u64,
1236                mean_lateness_ns: u64,
1237                max_lateness_ns: u64,
1238                missed_ticks: u64,
1239                overruns: u64,
1240            }
1241
1242            /// One exact version-qualified topic/direction/buffer row. These
1243            /// are process-lifetime setup declarations: dropping an authoring
1244            /// handle does not dynamically unregister a row. Empty `topic`
1245            /// plus `Mixed` direction/kind identifies the explicit overflow
1246            /// row; `overflowed_rows` is zero on normal rows.
1247            struct RuntimeTopic {
1248                topic: String,
1249                direction: RuntimeDirection,
1250                buffer_kind: RuntimeBufferKind,
1251                count: u64,
1252                /// Finite, non-negative message rate. Retention tools clamp
1253                /// malformed non-finite inputs before they reach snapshots.
1254                rate_hz: f32,
1255                drops: u64,
1256                latest_overwrites: u64,
1257                bounded_evictions: u64,
1258                /// Sample capacity. Outbound rows repeat the shared process
1259                /// queue capacity and are non-additive; byte pressure is not
1260                /// represented. Latest capacity/depth describe slot occupancy.
1261                capacity: u64,
1262                current_depth: u64,
1263                high_water_depth: u64,
1264                decode_errors: u64,
1265                /// Samples discarded because they belonged to a retired world
1266                /// history, or because a quarantined candidate timeline was
1267                /// purged when a different one became authoritative.
1268                timeline_filtered: u64,
1269                overflowed_rows: u32,
1270            }
1271
1272
1273
1274
1275            telemetry {
1276                /// Runner-originated portable performance rollup. The runner
1277                /// publishes at most one per host-monotonic grid interval;
1278                /// envelope provenance identifies the participant. Interval
1279                /// counters are best-effort sequential atomic samples, not a
1280                /// transactional stop-the-world boundary, so concurrent queue
1281                /// activity may land on either neighboring rollup.
1282                struct Rollup {
1283                    window_ns: u64,
1284                    step: Option<crate::v0_1::supervisor::RuntimeStep>,
1285                    topics: Vec<crate::v0_1::supervisor::RuntimeTopic>,
1286                    overflow: Option<crate::v0_1::supervisor::RuntimeTopic>,
1287                }
1288
1289                /// Requests the supervisor's current bounded five-minute
1290                /// runtime history.
1291                struct SnapshotRequest {
1292                    /// Optional exact participant filter. `None` selects the
1293                    /// complete per-robot history.
1294                    participant_id: Option<String>,
1295                    /// Maximum newest records to return. Zero selects the
1296                    /// supervisor's bounded default.
1297                    limit: u32,
1298                    /// Exclusive global ingest-sequence upper bound for
1299                    /// backward pagination. `None` starts at the newest record.
1300                    before_sequence: Option<u64>,
1301                }
1302
1303                /// One retained rollup. `sequence` is assigned by
1304                /// the supervisor at ingest, independent of producer metadata.
1305                /// Duplicate normal topic keys are deterministically
1306                /// re-aggregated before row bounds are applied.
1307                struct Record {
1308                    sequence: u64,
1309                    participant_id: String,
1310                    /// Text values truncated by the supervisor's ingest bound.
1311                    /// Oversized/excess topic identities are not truncated;
1312                    /// they are aggregated into the explicit overflow row.
1313                    truncated: u32,
1314                    window_ns: u64,
1315                    step: Option<crate::v0_1::supervisor::RuntimeStep>,
1316                    topics: Vec<crate::v0_1::supervisor::RuntimeTopic>,
1317                    overflow: Option<crate::v0_1::supervisor::RuntimeTopic>,
1318                }
1319
1320                struct Snapshot {
1321                    cursor: crate::v0_1::supervisor::Cursor,
1322                    records: Vec<Record>,
1323                    /// Records evicted by the absolute memory cap before their
1324                    /// five-minute age horizon elapsed.
1325                    capacity_evictions: u64,
1326                    /// Pass this as the next request's `before_sequence` to
1327                    /// continue backward. `None` means the retained matching
1328                    /// history is complete.
1329                    next_before_sequence: Option<u64>,
1330                }
1331
1332                struct Follow {
1333                    cursor: crate::v0_1::supervisor::Cursor,
1334                    record: Record,
1335                }
1336
1337                topic rollup: diagnostic Rollup;
1338                topic snapshot: query SnapshotRequest => Snapshot;
1339                topic follow: diagnostic Follow;
1340            }
1341                log {
1342                    /// Requests the supervisor's complete current bounded log snapshot. The
1343                    /// first protocol version intentionally has no pagination or
1344                    /// filtering surface.
1345                    struct SnapshotRequest {}
1346
1347                    /// Wall-clock timestamp copied from one participant-originated
1348                    /// structured `v0.1::logs` event.
1349                    struct Timestamp {
1350                        unix_seconds: i64,
1351                        nanos: u32,
1352                    }
1353
1354                    #[derive(Copy, Eq)]
1355                    #[serde(rename_all = "snake_case")]
1356                    enum Level {
1357                        Error,
1358                        Warn,
1359                        Info,
1360                        Debug,
1361                        Trace,
1362                    }
1363
1364                    #[serde(untagged)]
1365                    enum LogValue {
1366                        Bool(bool),
1367                        I64(i64),
1368                        U64(u64),
1369                        F64(f64),
1370                        String(String),
1371                    }
1372
1373                    /// One retained participant log. `sequence` is assigned by
1374                    /// the supervisor at ingest and is independent of the producer's
1375                    /// `source_sequence`.
1376                    struct Record {
1377                        sequence: u64,
1378                        participant_id: String,
1379                        source_sequence: u64,
1380                        time: Timestamp,
1381                        level: Level,
1382                        target: String,
1383                        message: String,
1384                        fields: ::std::collections::BTreeMap<String, LogValue>,
1385                        dropped: u32,
1386                        truncated: u32,
1387                    }
1388
1389                    /// The complete bounded log state at `cursor`.
1390                    struct Snapshot {
1391                        cursor: crate::v0_1::supervisor::Cursor,
1392                        /// Cumulative structured log samples evicted from
1393                        /// the supervisor's bounded ingest subscriber in this process.
1394                        /// An increase is observable, unrecoverable source loss;
1395                        /// it is distinct from producer-side `Record::dropped`.
1396                        ingest_dropped: u64,
1397                        records: Vec<Record>,
1398                    }
1399
1400                    /// One live record following the snapshot query. A consumer
1401                    /// must re-query when the generation changes or the sequence is
1402                    /// not exactly one after its installed cursor.
1403                    struct Follow {
1404                        cursor: crate::v0_1::supervisor::Cursor,
1405                        /// Current cumulative the supervisor's log collector ingest loss counter.
1406                        ingest_dropped: u64,
1407                        record: Record,
1408                    }
1409
1410                    topic snapshot: query SnapshotRequest => Snapshot;
1411                    topic follow: diagnostic Follow;
1412                }
1413            asset {
1414                /// Fetch a stored asset by path.
1415                struct GetRequest {
1416                    path: String,
1417                }
1418
1419                /// The asset bytes, a not-found marker, or a rejected path.
1420                enum GetResponse {
1421                    Found { bytes: Vec<u8> },
1422                    Missing,
1423                    InvalidPath,
1424                }
1425
1426                topic get: query GetRequest => GetResponse;
1427            }
1428        }
1429
1430    }
1431    latest v0_1;
1432}
1433
1434#[cfg(test)]
1435mod tests;