Managed planning contract — robot-msg-irsl 0.5.4
================================================

This is a coordinated contract replacement: RobotAction's schema/binary layout
changes. No mixed-version compatibility, legacy decoder, or migration adapter is
provided. Envelope protocol 2 and binary magic R2 remain unchanged. RobotState,
model descriptors, model identity and unrelated messages do not change. Package
version and envelope protocol version are separate concepts.

0.5.4 adds the commanded-position start (see "Commanded-position start" below):
TrajectoryExecution.start_reference, PlanningJointLimits.start_step and
start_tracking, StateSnapshot ArmSample.q_des, and PlanningStatus
contract_version 4. Wire IDs are unchanged (they derive from msg_type). Every
new field is appended last with a new presence bit and its default/absence is
elided, so binary frames that do not use a new field keep their 0.5.3 bytes,
except that a valid 0.5.4 PlanningStatus always carries contract_version 4.
0.5.3 decoders reject every nondefault new field (unknown presence bit) and
every 0.5.4 PlanningStatus (version marker); 0.5.4 decoders reject 0.5.3
PlanningStatus. JSON always states defaulted fields, so 0.5.3 JSON decoders also
reject 0.5.4 TrajectoryExecution JSON even when start_reference is the default.

Python public API
-----------------

All types below are exported by robot_msg. TrajectoryExecution,
PlanningJointLimits, PlanningExecutionRecord and ArmSample are also in
robot_msg.types.
RobotAction and its nested action types are in
robot_msg.messages.switch_controller.robot_action. PlanningStatus is in
robot_msg.messages.switch_controller.planning_status.

Exact constructor fields, in constructor order (all accept keyword arguments):

TrajectoryExecution(
    operation: str, request_id: str, client_id: str, execution_id: str,
    session_id: str, model_id: str, controller_generation: int,
    admission_epoch: int, joint_names: list[str] | None = None,
    reference_dynamics_policy: str = 'enforce_reference',
    start_reference: str = 'measured_position')

PlanningJointLimits(
    name: str, lower: float, upper: float, velocity: float,
    acceleration: float, jerk: float, start_drift: float,
    start_velocity: float, hard_velocity: float | None = None,
    hard_velocity_source: str = '', start_step: float | None = None,
    start_tracking: float | None = None)

ArmSample(
    arm_id: str, availability: str, enabled: bool, has_state: bool,
    dq: list[float] | None = None, q: list[float] | None = None,
    sample_time: Timestamp | None = None, source_sequence: int | None = None,
    q_des: list[float] | None = None)

PlanningExecutionRecord(
    client_id: str, execution_id: str, request_id: str, operation: str,
    phase: str, reason: str, progress: float)

RobotActionTrajectoryAction(
    q_traj: list[list[float]] | None = None,
    ee_pose_traj: list[list[Pose]] | None = None,
    traj_duration: float = 2.0, interpolation: str = 'linear',
    segment_durations: list[float] | None = None,
    dq_traj: list[list[float]] | None = None,
    ddq_traj: list[list[float]] | None = None)

RobotAction(
    frame_id: str, real_time_action: RobotActionRealTimeAction | None = None,
    trajectory_action: RobotActionTrajectoryAction | None = None,
    trajectory_execution: TrajectoryExecution | None = None,
    *, metadata: MessageMetadata = <fresh default factory>)

PlanningStatus(
    session_id: str, model_id: str, sequence: int,
    controller_generation: int, admission_epoch: int, ready: bool,
    mode: int, blocked_reason: str, action_port: int, status_port: int,
    joint_names: list[str], units: list[str],
    joint_limits: list[PlanningJointLimits],
    contract_version: int = 0, max_waypoints: int = 2000,
    max_coordinates: int = 256, max_wire_bytes: int = 1048576,
    state_timeout_seconds: float = 0.25, lease_seconds: float = 2.0,
    admission_seconds: float = 1.0,
    records: list[PlanningExecutionRecord] = <fresh empty list>,
    response: PlanningExecutionRecord | None = None,
    reference_dynamics_override_supported: bool = False,
    *, metadata: MessageMetadata = <fresh default factory>)

PlanningStatus.MSG_TYPE = 'switch_controller.planning_status'
PlanningStatus.WIRE_ID = 4154214136 (0xf79c46f8)
RobotAction.MSG_TYPE = 'switch_controller.robot_action'
RobotAction.WIRE_ID = 3606767787 (0xd6fae8ab)

All classes are slotted dataclasses. Construction/assignment alone does not
validate: from_payload, to_payload, validate and both JSON/binary codecs enforce
field and cross-field constraints. Shared types expose from_payload/to_payload;
only messages have complete envelope encode/decode APIs. No generic JSON/dict
field is used inside the public typed contract.

