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 log {
769 /// Requests tool-log's complete current bounded snapshot. The
770 /// first protocol version intentionally has no pagination or
771 /// filtering surface.
772 struct SnapshotRequest {}
773
774 /// Wall-clock timestamp copied from one participant-originated
775 /// structured `v0.1::logs` event.
776 struct Timestamp {
777 unix_seconds: i64,
778 nanos: u32,
779 }
780
781 #[derive(Copy, Eq)]
782 #[serde(rename_all = "snake_case")]
783 enum Level {
784 Error,
785 Warn,
786 Info,
787 Debug,
788 Trace,
789 }
790
791 #[serde(untagged)]
792 enum LogValue {
793 Bool(bool),
794 I64(i64),
795 U64(u64),
796 F64(f64),
797 String(String),
798 }
799
800 /// One retained participant log. `sequence` is assigned by
801 /// tool-log at ingest and is independent of the producer's
802 /// `source_sequence`.
803 struct Record {
804 sequence: u64,
805 participant_id: String,
806 source_sequence: u64,
807 time: Timestamp,
808 level: Level,
809 target: String,
810 message: String,
811 fields: ::std::collections::BTreeMap<String, LogValue>,
812 dropped: u32,
813 truncated: u32,
814 }
815
816 /// The complete bounded tool-log state at `cursor`.
817 struct Snapshot {
818 cursor: crate::v0_1::tool::Cursor,
819 /// Cumulative structured log samples evicted from
820 /// tool-log's bounded ingest subscriber in this process.
821 /// An increase is observable, unrecoverable source loss;
822 /// it is distinct from producer-side `Record::dropped`.
823 ingest_dropped: u64,
824 records: Vec<Record>,
825 }
826
827 /// One live record following the snapshot query. A consumer
828 /// must re-query when the generation changes or the sequence is
829 /// not exactly one after its installed cursor.
830 struct Follow {
831 cursor: crate::v0_1::tool::Cursor,
832 /// Current cumulative tool-log ingest loss counter.
833 ingest_dropped: u64,
834 record: Record,
835 }
836
837 topic snapshot: query SnapshotRequest => Snapshot;
838 topic follow: diagnostic Follow;
839 }
840
841
842
843 runtime {
844 /// Runner-originated portable performance rollup. The runner
845 /// publishes at most one per host-monotonic grid interval;
846 /// envelope provenance identifies the participant. Interval
847 /// counters are best-effort sequential atomic samples, not a
848 /// transactional stop-the-world boundary, so concurrent queue
849 /// activity may land on either neighboring rollup.
850 struct Rollup {
851 window_ns: u64,
852 step: Option<crate::v0_1::tool::RuntimeStep>,
853 topics: Vec<crate::v0_1::tool::RuntimeTopic>,
854 overflow: Option<crate::v0_1::tool::RuntimeTopic>,
855 }
856
857 /// Requests tool-telemetry's current bounded five-minute
858 /// runtime history.
859 struct SnapshotRequest {
860 /// Optional exact participant filter. `None` selects the
861 /// complete per-robot history.
862 participant_id: Option<String>,
863 /// Maximum newest records to return. Zero selects the
864 /// tool's bounded default.
865 limit: u32,
866 /// Exclusive global ingest-sequence upper bound for
867 /// backward pagination. `None` starts at the newest record.
868 before_sequence: Option<u64>,
869 }
870
871 /// One retained rollup. `sequence` is assigned by
872 /// tool-telemetry at ingest, independent of producer metadata.
873 /// Duplicate normal topic keys are deterministically
874 /// re-aggregated before row bounds are applied.
875 struct Record {
876 sequence: u64,
877 participant_id: String,
878 /// Text values truncated by tool-telemetry's ingest bound.
879 /// Oversized/excess topic identities are not truncated;
880 /// they are aggregated into the explicit overflow row.
881 truncated: u32,
882 window_ns: u64,
883 step: Option<crate::v0_1::tool::RuntimeStep>,
884 topics: Vec<crate::v0_1::tool::RuntimeTopic>,
885 overflow: Option<crate::v0_1::tool::RuntimeTopic>,
886 }
887
888 struct Snapshot {
889 cursor: crate::v0_1::tool::Cursor,
890 records: Vec<Record>,
891 /// Records evicted by the absolute memory cap before their
892 /// five-minute age horizon elapsed.
893 capacity_evictions: u64,
894 /// Pass this as the next request's `before_sequence` to
895 /// continue backward. `None` means the retained matching
896 /// history is complete.
897 next_before_sequence: Option<u64>,
898 }
899
900 struct Follow {
901 cursor: crate::v0_1::tool::Cursor,
902 record: Record,
903 }
904
905 topic rollup: diagnostic Rollup;
906 topic snapshot: query SnapshotRequest => Snapshot;
907 topic follow: diagnostic Follow;
908 }
909 }
910
911
912
913
914
915 perception {
916 /// A single detected object: class, confidence, and pose in a frame.
917 struct Detection {
918 class_id: String,
919 confidence: f32,
920 position_m: [f64; 3],
921 frame_id: String,
922 track_id: Option<u64>,
923 }
924
925 /// A batch of detections from one perception cycle.
926 struct Detections {
927 detections: Vec<Detection>,
928 /// The frame instant these detections were derived from.
929 stamp: Option<::phoxal_bus::RobotInstant>,
930 }
931
932 /// The perception participant's published health.
933 struct State {
934 healthy: bool,
935 detector: String,
936 }
937
938 topic detections: state Detections;
939 topic state: state State;
940 }
941
942 video {
943 /// Ask to open a video stream for a capability at an optional size.
944 struct OpenRequest {
945 capability: String,
946 width_px: Option<u32>,
947 height_px: Option<u32>,
948 }
949
950 /// The id of the stream that was opened.
951 struct OpenResponse {
952 stream_id: String,
953 }
954
955 topic open: query OpenRequest => OpenResponse;
956
957 stream(stream) {
958 /// Where one open video stream is in its lifecycle.
959 #[derive(Copy, Eq)]
960 #[serde(rename_all = "snake_case")]
961 enum StreamPhase {
962 Starting,
963 Active,
964 Stopped,
965 }
966
967 /// The published state of one video stream: its lifecycle phase
968 /// and the number of source frames seen so far. The video participant
969 /// publishes it per stream; clients subscribe, hence `state`.
970 struct StreamState {
971 phase: StreamPhase,
972 frames_seen: u64,
973 }
974
975 topic state: state StreamState;
976 }
977 }
978
979 simulation {
980 /// The authoritative advancing simulation clock. Publication means
981 /// the world advanced; silence means it did not.
982 ///
983 /// The timeline and instant ride in the envelope, like every other
984 /// `state`-shaped publication - the world authority stamps them with
985 /// a world step token. The body carries only the step counter, which
986 /// is not derivable from the envelope.
987 struct Clock {
988 step: u64,
989 }
990
991 // `world_clock`, not `state`: only the world-authority participant
992 // (`#[phoxal::simulator]`) may publish it, enforced at compile time
993 // by the disjoint `WorldClockContract` this role generates instead
994 // of `StateContract`; see
995 // `phoxal_bus::contract::WorldClockContract`'s docs.
996 topic clock: world_clock Clock;
997 }
998
999 // Per-instance component capabilities (D17/D38: framework participant / driver
1000 // territory). `component(instance)` selects a manifest-declared component;
1001 // each child `kind(capability)` is a self-contained node whose key is
1002 // `component/{instance}/<kind>/{capability}/<leaf>`. Nodes duplicate any
1003 // types they share by design - the node path disambiguates, so the names
1004 // are path-local.
1005 component(instance) {
1006 motor(capability) {
1007 /// A per-actuator command.
1008 enum Command {
1009 Velocity(f32),
1010 Torque(f32),
1011 Stop,
1012 }
1013
1014 topic command: command Command;
1015 }
1016
1017 encoder(capability) {
1018 /// Per-encoder sample on a dynamic per-instance key.
1019 struct Sample {
1020 position_rad: f64,
1021 velocity_radps: f32,
1022 }
1023
1024 topic sample: measurement Sample;
1025 }
1026
1027 accelerometer(capability) {
1028 /// Raw accelerometer sample in the sensor-local frame in m/s^2.
1029 struct Sample {
1030 linear_acceleration: [f32; 3],
1031 }
1032
1033 topic sample: measurement Sample;
1034 }
1035
1036 gyroscope(capability) {
1037 /// Raw angular velocity sample in the sensor-local frame in rad/s.
1038 struct Sample {
1039 angular_velocity: [f32; 3],
1040 }
1041
1042 topic sample: measurement Sample;
1043 }
1044
1045 magnetometer(capability) {
1046 /// Raw magnetic-field sample in the sensor-local frame.
1047 struct Sample {
1048 magnetic_field: [f32; 3],
1049 }
1050
1051 topic sample: measurement Sample;
1052 }
1053
1054 imu(capability) {
1055 #[derive(Copy, Eq)]
1056 #[serde(rename_all = "snake_case")]
1057 enum SensorHealth {
1058 Nominal,
1059 Degraded,
1060 Fault,
1061 }
1062
1063 #[derive(Copy)]
1064 struct Bias {
1065 angular_velocity_radps: [f32; 3],
1066 linear_acceleration_mps2: [f32; 3],
1067 }
1068
1069 struct Sample {
1070 orientation: Option<[f32; 4]>,
1071 angular_velocity_radps: [f32; 3],
1072 linear_acceleration_mps2: [f32; 3],
1073 covariance: Option<[f32; 9]>,
1074 noise_density: Option<[f32; 3]>,
1075 sensor_frame_id: Option<String>,
1076 health: SensorHealth,
1077 bias: Option<Bias>,
1078 }
1079
1080 topic sample: measurement Sample;
1081 }
1082
1083 range(capability) {
1084 #[derive(Copy, Eq)]
1085 #[serde(rename_all = "snake_case")]
1086 enum SensorHealth {
1087 Nominal,
1088 Degraded,
1089 Fault,
1090 }
1091
1092 #[derive(Copy)]
1093 struct Limits {
1094 min_m: f32,
1095 max_m: f32,
1096 }
1097
1098 #[derive(Copy)]
1099 struct SampleQuality {
1100 valid: bool,
1101 confidence: Option<f32>,
1102 }
1103
1104 struct Sample {
1105 distance_m: f32,
1106 limits: Option<Limits>,
1107 quality: Option<SampleQuality>,
1108 health: SensorHealth,
1109 }
1110
1111 topic sample: measurement Sample;
1112 }
1113
1114 gnss(capability) {
1115 /// A GNSS fix: geodetic position plus a 3x3 position covariance.
1116 struct Sample {
1117 latitude: f64,
1118 longitude: f64,
1119 altitude: f64,
1120 position_covariance: [f64; 9],
1121 }
1122
1123 topic sample: measurement Sample;
1124 }
1125
1126 camera(capability) {
1127 #[derive(Copy, Eq)]
1128 #[serde(rename_all = "snake_case")]
1129 enum Encoding {
1130 Jpeg,
1131 Png,
1132 L8,
1133 Rgb8,
1134 Rgba8,
1135 }
1136
1137 #[derive(Copy)]
1138 struct Intrinsics {
1139 fx: f32,
1140 fy: f32,
1141 cx: f32,
1142 cy: f32,
1143 }
1144
1145 struct Distortion {
1146 model: String,
1147 coefficients: Vec<f32>,
1148 }
1149
1150 #[derive(Copy)]
1151 struct ExposureTiming {
1152 exposure_start_ns: Option<u64>,
1153 exposure_duration_ns: Option<u64>,
1154 }
1155
1156 struct CalibrationIdentity {
1157 id: String,
1158 version: String,
1159 }
1160
1161 /// One camera frame: encoded pixel bytes plus optional calibration
1162 /// and timing metadata.
1163 struct Frame {
1164 width: u32,
1165 height: u32,
1166 encoding: Encoding,
1167 intrinsics: Option<Intrinsics>,
1168 distortion: Option<Distortion>,
1169 exposure: Option<ExposureTiming>,
1170 calibration: Option<CalibrationIdentity>,
1171 #[serde(with = "serde_bytes")]
1172 data: Vec<u8>,
1173 }
1174
1175 topic frame: measurement Frame;
1176 }
1177
1178 depth(capability) {
1179 #[derive(Copy, Eq)]
1180 #[serde(rename_all = "snake_case")]
1181 enum Encoding {
1182 U16Millimeters,
1183 }
1184
1185 #[derive(Copy, Eq)]
1186 #[serde(rename_all = "snake_case")]
1187 enum InvalidSamplePolicy {
1188 ZeroIsInvalid,
1189 NonFiniteIsInvalid,
1190 }
1191
1192 #[derive(Copy)]
1193 struct Intrinsics {
1194 fx: f32,
1195 fy: f32,
1196 cx: f32,
1197 cy: f32,
1198 }
1199
1200 struct Distortion {
1201 model: String,
1202 coefficients: Vec<f32>,
1203 }
1204
1205 #[derive(Copy)]
1206 struct ExposureTiming {
1207 exposure_start_ns: Option<u64>,
1208 exposure_duration_ns: Option<u64>,
1209 }
1210
1211 struct CalibrationIdentity {
1212 id: String,
1213 version: String,
1214 }
1215
1216 /// One depth frame: per-pixel millimetre samples plus optional
1217 /// calibration and timing metadata.
1218 struct Frame {
1219 samples_mm: Vec<u16>,
1220 encoding: Encoding,
1221 invalid_sample_policy: InvalidSamplePolicy,
1222 width: Option<u32>,
1223 height: Option<u32>,
1224 intrinsics: Option<Intrinsics>,
1225 distortion: Option<Distortion>,
1226 exposure: Option<ExposureTiming>,
1227 calibration: Option<CalibrationIdentity>,
1228 }
1229
1230 topic frame: measurement Frame;
1231 }
1232
1233 lidar(capability) {
1234 #[derive(Copy, Eq)]
1235 #[serde(rename_all = "snake_case")]
1236 enum SensorHealth {
1237 Nominal,
1238 Degraded,
1239 Fault,
1240 }
1241
1242 #[derive(Copy)]
1243 struct ScanGeometry {
1244 angle_min_rad: f32,
1245 angle_increment_rad: f32,
1246 }
1247
1248 #[derive(Copy)]
1249 struct RangeLimits {
1250 min_m: f32,
1251 max_m: f32,
1252 }
1253
1254 #[derive(Copy)]
1255 struct ScanQuality {
1256 valid_points: u32,
1257 }
1258
1259 struct Ranges {
1260 ranges: Vec<f32>,
1261 geometry: Option<ScanGeometry>,
1262 limits: Option<RangeLimits>,
1263 quality: Option<ScanQuality>,
1264 health: SensorHealth,
1265 }
1266
1267 struct Points {
1268 points: Vec<[f32; 3]>,
1269 limits: Option<RangeLimits>,
1270 quality: Option<ScanQuality>,
1271 health: SensorHealth,
1272 }
1273
1274 /// One lidar scan, either as polar ranges or as cartesian points.
1275 #[serde(tag = "kind", rename_all = "snake_case")]
1276 enum Scan {
1277 Ranges(Ranges),
1278 Points(Points),
1279 }
1280
1281 topic scan: measurement Scan;
1282 }
1283
1284 mmwave(capability) {
1285 /// One mmWave radar detection: position, velocity, and SNR.
1286 #[derive(Copy)]
1287 struct Detection {
1288 position: [f32; 3],
1289 velocity: [f32; 3],
1290 snr: f32,
1291 }
1292
1293 /// One mmWave radar scan as a set of detections.
1294 struct Scan {
1295 detections: Vec<Detection>,
1296 }
1297
1298 topic scan: measurement Scan;
1299 }
1300
1301 microphone(capability) {
1302 /// One audio frame as raw encoded bytes.
1303 struct Frame {
1304 data: Vec<u8>,
1305 }
1306
1307 topic frame: measurement Frame;
1308 }
1309
1310 led(capability) {
1311 /// A per-LED on/off command.
1312 #[derive(Copy, Eq)]
1313 enum Command {
1314 On,
1315 Off,
1316 }
1317
1318 topic command: command Command;
1319 }
1320
1321 speaker(capability) {
1322 /// One chunk of an audio stream to play on this speaker.
1323 ///
1324 /// `Some(bytes)` carries WAV-coded audio: the first chunk of a
1325 /// stream starts with the standard WAV header, later chunks
1326 /// continue its data. `None` ends the stream and is what tells
1327 /// the owner the sound is complete.
1328 struct Chunk {
1329 stream: Option<Vec<u8>>,
1330 }
1331
1332 topic stream: command Chunk;
1333 }
1334
1335 battery(capability) {
1336 /// Battery state reported by the pack's owner - the simulator
1337 /// backing this capability, or the real driver.
1338 struct State {
1339 voltage_v: f32,
1340 current_a: f32,
1341 charge_ratio: f32,
1342 }
1343
1344 topic state: state State;
1345 }
1346
1347 emergency_stop(capability) {
1348 /// Per-instance emergency-stop state.
1349 #[derive(Eq)]
1350 struct State {
1351 engaged: bool,
1352 }
1353
1354 topic state: state State;
1355 }
1356 }
1357
1358 odometry {
1359 /// A planar pose + twist estimate in the odometry frame.
1360 struct State {
1361 x_m: f64,
1362 y_m: f64,
1363 yaw_rad: f64,
1364 linear_x_mps: f32,
1365 angular_z_radps: f32,
1366 }
1367
1368 topic state: state State;
1369 }
1370
1371 localize {
1372 /// A planar localization estimate in the map frame.
1373 struct LocalizationState {
1374 x_m: f64,
1375 y_m: f64,
1376 yaw_rad: f64,
1377 confidence: f32,
1378 }
1379
1380 topic state: state LocalizationState;
1381 }
1382
1383 map {
1384 /// A published map revision marker.
1385 struct Revision {
1386 revision: u64,
1387 resolution_m: f32,
1388 }
1389
1390 /// Request a rectangular submap window (map-frame metres).
1391 struct SubmapRequest {
1392 min_x_m: f64,
1393 min_y_m: f64,
1394 max_x_m: f64,
1395 max_y_m: f64,
1396 }
1397
1398 /// An occupancy-grid window: row-major cells, 0..=100 + 255 = unknown.
1399 struct SubmapResponse {
1400 width: u32,
1401 height: u32,
1402 resolution_m: f32,
1403 cells: Vec<u8>,
1404 }
1405
1406 topic revision: state Revision;
1407 topic submap: query SubmapRequest => SubmapResponse;
1408 }
1409
1410 // Contracts the supervisor itself answers. The node is part of the
1411 // wire key, so a reader can tell from the key alone that the supervisor
1412 // is the authority - and a stale participant sitting on an old key
1413 // physically cannot answer one of these (organization#978).
1414 supervisor {
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;