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

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,
StateSnapshot, model descriptors, model identity and unrelated messages do not
change. Package version and envelope protocol version are separate concepts.

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

All types below are exported by robot_msg. TrajectoryExecution,
PlanningJointLimits and PlanningExecutionRecord 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')

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 = '')

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. 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=3. The generated
constructor default is deliberately INVALID sentinel 0, not 3. The wire schema
uses the finite non-singleton integer range 0..255 (one actual value byte when
present); semantic validation accepts exactly 3. A missing marker decodes 0 and
rejects, so old version-1/default-elided binary status cannot masquerade as 3.
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.

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

All types are in namespace robot_msg. Include <robot_msg/types.hpp> for the three
shared types, <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>.

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.