Ports and identities
--------------------

robot_msg.ports.PLANNING_ACTION = 28502 carries RobotAction.
robot_msg.ports.PLANNING_STATUS = 28505 carries PlanningStatus.

operation = submit | status | cancel | heartbeat (strings in both languages).
request_id: 1..128 Unicode characters. client_id, execution_id, session_id:
exactly 32 lowercase ASCII hexadecimal characters. model_id: exactly 64 lowercase
ASCII hexadecimal characters. controller_generation, admission_epoch and
sequence: nonnegative signed int64. mode: signed int64. Python bool/float are not
integers. Number fields accept finite int/float values, not booleans.

Managed operations
------------------

Submit requires joint_names: 1..256 unique ordered strings, each 1..128
characters. Non-submit operations must omit joint_names entirely.

reference_dynamics_policy is exactly enforce_reference (default) or
override_reference. Only submit may use override_reference. The nondefault
selection occupies a new wire presence bit and enum byte; old decoders reject
it. Consent is per execution, immutable in preparation/request/payload digests,
not a global setting or an authentication mechanism. Explicit override waives
REFERENCE velocity/acceleration/jerk only, on both real and simulation backends.
Known physical velocity caps, continuous positions, numeric/C2/resource checks,
mode, source freshness, start drift/velocity, ownership/lease and all other
admission fences remain mandatory. Cancel/status/heartbeat always use default
enforce_reference, including when addressing an override execution.

Managed submit requires frame_id='world', no real_time_action, and a
trajectory_action containing q_traj only, with no ee_pose_traj even if empty.
interpolation must be 'quintic_stop_v1' or 'quintic_hermite_v1'. There are
2..2000 waypoints, with uniform
finite rows of 1..256 coordinates, exactly the joint_names length.
segment_durations is required: 1..1999 positive finite seconds, exactly one per
waypoint interval. Its finite sum must match positive finite numeric traj_duration
using abs(sum-duration) <= 1e-9 * max(abs(sum), abs(duration)); no absolute epsilon.
Legacy quintic_stop_v1 uses left-to-right IEEE-754 double accumulation, unchanged.
quintic_hermite_v1 uses Python math.fsum-compatible error-free partials and
half-even final rounding in C++. For each prefix end=fsum(h[:k+1]), with
previous=fsum(h[:k]) (initially 0), require end>previous AND
abs((end-previous)-h[k]) <= 1e-9*h[k], with no absolute epsilon. Otherwise reject
segment_duration_resolution: a positive but materially distorted cumulative
interval is not a valid physical Hermite interval. The semantic helpers and
controller preparation apply this same rule; no silent retiming is performed.
The canonical Hermite endpoint is the final cumulative sum, not a rescaling to
the asserted traj_duration.
traj_duration retains its numeric default 2.0. Omission is accepted when the
segment sum matches 2.0; there is no explicit-presence tracking. Both codecs may
elide numeric defaults and reconstruct the same value.

quintic_stop_v1 interpolates each interval using s(u)=10u^3-15u^4+6u^5, u in [0,1],
with zero velocity and acceleration at every original waypoint. q_traj contains
the original knots, not a pre-sampled controller stream. Segment durations are
seconds, not absolute timestamps.

quintic_hermite_v1 requires BOTH dq_traj and ddq_traj, each the exact q_traj
shape [knot][coordinate]. Values are finite physical rad/s or m/s and rad/s^2
or m/s^2 respectively, with exactly zero first/last rows. Shared internal
velocities/accelerations yield C2, not C3; one-sided jerk can jump. linear and
quintic_stop_v1 forbid tangent fields, including empty arrays.
For h=segment_durations[k], u=t/h, use ascending normalized coefficients:
c0=q0, c1=h*v0, c2=.5*h*h*a0, D=q1-c0-c1-c2,
V=h*v1-c1-2*c2, A=h*h*a1-2*c2,
c3=10*D-4*V+.5*A, c4=-15*D+7*V-A, c5=6*D-3*V+.5*A.
Evaluate with Horner; physical derivatives divide by h^r. Original knot q/dq/ddq
are exact at boundaries. Offgrid knots are permitted. Controllers prepare
immutable coefficients and cumulative boundaries outside real time and must
verify continuous interior position, known hard velocity and (unless explicitly
overridden) reference v/a/j bounds, not sample-grid finite
differences or the stop-mode maximum formula.

The semantic validator rejects a Hermite double-only payload lower bound above
1 MiB: 8*(3*knots*coordinates + segments + 1). This does not replace the actual
receiver frame cap and does not impose a global cap on unrelated/legacy codecs.

