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                /// Reserved observable state for a future authenticated router
694                /// uplink. Phase 1 has no publisher for this contract.
695                #[derive(Copy, Eq)]
696                #[serde(rename_all = "snake_case")]
697                enum UplinkPhase {
698                    Disabled,
699                    Connecting,
700                    Connected,
701                    /// Reserved for future retry telemetry.
702                    Retrying,
703                }
704
705                /// Reserved router-owned state for a future optional site uplink.
706                struct State {
707                    phase: UplinkPhase,
708                    connect: Option<String>,
709                    /// Reserved for future retry telemetry.
710                    retry_attempt: u32,
711                    /// Optional human-readable diagnostic while not connected,
712                    /// such as DNS failure or waiting for the configured remote
713                    /// link. Invalid endpoints fail configuration before startup.
714                    detail: Option<String>,
715                }
716
717                topic state: state State;
718            }
719        }
720
721
722
723
724        perception {
725            /// A single detected object: class, confidence, and pose in a frame.
726            struct Detection {
727                class_id: String,
728                confidence: f32,
729                position_m: [f64; 3],
730                frame_id: String,
731                track_id: Option<u64>,
732            }
733
734            /// A batch of detections from one perception cycle.
735            struct Detections {
736                detections: Vec<Detection>,
737                stamp_ns: Option<u64>,
738            }
739
740            /// The perception participant's published health.
741            struct State {
742                healthy: bool,
743                detector: String,
744            }
745
746            topic detections: state Detections;
747            topic state: state State;
748        }
749
750        video {
751            /// Ask to open a video stream for a capability at an optional size.
752            struct OpenRequest {
753                capability: String,
754                width_px: Option<u32>,
755                height_px: Option<u32>,
756            }
757
758            /// The id of the stream that was opened.
759            struct OpenResponse {
760                stream_id: String,
761            }
762
763            topic open: query OpenRequest => OpenResponse;
764
765            stream(stream) {
766                /// Where one open video stream is in its lifecycle.
767                #[derive(Copy, Eq)]
768                #[serde(rename_all = "snake_case")]
769                enum StreamPhase {
770                    Starting,
771                    Active,
772                    Stopped,
773                }
774
775                /// The published state of one video stream: its lifecycle phase
776                /// and the number of source frames seen so far. The video participant
777                /// publishes it per stream; clients subscribe, hence `state`.
778                struct StreamState {
779                    phase: StreamPhase,
780                    frames_seen: u64,
781                }
782
783                topic state: state StreamState;
784            }
785        }
786
787        simulation {
788            /// The simulator clock: current time and whether it is advancing.
789            struct Clock {
790                now_ns: u64,
791                running: bool,
792            }
793
794            /// A command to the simulator's run loop.
795            #[derive(Copy, Eq)]
796            enum Control {
797                Pause,
798                Resume,
799                Reset,
800            }
801
802            /// The simulated robot's ground-truth planar pose.
803            struct RobotPose {
804                x_m: f64,
805                y_m: f64,
806                yaw_rad: f64,
807            }
808
809            /// Whether the simulated robot is in contact, with optional detail.
810            struct Contact {
811                in_contact: bool,
812                detail: Option<String>,
813            }
814
815            topic clock: state Clock;
816            topic control: command Control;
817            topic robot_pose: state RobotPose;
818            topic contact: state Contact;
819        }
820
821        // Per-instance component capabilities (D17/D38: framework participant / driver
822        // territory). `component(instance)` selects a manifest-declared component;
823        // each child `kind(capability)` is a self-contained node whose key is
824        // `component/{instance}/<kind>/{capability}/<leaf>`. Nodes duplicate any
825        // types they share by design - the node path disambiguates, so the names
826        // are path-local.
827        component(instance) {
828            motor(capability) {
829                /// A per-actuator command.
830                enum Command {
831                    Velocity(f32),
832                    Torque(f32),
833                    Stop,
834                }
835
836                topic command: command Command;
837            }
838
839            encoder(capability) {
840                /// Per-encoder sample on a dynamic per-instance key.
841                struct Sample {
842                    position_rad: f64,
843                    velocity_radps: f32,
844                }
845
846                topic sample: state Sample;
847            }
848
849            accelerometer(capability) {
850                /// Raw accelerometer sample in the sensor-local frame in m/s^2.
851                struct Sample {
852                    linear_acceleration: [f32; 3],
853                }
854
855                topic sample: state Sample;
856            }
857
858            gyroscope(capability) {
859                /// Raw angular velocity sample in the sensor-local frame in rad/s.
860                struct Sample {
861                    angular_velocity: [f32; 3],
862                }
863
864                topic sample: state Sample;
865            }
866
867            magnetometer(capability) {
868                /// Raw magnetic-field sample in the sensor-local frame.
869                struct Sample {
870                    magnetic_field: [f32; 3],
871                }
872
873                topic sample: state Sample;
874            }
875
876            imu(capability) {
877                #[derive(Copy, Eq)]
878                #[serde(rename_all = "snake_case")]
879                enum SensorHealth {
880                    Nominal,
881                    Degraded,
882                    Fault,
883                }
884
885                #[derive(Copy)]
886                struct Bias {
887                    angular_velocity_radps: [f32; 3],
888                    linear_acceleration_mps2: [f32; 3],
889                }
890
891                struct Sample {
892                    orientation: Option<[f32; 4]>,
893                    angular_velocity_radps: [f32; 3],
894                    linear_acceleration_mps2: [f32; 3],
895                    covariance: Option<[f32; 9]>,
896                    noise_density: Option<[f32; 3]>,
897                    sensor_frame_id: Option<String>,
898                    measured_at_ns: Option<u64>,
899                    health: SensorHealth,
900                    bias: Option<Bias>,
901                }
902
903                topic sample: state Sample;
904            }
905
906            range(capability) {
907                #[derive(Copy, Eq)]
908                #[serde(rename_all = "snake_case")]
909                enum SensorHealth {
910                    Nominal,
911                    Degraded,
912                    Fault,
913                }
914
915                #[derive(Copy)]
916                struct Limits {
917                    min_m: f32,
918                    max_m: f32,
919                }
920
921                #[derive(Copy)]
922                struct SampleQuality {
923                    valid: bool,
924                    confidence: Option<f32>,
925                }
926
927                struct Sample {
928                    distance_m: f32,
929                    limits: Option<Limits>,
930                    measured_at_ns: Option<u64>,
931                    quality: Option<SampleQuality>,
932                    health: SensorHealth,
933                }
934
935                topic sample: state Sample;
936            }
937
938            gnss(capability) {
939                /// A GNSS fix: geodetic position plus a 3x3 position covariance.
940                struct Sample {
941                    latitude: f64,
942                    longitude: f64,
943                    altitude: f64,
944                    position_covariance: [f64; 9],
945                }
946
947                topic sample: state Sample;
948            }
949
950            camera(capability) {
951                #[derive(Copy, Eq)]
952                #[serde(rename_all = "snake_case")]
953                enum Encoding {
954                    Jpeg,
955                    Png,
956                    L8,
957                    Rgb8,
958                    Rgba8,
959                }
960
961                #[derive(Copy)]
962                struct Intrinsics {
963                    fx: f32,
964                    fy: f32,
965                    cx: f32,
966                    cy: f32,
967                }
968
969                struct Distortion {
970                    model: String,
971                    coefficients: Vec<f32>,
972                }
973
974                #[derive(Copy)]
975                struct ExposureTiming {
976                    exposure_start_ns: Option<u64>,
977                    exposure_duration_ns: Option<u64>,
978                }
979
980                struct CalibrationIdentity {
981                    id: String,
982                    version: String,
983                }
984
985                /// One camera frame: encoded pixel bytes plus optional calibration
986                /// and timing metadata.
987                struct Frame {
988                    width: u32,
989                    height: u32,
990                    encoding: Encoding,
991                    intrinsics: Option<Intrinsics>,
992                    distortion: Option<Distortion>,
993                    exposure: Option<ExposureTiming>,
994                    measured_at_ns: Option<u64>,
995                    calibration: Option<CalibrationIdentity>,
996                    #[serde(with = "serde_bytes")]
997                    data: Vec<u8>,
998                }
999
1000                topic frame: state Frame;
1001            }
1002
1003            depth(capability) {
1004                #[derive(Copy, Eq)]
1005                #[serde(rename_all = "snake_case")]
1006                enum Encoding {
1007                    U16Millimeters,
1008                }
1009
1010                #[derive(Copy, Eq)]
1011                #[serde(rename_all = "snake_case")]
1012                enum InvalidSamplePolicy {
1013                    ZeroIsInvalid,
1014                    NonFiniteIsInvalid,
1015                }
1016
1017                #[derive(Copy)]
1018                struct Intrinsics {
1019                    fx: f32,
1020                    fy: f32,
1021                    cx: f32,
1022                    cy: f32,
1023                }
1024
1025                struct Distortion {
1026                    model: String,
1027                    coefficients: Vec<f32>,
1028                }
1029
1030                #[derive(Copy)]
1031                struct ExposureTiming {
1032                    exposure_start_ns: Option<u64>,
1033                    exposure_duration_ns: Option<u64>,
1034                }
1035
1036                struct CalibrationIdentity {
1037                    id: String,
1038                    version: String,
1039                }
1040
1041                /// One depth frame: per-pixel millimetre samples plus optional
1042                /// calibration and timing metadata.
1043                struct Frame {
1044                    samples_mm: Vec<u16>,
1045                    encoding: Encoding,
1046                    invalid_sample_policy: InvalidSamplePolicy,
1047                    width: Option<u32>,
1048                    height: Option<u32>,
1049                    intrinsics: Option<Intrinsics>,
1050                    distortion: Option<Distortion>,
1051                    exposure: Option<ExposureTiming>,
1052                    measured_at_ns: Option<u64>,
1053                    calibration: Option<CalibrationIdentity>,
1054                }
1055
1056                topic frame: state Frame;
1057            }
1058
1059            lidar(capability) {
1060                #[derive(Copy, Eq)]
1061                #[serde(rename_all = "snake_case")]
1062                enum SensorHealth {
1063                    Nominal,
1064                    Degraded,
1065                    Fault,
1066                }
1067
1068                #[derive(Copy)]
1069                struct ScanGeometry {
1070                    angle_min_rad: f32,
1071                    angle_increment_rad: f32,
1072                }
1073
1074                #[derive(Copy)]
1075                struct RangeLimits {
1076                    min_m: f32,
1077                    max_m: f32,
1078                }
1079
1080                #[derive(Copy)]
1081                struct ScanQuality {
1082                    valid_points: u32,
1083                }
1084
1085                struct Ranges {
1086                    ranges: Vec<f32>,
1087                    geometry: Option<ScanGeometry>,
1088                    limits: Option<RangeLimits>,
1089                    measured_at_ns: Option<u64>,
1090                    quality: Option<ScanQuality>,
1091                    health: SensorHealth,
1092                }
1093
1094                struct Points {
1095                    points: Vec<[f32; 3]>,
1096                    limits: Option<RangeLimits>,
1097                    measured_at_ns: Option<u64>,
1098                    quality: Option<ScanQuality>,
1099                    health: SensorHealth,
1100                }
1101
1102                /// One lidar scan, either as polar ranges or as cartesian points.
1103                #[serde(tag = "kind", rename_all = "snake_case")]
1104                enum Scan {
1105                    Ranges(Ranges),
1106                    Points(Points),
1107                }
1108
1109                topic scan: state Scan;
1110            }
1111
1112            mmwave(capability) {
1113                /// One mmWave radar detection: position, velocity, and SNR.
1114                #[derive(Copy)]
1115                struct Detection {
1116                    position: [f32; 3],
1117                    velocity: [f32; 3],
1118                    snr: f32,
1119                }
1120
1121                /// One mmWave radar scan as a set of detections.
1122                struct Scan {
1123                    detections: Vec<Detection>,
1124                }
1125
1126                topic scan: state Scan;
1127            }
1128
1129            microphone(capability) {
1130                /// One audio frame as raw encoded bytes.
1131                struct Frame {
1132                    data: Vec<u8>,
1133                }
1134
1135                topic frame: state Frame;
1136            }
1137
1138            led(capability) {
1139                /// A per-LED on/off command.
1140                #[derive(Copy, Eq)]
1141                enum Command {
1142                    On,
1143                    Off,
1144                }
1145
1146                topic command: command Command;
1147            }
1148
1149            emergency_stop(capability) {
1150                /// Per-instance emergency-stop state.
1151                #[derive(Eq)]
1152                struct State {
1153                    engaged: bool,
1154                }
1155
1156                topic state: state State;
1157            }
1158        }
1159
1160        odometry {
1161            /// A planar pose + twist estimate in the odometry frame.
1162            struct State {
1163                x_m: f64,
1164                y_m: f64,
1165                yaw_rad: f64,
1166                linear_x_mps: f32,
1167                angular_z_radps: f32,
1168            }
1169
1170            topic state: state State;
1171        }
1172
1173        localize {
1174            /// A planar localization estimate in the map frame.
1175            struct LocalizationState {
1176                x_m: f64,
1177                y_m: f64,
1178                yaw_rad: f64,
1179                confidence: f32,
1180            }
1181
1182            topic state: state LocalizationState;
1183        }
1184
1185        presence {
1186            /// Per-participant liveness + readiness beacon.
1187            enum Readiness {
1188                NotStarted,
1189                Initializing,
1190                Ready,
1191                Degraded,
1192                Failed,
1193            }
1194
1195            /// A single participant's liveness beacon. Participants publish their
1196            /// own heartbeat; the presence participant subscribes them as its control
1197            /// input, hence the `command` role.
1198            struct Heartbeat {
1199                participant: String,
1200                readiness: Readiness,
1201            }
1202
1203            /// The presence participant's aggregate readiness across all participants.
1204            /// Presence publishes it; clients subscribe, hence the `state` role.
1205            struct State {
1206                readiness: Readiness,
1207            }
1208
1209            topic heartbeat: command Heartbeat;
1210            topic state: state State;
1211        }
1212
1213        map {
1214            /// A published map revision marker.
1215            struct Revision {
1216                revision: u64,
1217                resolution_m: f32,
1218            }
1219
1220            /// Request a rectangular submap window (map-frame metres).
1221            struct SubmapRequest {
1222                min_x_m: f64,
1223                min_y_m: f64,
1224                max_x_m: f64,
1225                max_y_m: f64,
1226            }
1227
1228            /// An occupancy-grid window: row-major cells, 0..=100 + 255 = unknown.
1229            struct SubmapResponse {
1230                width: u32,
1231                height: u32,
1232                resolution_m: f32,
1233                cells: Vec<u8>,
1234            }
1235
1236            topic revision: state Revision;
1237            topic submap: query SubmapRequest => SubmapResponse;
1238        }
1239
1240        asset {
1241            /// Fetch a stored asset by path.
1242            struct GetRequest {
1243                path: String,
1244            }
1245
1246            /// The asset bytes, a not-found marker, or a rejected path.
1247            enum GetResponse {
1248                Found { bytes: Vec<u8> },
1249                Missing,
1250                InvalidPath,
1251            }
1252
1253            topic get: query GetRequest => GetResponse;
1254        }
1255    }
1256
1257    // v2 is the one evolving preview surface. New and changed contracts are
1258    // edited here until the complete version is ready to freeze; preview work
1259    // does not mint another public API namespace for each implementation batch.
1260    preview version v2 {
1261        battery {
1262            /// Battery state remains preview while hardware ownership evolves.
1263            struct State {
1264                voltage_v: f32,
1265                current_a: f32,
1266                charge_ratio: f32,
1267            }
1268
1269            topic state: state State;
1270        }
1271
1272        simulation {
1273            /// One robot node that the simulator spawn authority should import.
1274            struct RobotSpawn {
1275                robot_id: String,
1276                node_string: String,
1277            }
1278
1279            /// Requests the current complete robot spawn set.
1280            ///
1281            /// `known_revision` lets a future responder distinguish initial
1282            /// bootstrap from refreshes after a runtime join. Responders may
1283            /// still return the current set when the revision is unchanged.
1284            struct SpawnRequest {
1285                known_revision: Option<u64>,
1286            }
1287
1288            /// The complete robot spawn set for one simulation world.
1289            struct SpawnSet {
1290                revision: u64,
1291                robots: Vec<RobotSpawn>,
1292            }
1293
1294            /// The authoritative advancing simulation clock. Publication means
1295            /// the world advanced; silence means it did not.
1296            struct Clock {
1297                now_ns: u64,
1298                step: u64,
1299            }
1300
1301            topic spawn: query SpawnRequest => SpawnSet;
1302            topic clock: state Clock;
1303        }
1304
1305        router {
1306            /// One topic-producer pair's measured ingress over the sample
1307            /// window. Row identity is `(topic, from_participant)`;
1308            /// `from_participant == ""` means the sample had no decodable
1309            /// Phoxal producer envelope. Quiet rows disappear after a short
1310            /// grace period and are then evicted, so
1311            /// `count` is cumulative only for the current observed lifetime
1312            /// and may restart from zero if that pair later returns. The
1313            /// sentinel `topic == "" && from_participant == ""` aggregates
1314            /// traffic omitted when the bounded detailed table is full or the
1315            /// bus tool's non-blocking observation queue drops a burst or an
1316            /// observation has oversized identity metadata. Those
1317            /// drops never apply backpressure to robot traffic. Once emitted,
1318            /// the sentinel remains present for the session so consumers do
1319            /// not lose the fact that earlier traffic was unattributed; its
1320            /// window rate may be zero in later snapshots.
1321            struct TopicMetric {
1322                topic: String,
1323                from_participant: String,
1324                ingress_rate_hz: f32,
1325                count: u64,
1326            }
1327
1328            /// The bus tool's measured message-flow snapshot for this robot
1329            /// bus root; 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;