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        tool {
683            /// Opaque identity for one retention-tool process together with a
684            /// position in its completed follow stream. A snapshot cursor
685            /// covers the retained completed items; a bus snapshot's optional
686            /// `current` window deliberately has the next sequence. Consumers
687            /// compare `generation` for equality only and must never parse or
688            /// order it.
689            #[derive(Eq)]
690            struct Cursor {
691                generation: String,
692                sequence: u64,
693            }
694
695            /// Which side of one participant-local bus buffer a runtime row
696            /// measures. The version-qualified `topic` field remains the wire
697            /// identity; direction is never inferred from its spelling.
698            #[derive(Copy, Eq, Ord, PartialOrd)]
699            #[serde(rename_all = "snake_case")]
700            enum RuntimeDirection {
701                Publish,
702                Subscribe,
703                /// Used only by the bounded overflow row, which may combine
704                /// omitted rows from both directions.
705                Mixed,
706            }
707
708            /// The concrete bounded buffer whose pressure a runtime row
709            /// measures.
710            #[derive(Copy, Eq, Ord, PartialOrd)]
711            #[serde(rename_all = "snake_case")]
712            enum RuntimeBufferKind {
713                /// Per-topic view of the one shared process outbound queue.
714                /// Its sample capacity is repeated on each row and must not be
715                /// summed; the queue's separate byte pressure is not in v0.1.
716                Outbound,
717                /// Keep-last slot. Depth `1` means occupied, never backlog.
718                Latest,
719                Subscriber,
720                /// Used only by the bounded overflow row.
721                Mixed,
722            }
723
724            /// Host-monotonic scheduled-step work completed during one rollup
725            /// window. An unscheduled participant reports `None` instead.
726            struct RuntimeStep {
727                target_period_ns: u64,
728                completed: u64,
729                errors: u64,
730                mean_duration_ns: u64,
731                max_duration_ns: u64,
732                mean_lateness_ns: u64,
733                max_lateness_ns: u64,
734                missed_ticks: u64,
735                overruns: u64,
736            }
737
738            /// One exact version-qualified topic/direction/buffer row. These
739            /// are process-lifetime setup declarations: dropping an authoring
740            /// handle does not dynamically unregister a row. Empty `topic`
741            /// plus `Mixed` direction/kind identifies the explicit overflow
742            /// row; `overflowed_rows` is zero on normal rows.
743            struct RuntimeTopic {
744                topic: String,
745                direction: RuntimeDirection,
746                buffer_kind: RuntimeBufferKind,
747                count: u64,
748                /// Finite, non-negative message rate. Retention tools clamp
749                /// malformed non-finite inputs before they reach snapshots.
750                rate_hz: f32,
751                drops: u64,
752                latest_overwrites: u64,
753                bounded_evictions: u64,
754                /// Sample capacity. Outbound rows repeat the shared process
755                /// queue capacity and are non-additive; byte pressure is not
756                /// represented. Latest capacity/depth describe slot occupancy.
757                capacity: u64,
758                current_depth: u64,
759                high_water_depth: u64,
760                decode_errors: u64,
761                /// Samples discarded because they belonged to a retired world
762                /// history, or because a quarantined candidate timeline was
763                /// purged when a different one became authoritative.
764                timeline_filtered: u64,
765                overflowed_rows: u32,
766            }
767
768
769
770
771            runtime {
772                /// Runner-originated portable performance rollup. The runner
773                /// publishes at most one per host-monotonic grid interval;
774                /// envelope provenance identifies the participant. Interval
775                /// counters are best-effort sequential atomic samples, not a
776                /// transactional stop-the-world boundary, so concurrent queue
777                /// activity may land on either neighboring rollup.
778                struct Rollup {
779                    window_ns: u64,
780                    step: Option<crate::v0_1::tool::RuntimeStep>,
781                    topics: Vec<crate::v0_1::tool::RuntimeTopic>,
782                    overflow: Option<crate::v0_1::tool::RuntimeTopic>,
783                }
784
785                /// Requests tool-telemetry's current bounded five-minute
786                /// runtime history.
787                struct SnapshotRequest {
788                    /// Optional exact participant filter. `None` selects the
789                    /// complete per-robot history.
790                    participant_id: Option<String>,
791                    /// Maximum newest records to return. Zero selects the
792                    /// tool's bounded default.
793                    limit: u32,
794                    /// Exclusive global ingest-sequence upper bound for
795                    /// backward pagination. `None` starts at the newest record.
796                    before_sequence: Option<u64>,
797                }
798
799                /// One retained rollup. `sequence` is assigned by
800                /// tool-telemetry at ingest, independent of producer metadata.
801                /// Duplicate normal topic keys are deterministically
802                /// re-aggregated before row bounds are applied.
803                struct Record {
804                    sequence: u64,
805                    participant_id: String,
806                    /// Text values truncated by tool-telemetry's ingest bound.
807                    /// Oversized/excess topic identities are not truncated;
808                    /// they are aggregated into the explicit overflow row.
809                    truncated: u32,
810                    window_ns: u64,
811                    step: Option<crate::v0_1::tool::RuntimeStep>,
812                    topics: Vec<crate::v0_1::tool::RuntimeTopic>,
813                    overflow: Option<crate::v0_1::tool::RuntimeTopic>,
814                }
815
816                struct Snapshot {
817                    cursor: crate::v0_1::tool::Cursor,
818                    records: Vec<Record>,
819                    /// Records evicted by the absolute memory cap before their
820                    /// five-minute age horizon elapsed.
821                    capacity_evictions: u64,
822                    /// Pass this as the next request's `before_sequence` to
823                    /// continue backward. `None` means the retained matching
824                    /// history is complete.
825                    next_before_sequence: Option<u64>,
826                }
827
828                struct Follow {
829                    cursor: crate::v0_1::tool::Cursor,
830                    record: Record,
831                }
832
833                topic rollup: diagnostic Rollup;
834                topic snapshot: query SnapshotRequest => Snapshot;
835                topic follow: diagnostic Follow;
836            }
837        }
838
839
840
841
842
843        perception {
844            /// A single detected object: class, confidence, and pose in a frame.
845            struct Detection {
846                class_id: String,
847                confidence: f32,
848                position_m: [f64; 3],
849                frame_id: String,
850                track_id: Option<u64>,
851            }
852
853            /// A batch of detections from one perception cycle.
854            struct Detections {
855                detections: Vec<Detection>,
856                /// The frame instant these detections were derived from.
857                stamp: Option<::phoxal_bus::RobotInstant>,
858            }
859
860            /// The perception participant's published health.
861            struct State {
862                healthy: bool,
863                detector: String,
864            }
865
866            topic detections: state Detections;
867            topic state: state State;
868        }
869
870        video {
871            /// Ask to open a video stream for a capability at an optional size.
872            struct OpenRequest {
873                capability: String,
874                width_px: Option<u32>,
875                height_px: Option<u32>,
876            }
877
878            /// The id of the stream that was opened.
879            struct OpenResponse {
880                stream_id: String,
881            }
882
883            topic open: query OpenRequest => OpenResponse;
884
885            stream(stream) {
886                /// Where one open video stream is in its lifecycle.
887                #[derive(Copy, Eq)]
888                #[serde(rename_all = "snake_case")]
889                enum StreamPhase {
890                    Starting,
891                    Active,
892                    Stopped,
893                }
894
895                /// The published state of one video stream: its lifecycle phase
896                /// and the number of source frames seen so far. The video participant
897                /// publishes it per stream; clients subscribe, hence `state`.
898                struct StreamState {
899                    phase: StreamPhase,
900                    frames_seen: u64,
901                }
902
903                topic state: state StreamState;
904            }
905        }
906
907        simulation {
908            /// The authoritative advancing simulation clock. Publication means
909            /// the world advanced; silence means it did not.
910            ///
911            /// The timeline and instant ride in the envelope, like every other
912            /// `state`-shaped publication - the world authority stamps them with
913            /// a world step token. The body carries only the step counter, which
914            /// is not derivable from the envelope.
915            struct Clock {
916                step: u64,
917            }
918
919            // `world_clock`, not `state`: only the world-authority participant
920            // (`#[phoxal::simulator]`) may publish it, enforced at compile time
921            // by the disjoint `WorldClockContract` this role generates instead
922            // of `StateContract`; see
923            // `phoxal_bus::contract::WorldClockContract`'s docs.
924            topic clock: world_clock Clock;
925        }
926
927        // Per-instance component capabilities (D17/D38: framework participant / driver
928        // territory). `component(instance)` selects a manifest-declared component;
929        // each child `kind(capability)` is a self-contained node whose key is
930        // `component/{instance}/<kind>/{capability}/<leaf>`. Nodes duplicate any
931        // types they share by design - the node path disambiguates, so the names
932        // are path-local.
933        component(instance) {
934            motor(capability) {
935                /// A per-actuator command.
936                enum Command {
937                    Velocity(f32),
938                    Torque(f32),
939                    Stop,
940                }
941
942                topic command: command Command;
943            }
944
945            encoder(capability) {
946                /// Per-encoder sample on a dynamic per-instance key.
947                struct Sample {
948                    position_rad: f64,
949                    velocity_radps: f32,
950                }
951
952                topic sample: measurement Sample;
953            }
954
955            accelerometer(capability) {
956                /// Raw accelerometer sample in the sensor-local frame in m/s^2.
957                struct Sample {
958                    linear_acceleration: [f32; 3],
959                }
960
961                topic sample: measurement Sample;
962            }
963
964            gyroscope(capability) {
965                /// Raw angular velocity sample in the sensor-local frame in rad/s.
966                struct Sample {
967                    angular_velocity: [f32; 3],
968                }
969
970                topic sample: measurement Sample;
971            }
972
973            magnetometer(capability) {
974                /// Raw magnetic-field sample in the sensor-local frame.
975                struct Sample {
976                    magnetic_field: [f32; 3],
977                }
978
979                topic sample: measurement Sample;
980            }
981
982            imu(capability) {
983                #[derive(Copy, Eq)]
984                #[serde(rename_all = "snake_case")]
985                enum SensorHealth {
986                    Nominal,
987                    Degraded,
988                    Fault,
989                }
990
991                #[derive(Copy)]
992                struct Bias {
993                    angular_velocity_radps: [f32; 3],
994                    linear_acceleration_mps2: [f32; 3],
995                }
996
997                struct Sample {
998                    orientation: Option<[f32; 4]>,
999                    angular_velocity_radps: [f32; 3],
1000                    linear_acceleration_mps2: [f32; 3],
1001                    covariance: Option<[f32; 9]>,
1002                    noise_density: Option<[f32; 3]>,
1003                    sensor_frame_id: Option<String>,
1004                    health: SensorHealth,
1005                    bias: Option<Bias>,
1006                }
1007
1008                topic sample: measurement Sample;
1009            }
1010
1011            range(capability) {
1012                #[derive(Copy, Eq)]
1013                #[serde(rename_all = "snake_case")]
1014                enum SensorHealth {
1015                    Nominal,
1016                    Degraded,
1017                    Fault,
1018                }
1019
1020                #[derive(Copy)]
1021                struct Limits {
1022                    min_m: f32,
1023                    max_m: f32,
1024                }
1025
1026                #[derive(Copy)]
1027                struct SampleQuality {
1028                    valid: bool,
1029                    confidence: Option<f32>,
1030                }
1031
1032                struct Sample {
1033                    distance_m: f32,
1034                    limits: Option<Limits>,
1035                    quality: Option<SampleQuality>,
1036                    health: SensorHealth,
1037                }
1038
1039                topic sample: measurement Sample;
1040            }
1041
1042            gnss(capability) {
1043                /// A GNSS fix: geodetic position plus a 3x3 position covariance.
1044                struct Sample {
1045                    latitude: f64,
1046                    longitude: f64,
1047                    altitude: f64,
1048                    position_covariance: [f64; 9],
1049                }
1050
1051                topic sample: measurement Sample;
1052            }
1053
1054            camera(capability) {
1055                #[derive(Copy, Eq)]
1056                #[serde(rename_all = "snake_case")]
1057                enum Encoding {
1058                    Jpeg,
1059                    Png,
1060                    L8,
1061                    Rgb8,
1062                    Rgba8,
1063                }
1064
1065                #[derive(Copy)]
1066                struct Intrinsics {
1067                    fx: f32,
1068                    fy: f32,
1069                    cx: f32,
1070                    cy: f32,
1071                }
1072
1073                struct Distortion {
1074                    model: String,
1075                    coefficients: Vec<f32>,
1076                }
1077
1078                #[derive(Copy)]
1079                struct ExposureTiming {
1080                    exposure_start_ns: Option<u64>,
1081                    exposure_duration_ns: Option<u64>,
1082                }
1083
1084                struct CalibrationIdentity {
1085                    id: String,
1086                    version: String,
1087                }
1088
1089                /// One camera frame: encoded pixel bytes plus optional calibration
1090                /// and timing metadata.
1091                struct Frame {
1092                    width: u32,
1093                    height: u32,
1094                    encoding: Encoding,
1095                    intrinsics: Option<Intrinsics>,
1096                    distortion: Option<Distortion>,
1097                    exposure: Option<ExposureTiming>,
1098                    calibration: Option<CalibrationIdentity>,
1099                    #[serde(with = "serde_bytes")]
1100                    data: Vec<u8>,
1101                }
1102
1103                topic frame: measurement Frame;
1104            }
1105
1106            depth(capability) {
1107                #[derive(Copy, Eq)]
1108                #[serde(rename_all = "snake_case")]
1109                enum Encoding {
1110                    U16Millimeters,
1111                }
1112
1113                #[derive(Copy, Eq)]
1114                #[serde(rename_all = "snake_case")]
1115                enum InvalidSamplePolicy {
1116                    ZeroIsInvalid,
1117                    NonFiniteIsInvalid,
1118                }
1119
1120                #[derive(Copy)]
1121                struct Intrinsics {
1122                    fx: f32,
1123                    fy: f32,
1124                    cx: f32,
1125                    cy: f32,
1126                }
1127
1128                struct Distortion {
1129                    model: String,
1130                    coefficients: Vec<f32>,
1131                }
1132
1133                #[derive(Copy)]
1134                struct ExposureTiming {
1135                    exposure_start_ns: Option<u64>,
1136                    exposure_duration_ns: Option<u64>,
1137                }
1138
1139                struct CalibrationIdentity {
1140                    id: String,
1141                    version: String,
1142                }
1143
1144                /// One depth frame: per-pixel millimetre samples plus optional
1145                /// calibration and timing metadata.
1146                struct Frame {
1147                    samples_mm: Vec<u16>,
1148                    encoding: Encoding,
1149                    invalid_sample_policy: InvalidSamplePolicy,
1150                    width: Option<u32>,
1151                    height: Option<u32>,
1152                    intrinsics: Option<Intrinsics>,
1153                    distortion: Option<Distortion>,
1154                    exposure: Option<ExposureTiming>,
1155                    calibration: Option<CalibrationIdentity>,
1156                }
1157
1158                topic frame: measurement Frame;
1159            }
1160
1161            lidar(capability) {
1162                #[derive(Copy, Eq)]
1163                #[serde(rename_all = "snake_case")]
1164                enum SensorHealth {
1165                    Nominal,
1166                    Degraded,
1167                    Fault,
1168                }
1169
1170                #[derive(Copy)]
1171                struct ScanGeometry {
1172                    angle_min_rad: f32,
1173                    angle_increment_rad: f32,
1174                }
1175
1176                #[derive(Copy)]
1177                struct RangeLimits {
1178                    min_m: f32,
1179                    max_m: f32,
1180                }
1181
1182                #[derive(Copy)]
1183                struct ScanQuality {
1184                    valid_points: u32,
1185                }
1186
1187                struct Ranges {
1188                    ranges: Vec<f32>,
1189                    geometry: Option<ScanGeometry>,
1190                    limits: Option<RangeLimits>,
1191                    quality: Option<ScanQuality>,
1192                    health: SensorHealth,
1193                }
1194
1195                struct Points {
1196                    points: Vec<[f32; 3]>,
1197                    limits: Option<RangeLimits>,
1198                    quality: Option<ScanQuality>,
1199                    health: SensorHealth,
1200                }
1201
1202                /// One lidar scan, either as polar ranges or as cartesian points.
1203                #[serde(tag = "kind", rename_all = "snake_case")]
1204                enum Scan {
1205                    Ranges(Ranges),
1206                    Points(Points),
1207                }
1208
1209                topic scan: measurement Scan;
1210            }
1211
1212            mmwave(capability) {
1213                /// One mmWave radar detection: position, velocity, and SNR.
1214                #[derive(Copy)]
1215                struct Detection {
1216                    position: [f32; 3],
1217                    velocity: [f32; 3],
1218                    snr: f32,
1219                }
1220
1221                /// One mmWave radar scan as a set of detections.
1222                struct Scan {
1223                    detections: Vec<Detection>,
1224                }
1225
1226                topic scan: measurement Scan;
1227            }
1228
1229            microphone(capability) {
1230                /// One audio frame as raw encoded bytes.
1231                struct Frame {
1232                    data: Vec<u8>,
1233                }
1234
1235                topic frame: measurement Frame;
1236            }
1237
1238            led(capability) {
1239                /// A per-LED on/off command.
1240                #[derive(Copy, Eq)]
1241                enum Command {
1242                    On,
1243                    Off,
1244                }
1245
1246                topic command: command Command;
1247            }
1248
1249            speaker(capability) {
1250                /// One chunk of an audio stream to play on this speaker.
1251                ///
1252                /// `Some(bytes)` carries WAV-coded audio: the first chunk of a
1253                /// stream starts with the standard WAV header, later chunks
1254                /// continue its data. `None` ends the stream and is what tells
1255                /// the owner the sound is complete.
1256                struct Chunk {
1257                    stream: Option<Vec<u8>>,
1258                }
1259
1260                topic stream: command Chunk;
1261            }
1262
1263            battery(capability) {
1264                /// Battery state reported by the pack's owner - the simulator
1265                /// backing this capability, or the real driver.
1266                struct State {
1267                    voltage_v: f32,
1268                    current_a: f32,
1269                    charge_ratio: f32,
1270                }
1271
1272                topic state: state State;
1273            }
1274
1275            emergency_stop(capability) {
1276                /// Per-instance emergency-stop state.
1277                #[derive(Eq)]
1278                struct State {
1279                    engaged: bool,
1280                }
1281
1282                topic state: state State;
1283            }
1284        }
1285
1286        odometry {
1287            /// A planar pose + twist estimate in the odometry frame.
1288            struct State {
1289                x_m: f64,
1290                y_m: f64,
1291                yaw_rad: f64,
1292                linear_x_mps: f32,
1293                angular_z_radps: f32,
1294            }
1295
1296            topic state: state State;
1297        }
1298
1299        localize {
1300            /// A planar localization estimate in the map frame.
1301            struct LocalizationState {
1302                x_m: f64,
1303                y_m: f64,
1304                yaw_rad: f64,
1305                confidence: f32,
1306            }
1307
1308            topic state: state LocalizationState;
1309        }
1310
1311        map {
1312            /// A published map revision marker.
1313            struct Revision {
1314                revision: u64,
1315                resolution_m: f32,
1316            }
1317
1318            /// Request a rectangular submap window (map-frame metres).
1319            struct SubmapRequest {
1320                min_x_m: f64,
1321                min_y_m: f64,
1322                max_x_m: f64,
1323                max_y_m: f64,
1324            }
1325
1326            /// An occupancy-grid window: row-major cells, 0..=100 + 255 = unknown.
1327            struct SubmapResponse {
1328                width: u32,
1329                height: u32,
1330                resolution_m: f32,
1331                cells: Vec<u8>,
1332            }
1333
1334            topic revision: state Revision;
1335            topic submap: query SubmapRequest => SubmapResponse;
1336        }
1337
1338        // Contracts the supervisor itself answers. The node is part of the
1339        // wire key, so a reader can tell from the key alone that the supervisor
1340        // is the authority - and a stale participant sitting on an old key
1341        // physically cannot answer one of these (organization#978).
1342        supervisor {
1343                log {
1344                    /// Requests the supervisor's complete current bounded log snapshot. The
1345                    /// first protocol version intentionally has no pagination or
1346                    /// filtering surface.
1347                    struct SnapshotRequest {}
1348
1349                    /// Wall-clock timestamp copied from one participant-originated
1350                    /// structured `v0.1::logs` event.
1351                    struct Timestamp {
1352                        unix_seconds: i64,
1353                        nanos: u32,
1354                    }
1355
1356                    #[derive(Copy, Eq)]
1357                    #[serde(rename_all = "snake_case")]
1358                    enum Level {
1359                        Error,
1360                        Warn,
1361                        Info,
1362                        Debug,
1363                        Trace,
1364                    }
1365
1366                    #[serde(untagged)]
1367                    enum LogValue {
1368                        Bool(bool),
1369                        I64(i64),
1370                        U64(u64),
1371                        F64(f64),
1372                        String(String),
1373                    }
1374
1375                    /// One retained participant log. `sequence` is assigned by
1376                    /// the supervisor at ingest and is independent of the producer's
1377                    /// `source_sequence`.
1378                    struct Record {
1379                        sequence: u64,
1380                        participant_id: String,
1381                        source_sequence: u64,
1382                        time: Timestamp,
1383                        level: Level,
1384                        target: String,
1385                        message: String,
1386                        fields: ::std::collections::BTreeMap<String, LogValue>,
1387                        dropped: u32,
1388                        truncated: u32,
1389                    }
1390
1391                    /// The complete bounded log state at `cursor`.
1392                    struct Snapshot {
1393                        cursor: crate::v0_1::tool::Cursor,
1394                        /// Cumulative structured log samples evicted from
1395                        /// the supervisor's bounded ingest subscriber in this process.
1396                        /// An increase is observable, unrecoverable source loss;
1397                        /// it is distinct from producer-side `Record::dropped`.
1398                        ingest_dropped: u64,
1399                        records: Vec<Record>,
1400                    }
1401
1402                    /// One live record following the snapshot query. A consumer
1403                    /// must re-query when the generation changes or the sequence is
1404                    /// not exactly one after its installed cursor.
1405                    struct Follow {
1406                        cursor: crate::v0_1::tool::Cursor,
1407                        /// Current cumulative the supervisor's log collector ingest loss counter.
1408                        ingest_dropped: u64,
1409                        record: Record,
1410                    }
1411
1412                    topic snapshot: query SnapshotRequest => Snapshot;
1413                    topic follow: diagnostic Follow;
1414                }
1415            asset {
1416                /// Fetch a stored asset by path.
1417                struct GetRequest {
1418                    path: String,
1419                }
1420
1421                /// The asset bytes, a not-found marker, or a rejected path.
1422                enum GetResponse {
1423                    Found { bytes: Vec<u8> },
1424                    Missing,
1425                    InvalidPath,
1426                }
1427
1428                topic get: query GetRequest => GetResponse;
1429            }
1430        }
1431
1432        joypad {
1433            /// Whether an observed controller is ready for the fixed manual
1434            /// input preset, disconnected, or connected without a compatible
1435            /// control mapping.
1436            enum DeviceStatus {
1437                Ready,
1438                Disconnected,
1439                Unsupported,
1440            }
1441
1442            /// One gamepad the tool can see. `id` is a STABLE wire id the tool
1443            /// assigns (name/guid-derived) - NOT a process-local gilrs id.
1444            struct Device {
1445                id: String,
1446                name: String,
1447                status: DeviceStatus,
1448            }
1449
1450            /// The joypad tool's published device state.
1451            struct Devices {
1452                available: Vec<Device>,
1453                selected: Option<String>,
1454                enabled: bool,
1455                /// Structural reason manual input cannot be enabled in this
1456                /// session (for example robot-model or backend limitations),
1457                /// independent of transient device/request errors.
1458                unavailable_reason: Option<String>,
1459                /// One-shot acknowledgement of a failed select/enable/rescan
1460                /// request. Event-driven consumers may show it once; periodic
1461                /// state heartbeats omit it. The tool also writes the failure
1462                /// to its log stream for durable diagnostics.
1463                last_error: Option<String>,
1464            }
1465
1466            /// Client asks the tool to select a device by its stable id.
1467            struct Select {
1468                id: String,
1469            }
1470
1471            /// Client asks the tool to enable or disable manual input.
1472            struct SetEnabled {
1473                enabled: bool,
1474            }
1475
1476            /// Client asks the tool to re-enumerate devices.
1477            struct Rescan {}
1478
1479            topic devices: diagnostic Devices;
1480            topic select: command Select;
1481            topic set_enabled: command SetEnabled;
1482            topic rescan: command Rescan;
1483        }
1484    }
1485    latest v0_1;
1486}
1487
1488#[cfg(test)]
1489mod tests;