Status, cancel and heartbeat carry neither real_time_action nor trajectory_action.
Without trajectory_execution, prior independent motion branches and linear
trajectory semantics remain. Unmanaged actions cannot set segment_durations or
nonlinear interpolation. These retained unmanaged semantics do not imply old-wire
or mixed-version compatibility.

Status, correlation and ownership
---------------------------------

PlanningStatus is an independent message/channel, never a RobotState extension.
Its joint_names, units and joint_limits correspond positionally and have equal
length <=256. Names are unique strings of 1..128 characters and each limit.name
matches the corresponding joint name. Units are 'rad' or 'm'. Empty coordinate
arrays are permitted only when ready=False; unready status may also describe
known coordinates. Limits require finite lower < upper and positive finite
velocity, acceleration, jerk, start_drift and start_velocity. Optional
start_step and start_tracking are positive finite when present (see
"Commanded-position start"). The ordered units
determine coordinate/start-drift units; derivative limits use the corresponding
SI units per second, squared second and cubed second. Timings are positive finite
seconds. hard_velocity is an optional positive finite independently sourced
physical velocity bound, with nonempty hard_velocity_source exactly when present.
Sources are model, backend or model+backend (both supplied even if one is looser).
Neither field present means unknown, not unlimited and not safety-certified.
There are no invented hard acceleration/jerk values.
reference_dynamics_override_supported defaults false; supporting controllers
explicitly advertise true independently of backend or selected mode.
Ports are integers 1..65535. blocked_reason and record.reason are <=1024
characters, including empty strings. Progress is finite in [0,1].

Valid producers MUST explicitly assign contract_version=4 (robot-msg-irsl
0.5.4). The generated constructor default is deliberately INVALID sentinel 0,
not 4. The wire schema uses the finite non-singleton integer range 0..255 (one
actual value byte when present); semantic validation accepts exactly 4, so
0.5.3 status (3), 0.5.2 status (2) and any other value are rejected. A missing
marker decodes 0 and rejects, so old version-1/default-elided binary status
cannot masquerade as 4; 0.5.3 decoders likewise reject version 4. Version 4
advertises that the controller understands start_reference and the optional
start_step/start_tracking limits. This is fail-closed capability detection, not
a mixed-schema bridge.
max_waypoints=2000, max_coordinates=256 and max_wire_bytes=1048576 are fixed, not
negotiable knobs. max_wire_bytes advertises
receiver admission limits; this transport-independent codec does not reject
large otherwise-valid envelopes by transport frame size. Receivers must enforce
the 1 MiB cap before decoding/queuing input.

phase = accepted | running | completed | cancelled | rejected | interrupted.
records contains at most 32 latest submit execution records, unique by
(client_id, execution_id), with at most one accepted/running owner. Terminal
records do not own execution. Interrupted reasons should identify lease_expired,
preempted or failure; free-text failure diagnostics remain allowed.

response is an optional typed result correlated by request_id/client_id/
execution_id, for any operation. It does not overwrite execution ownership.
Non-submit results belong in response, not records. A successful status probe
normally responds with operation='status', phase='completed', progress=0.0.
This completed status response is not a completed robot trajectory.

operation='status' is a read-only handshake/correlated status request. The
controller MUST NOT acquire ownership, renew a lease, or consume admission for a
probe. Identity, generation and epoch fields remain mandatory syntactically but
are not admission requests. Before discovery, callers can send syntactically
valid sentinel hex identities; the controller returns current identity,
generation and epoch in PlanningStatus, with a correlated response. These
stateful controller obligations cannot be enforced by a standalone codec.

Commanded-position start (0.5.4)
--------------------------------

Background: the planner historically anchored every managed trajectory at the
measured position q, while the controller keeps holding its last commanded
target after an execution ends. Tracking error (gravity, gains) makes q differ
from that held target, so the first commanded sample of the next execution could
jump by more than one control tick allows (for example a real NERO backend
rejecting target_step_rad 0.02286 rad > 0.01581 rad = max_velocity*dt + 1e-4).
0.5.4 lets the controller publish its held reference and lets the planner anchor
the first knot either at that held reference (seamless) or at the measured q
(legacy).

ArmSample.q_des (StateSnapshot.arms[*]) is the controller's currently
held/commanded joint-position reference for that arm: the position it would
command on the next tick if no new action arrives. It uses exactly the same
coordinate order, units and length as ArmSample.q. It is never a measurement and
must never be fabricated from measurement. Presence follows the q/dq convention:
an optional field without a schema default (Python list[float] | None = None,
C++ robot_msg::optional<std::vector<double>>, JSON key omitted, never null; at
most 4096 finite values). Absent and present-but-empty both mean "no
joint-position reference available"; both codecs preserve which one was sent.
When nonempty, every value must be finite, has_state must be true and
len(q_des) must equal len(q). q_des is the last ArmSample field and uses a new
presence bit, so snapshots without q_des keep their 0.5.3 bytes and 0.5.3
decoders reject snapshots carrying it.

TrajectoryExecution.start_reference selects which position the trajectory's
first knot is anchored to: measured_position (default) or commanded_position.
It is modelled exactly like reference_dynamics_policy: the nondefault value
occupies a new presence bit and one enum byte, the default is elided on the
binary wire, and 0.5.3 decoders reject the nondefault value. Only
operation=submit may use commanded_position; status, cancel and heartbeat must
use the default measured_position. The codec does not compare positions.

PlanningJointLimits.start_step is an optional positive finite number: the
largest |first commanded trajectory sample - controller's held commanded
reference| the controller/backend accepts at trajectory start. It is a
per-control-tick command step in the coordinate's unit (rad or m). Absent means
the controller advertises no per-tick command-step limit for this coordinate;
start_drift still applies.
PlanningJointLimits.start_tracking is an optional positive finite number: the
largest |measured q - held commanded reference| accepted for a
commanded_position start. Absent means this controller does not support
commanded_position starts for this coordinate.
Both follow the hard_velocity pattern: absence is distinguishable from every
value (Python float | None = None, C++ robot_msg::optional<double>, JSON key
omitted, never null), each has its own appended presence bit, and they are
independent of each other and of hard_velocity/hard_velocity_source.

Admission semantics. The controller enforces these; the codec cannot. Notation
per submitted coordinate: k0 = first knot (q_traj[0]), m = measured q,
c = controller's held commanded reference at admission (the value it publishes
as ArmSample.q_des).

  Every start: if start_step is advertised, require |k0 - c| <= start_step,
  else reject with reason start_command_step. start_velocity on measured dq is
  unchanged.

  start_reference=measured_position: require |m - k0| <= start_drift, else
  reject with reason start_drift (existing behavior).

  start_reference=commanded_position: c must be available and start_tracking
  must be advertised for every submitted coordinate, else reject with reason
  commanded_start_unavailable (checked before any comparison involving c).
  Require |k0 - c| <= start_drift, else reject with reason start_drift. Require
  |m - c| <= start_tracking, else reject with reason start_tracking.

A planner choosing commanded_position anchors k0 at the published q_des. It can
only expect admission when PlanningStatus advertises start_tracking for every
submitted coordinate and the snapshot carries a nonempty q_des; the controller
rejects other commanded_position submits with commanded_start_unavailable.
Planner and controller both validate the first-tick step and start drift.

C++ public API
--------------

All types are in namespace robot_msg. Include <robot_msg/types.hpp> for the
shared types (TrajectoryExecution, PlanningJointLimits, PlanningExecutionRecord,
ArmSample), <robot_msg/messages/switch_controller/robot_action.hpp> for action
structs, and <robot_msg/messages/switch_controller/planning_status.hpp> for
PlanningStatus. <robot_msg/robot_msg.hpp> is the complete umbrella. Include
<robot_msg/ports.hpp> for robot_msg::ports::PLANNING_ACTION/PLANNING_STATUS.

Struct member names, order and defaults exactly mirror the Python constructors
above, except C++ uses aggregate/default construction, not required constructor
parameters. Strings/enums use std::string, integers std::int64_t, numbers double,
arrays std::vector<T>, and optional presence fields robot_msg::optional<T> (C++14
supported). In particular traj_duration is double = 2.0, NOT optional<double>.
Required fields default-construct to empty/zero/false; defaults are not evidence
of a valid message. metadata is MessageMetadata on both messages. records is an
empty vector by default and response is optional<PlanningExecutionRecord>.
0.5.4 members, each appended last: TrajectoryExecution::start_reference is
std::string = "measured_position"; PlanningJointLimits::start_step and
start_tracking are optional<double>; ArmSample::q_des is
optional<std::vector<double>>. PlanningStatus::contract_version stays
std::int64_t = 0 (invalid); producers assign 4. C++ ArmSample member order is
the schema field order (arm_id, availability, dq, enabled, has_state, q,
sample_time, source_sequence, q_des), not the Python constructor order.

robot_msg::validate, encode, encode_json, decode<T>, decode_json<T> and untyped
AnyMessage decode dispatch enforce the same schema/semantic constraints as
Python, including typed-object mutations before encoding. Shared types use the
generated detail codecs internally; there is no separate shared-type envelope.
