Skip to main content

nros/
node_metadata.rs

1//! Node source metadata recorded without opening middleware.
2
3use crate::{
4    ParameterType, ParameterValue, QoSProfile,
5    heapless::{String, Vec},
6};
7// phase-430 W4 — the ONE clock-source enum, from `nros_node::timer` (ungated:
8// see the note on its definition). The declarative layer records which clock a
9// declared timer wants and the runtime hands it to
10// `Executor::register_timer_entry`; a metadata-local copy of the enum here
11// would be the drift 0135/0160 measured one layer down.
12use nros_node::timer::TimerClockSource;
13
14#[cfg(feature = "alloc")]
15use crate::{QoSDurabilityPolicy, QoSHistoryPolicy, QoSLivelinessPolicy, QoSReliabilityPolicy};
16#[cfg(feature = "alloc")]
17// phase-359 W8 — `alloc`, not `std`. These three are the file's ONLY reason for
18// a gate, and `alloc::{format, string::String, vec::Vec}` are the same types.
19// Gating them as `std` did not just mislabel them, it WITHHELD the source
20// metadata JSON API from `no_std + alloc` targets that can run it.
21use alloc::{format, string::String as StdString, vec::Vec as StdVec};
22
23/// The source-metadata sidecar schema version this module emits.
24///
25/// `1 -> 2`. Version 2 is ADDITIVE over version 1 and every
26/// reader in the tree defaults the new fields, so a v1 sidecar still parses:
27///
28/// * every endpoint kind carries `qos` (v1: publishers and subscribers only);
29///   the value is the profile the runtime was handed AFTER overrides, which is
30///   what the executor sizes for;
31/// * a `timers[]` row carries `kind` -- `wall` / `clock` / `oneshot` /
32///   `in_group` -- and a guard condition is a row of that array with
33///   `kind: "guard_condition"`, so slot consumers that count the array keep
34///   counting one slot each while a census can tell the two apart;
35/// * a `parameters[]` row carries `type`.
36///
37/// `2 -> 3`, additive again, and every reader defaults the new
38/// field:
39///
40/// * a `subscribers[]` row may carry `in_place` -- whether THAT registration's
41///   delivery shape can dispatch out of the backend's own receive slot
42///   ([`EntityMetadata::in_place_capable`]). **An absent key is a refusal**, not
43///   a `false`: it is what a probe that declares without registering leaves
44///   behind, and a consumer that read it as `false` would state a registration
45///   path nobody observed.
46///
47/// Version 4 is additive again:
48///
49/// * a `subscribers[]` row may carry `buffered` -- `"typed_bound"` or
50///   `"unbounded"`, the BUFFERED row that registration claimed
51///   ([`EntityMetadata::buffered_row`]): whether its receive slot is a bound
52///   the call site stated or the closure buffer (`RX_BUF`). Written beside
53///   `in_place` by the same observation, and absent exactly when it is.
54///
55/// Version 5 is additive again:
56///
57/// * a `nodes[]` row may carry `"lifecycle": true` -- the node's OWN code
58///   registered a lifecycle state machine while the probe ran it
59///   ([`NodeMetadata::code_managed`]). Observed at the executor's lifecycle
60///   funnel, never declared. Absent means no registration was observed, and
61///   the node is plain, which is the run-time rule too.
62///
63/// Version 6 is additive again:
64///
65/// * top-level `"parameter_description_max_len": N` and
66///   `"parameter_constraints_max_len": N` -- the longest parameter
67///   `description` and `additional_constraints` the code set while the probe
68///   watched, in bytes, before any truncation; `0` for one it never set. They
69///   size `NROS_PARAMS_MAX_DESCRIPTION_BYTES` and
70///   `NROS_PARAMS_MAX_CONSTRAINTS_BYTES` respectively. **An absent key means
71///   nobody watched**, never `0`: a producer that cannot observe prose leaves
72///   both out, and a consumer must refuse to derive either knob from that
73///   sidecar rather than read it as "no text".
74///
75/// Version 7 is additive again:
76///
77/// * top-level `"parameter_declarations_watched": true | false` -- whether
78///   the `parameters` list is the node's WHOLE declaration set. `true` only
79///   when every declaration route the image links was observed, the recorder
80///   took every row, and no node opted into undeclared parameters. `false`
81///   when the probe watched and one of those failed. **An absent key means
82///   nobody watched**: a consumer may read an empty `parameters` list as "this
83///   node declares none" only beside `true`.
84///
85/// Serialised in exactly one place (this module), as the census layer rule
86/// requires: the adapters that feed the recorder contain no JSON.
87///
88/// A key or version change re-blesses the golden sidecar the CLI parses
89/// strictly: see `the_golden_probe_sidecar_is_what_the_recorder_writes`.
90// Issue 2689.
91pub const SOURCE_METADATA_SCHEMA_VERSION: u32 = 7;
92
93/// The BUFFERED registration row a subscription claimed, as the
94/// registration funnel observed it.
95///
96/// The two buffered rows of the sizing descriptor's `registration_path`
97/// (the third, `in_place`, is [`EntityMetadata::in_place_capable`]'s).
98/// Observed, never inferred from the entry's language: there is
99/// a C/C++ registration with no type hint that takes the closure buffer exactly
100/// like a Rust generic one.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum BufferedRow {
103    /// The receive slot is a bound the call site stated (its type's).
104    TypedBound,
105    /// The receive slot is the closure buffer, `RX_BUF`.
106    Unbounded,
107}
108
109impl BufferedRow {
110    /// The schema spelling, which is also the sizing descriptor's.
111    pub const fn as_str(self) -> &'static str {
112        match self {
113            Self::TypedBound => "typed_bound",
114            Self::Unbounded => "unbounded",
115        }
116    }
117}
118
119/// Maximum nodes recorded by the built-in metadata recorder WITHOUT `alloc`.
120/// With `alloc` the recorder grows; see [`MetadataRecorder`].
121pub const DEFAULT_MAX_METADATA_NODES: usize = 8;
122/// Maximum entities recorded by the built-in metadata recorder WITHOUT `alloc`.
123/// With `alloc` the recorder grows; see [`MetadataRecorder`].
124pub const DEFAULT_MAX_METADATA_ENTITIES: usize = 32;
125/// Maximum callback/effect records kept by the built-in metadata recorder
126/// WITHOUT `alloc`. With `alloc` the recorder grows; see [`MetadataRecorder`].
127pub const DEFAULT_MAX_METADATA_CALLBACKS: usize = 32;
128/// Maximum bytes in recorded source names and stable IDs.
129pub const METADATA_STRING_CAPACITY: usize = 128;
130
131/// Fixed-capacity string used by component metadata records.
132pub type MetadataString = String<METADATA_STRING_CAPACITY>;
133
134/// Declaration-order node slot within one extracted component.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136pub struct NodeSlot(pub usize);
137
138impl NodeSlot {
139    /// Create a node slot from its declaration-order index.
140    pub const fn new(index: usize) -> Self {
141        Self(index)
142    }
143
144    /// Declaration-order index.
145    pub const fn index(self) -> usize {
146        self.0
147    }
148}
149
150/// Declaration-order entity slot within one extracted component.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152pub struct EntitySlot(pub usize);
153
154impl EntitySlot {
155    /// Create an entity slot from its declaration-order index.
156    pub const fn new(index: usize) -> Self {
157        Self(index)
158    }
159
160    /// Declaration-order index.
161    pub const fn index(self) -> usize {
162        self.0
163    }
164}
165
166/// Declaration-order callback slot within one extracted component.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
168pub struct CallbackSlot(pub usize);
169
170impl CallbackSlot {
171    /// Create a callback slot from its declaration-order index.
172    pub const fn new(index: usize) -> Self {
173        Self(index)
174    }
175
176    /// Declaration-order index.
177    pub const fn index(self) -> usize {
178        self.0
179    }
180}
181
182/// Source location attached to callbacks and parameters.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct SourceLocationMetadata {
185    pub artifact: MetadataString,
186    pub line: Option<u32>,
187    pub column: Option<u32>,
188}
189
190impl SourceLocationMetadata {
191    /// Empty source location used when caller data is unavailable.
192    pub const fn empty() -> Self {
193        Self {
194            artifact: MetadataString::new(),
195            line: None,
196            column: None,
197        }
198    }
199
200    /// Capture the Rust caller location.
201    #[track_caller]
202    pub fn caller() -> Result<Self, NodeMetadataError> {
203        let location = core::panic::Location::caller();
204        Ok(Self {
205            // issue 0699 — keep the TAIL, never fail on depth.
206            //
207            // rustc emits `Location::file()` ABSOLUTE whenever the recording
208            // crate is compiled as a path dependency from another directory,
209            // which is exactly how the metadata harness builds it. So this
210            // field carries the user's home directory, and a workspace nested
211            // ~100 chars deep overflowed the 128-byte buffer — `nros sync`
212            // failed with `Metadata(NameTooLong)` for no reason but where the
213            // user keeps their files.
214            //
215            // Truncating the FRONT is safe precisely here: the CLI's
216            // `metadata_build.rs` already rewrites this to be relative to the
217            // component package afterwards, so the prefix is discarded either
218            // way and the tail is the part that survives. A path is also
219            // diagnostic metadata — losing its head degrades a message,
220            // whereas erroring loses the whole register.
221            artifact: copy_str_keep_tail(location.file())?,
222            line: Some(location.line()),
223            column: Some(location.column()),
224        })
225    }
226}
227
228/// Parameter default value recorded for source metadata.
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum ParameterDefault {
231    Bool(bool),
232    Integer(i64),
233    Double(MetadataString),
234    String(MetadataString),
235    BoolArray,
236    IntegerArray,
237    DoubleArray,
238    StringArray,
239}
240
241impl ParameterDefault {
242    /// Parameter type implied by this default.
243    pub const fn parameter_type(&self) -> ParameterType {
244        match self {
245            Self::Bool(_) => ParameterType::Bool,
246            Self::Integer(_) => ParameterType::Integer,
247            Self::Double(_) => ParameterType::Double,
248            Self::String(_) => ParameterType::String,
249            Self::BoolArray => ParameterType::BoolArray,
250            Self::IntegerArray => ParameterType::IntegerArray,
251            Self::DoubleArray => ParameterType::DoubleArray,
252            Self::StringArray => ParameterType::StringArray,
253        }
254    }
255
256    /// The default a C/C++ node passed to
257    /// `declare_parameter`, as the recorder stores it.
258    ///
259    /// The ONE conversion from a runtime [`ParameterValue`] to the recorded
260    /// shape, so the parameter hook in `nros-cpp` carries a value across and
261    /// formats nothing. Array defaults record their KIND and not their
262    /// elements, which is what the sidecar has always emitted for them.
263    pub fn from_value(value: &ParameterValue) -> Result<Self, NodeMetadataError> {
264        use core::fmt::Write as _;
265        Ok(match value {
266            ParameterValue::Bool(v) => Self::Bool(*v),
267            ParameterValue::Integer(v) => Self::Integer(*v),
268            ParameterValue::Double(v) => {
269                let mut text = MetadataString::new();
270                write!(text, "{v:?}").map_err(|_| NodeMetadataError::NameTooLong)?;
271                Self::Double(text)
272            }
273            ParameterValue::String(v) => Self::String(copy_str(v.as_str())?),
274            ParameterValue::BoolArray(_) => Self::BoolArray,
275            ParameterValue::IntegerArray(_) => Self::IntegerArray,
276            ParameterValue::DoubleArray(_) => Self::DoubleArray,
277            ParameterValue::StringArray(_) => Self::StringArray,
278            ParameterValue::ByteArray(_) | ParameterValue::NotSet => Self::Integer(0),
279        })
280    }
281
282    /// Default JSON-compatible value for a parameter type.
283    pub fn for_type(param_type: ParameterType) -> Result<Self, NodeMetadataError> {
284        Ok(match param_type {
285            ParameterType::Bool => Self::Bool(false),
286            ParameterType::Integer => Self::Integer(0),
287            ParameterType::Double => Self::Double(copy_str("0.0")?),
288            ParameterType::String => Self::String(copy_str("")?),
289            ParameterType::BoolArray => Self::BoolArray,
290            ParameterType::IntegerArray => Self::IntegerArray,
291            ParameterType::DoubleArray => Self::DoubleArray,
292            ParameterType::StringArray => Self::StringArray,
293            ParameterType::ByteArray | ParameterType::NotSet => Self::Integer(0),
294        })
295    }
296}
297
298/// Unresolved ROS name category as written by component source.
299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300pub enum SourceNameKind {
301    /// Starts with `/`.
302    Absolute,
303    /// Starts with `~`.
304    Private,
305    /// Any other non-empty source name.
306    Relative,
307}
308
309impl SourceNameKind {
310    /// Classify a source name without resolving launch remaps or namespaces.
311    pub const fn from_source_name(name: &str) -> Self {
312        let bytes = name.as_bytes();
313        if bytes.is_empty() {
314            Self::Relative
315        } else if bytes[0] == b'/' {
316            Self::Absolute
317        } else if bytes[0] == b'~' {
318            Self::Private
319        } else {
320            Self::Relative
321        }
322    }
323}
324
325/// The ONE name-resolution seam: ROS 2 source-name
326/// expansion (`~`/relative → FQN, ns=`/` collapse) + launch remap substitution
327/// (exact-FQN match, first rule wins; no wildcards). Implemented in
328/// `nros_node::names` so both the Rust `ExecutorSink` and the C-ABI
329/// executor-side remap table share one lowering; re-exported here next to
330/// [`SourceNameKind`] as the source-metadata-level entry point.
331pub use nros_node::names::{
332    MAX_RESOLVED_NAME_LEN, ResolvedName, expand_name, fully_qualified_name, resolve_name,
333};
334
335/// Stable source-level identifier required for component-mode declarations.
336#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
337pub struct EntityId<'a>(pub &'a str);
338
339impl<'a> EntityId<'a> {
340    /// Create a stable entity identifier.
341    pub const fn new(id: &'a str) -> Self {
342        Self(id)
343    }
344
345    /// Borrow the identifier string.
346    pub const fn as_str(self) -> &'a str {
347        self.0
348    }
349}
350
351/// Stable node identifier required for component-mode node declarations.
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
353pub struct NodeId<'a>(pub &'a str);
354
355impl<'a> NodeId<'a> {
356    /// Create a stable node identifier.
357    pub const fn new(id: &'a str) -> Self {
358        Self(id)
359    }
360
361    /// Borrow the identifier string.
362    pub const fn as_str(self) -> &'a str {
363        self.0
364    }
365}
366
367/// Stable callback identifier required for component-mode callbacks.
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
369pub struct CallbackId<'a>(pub &'a str);
370
371impl<'a> CallbackId<'a> {
372    /// Create a stable callback identifier.
373    pub const fn new(id: &'a str) -> Self {
374        Self(id)
375    }
376
377    /// Borrow the identifier string.
378    pub const fn as_str(self) -> &'a str {
379        self.0
380    }
381}
382
383/// Entity role recorded for source metadata.
384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385pub enum EntityKind {
386    Publisher,
387    Subscription,
388    Timer,
389    ServiceServer,
390    ServiceClient,
391    ActionServer,
392    ActionClient,
393    Parameter,
394}
395
396/// Which executor-side entry a recorded slot row came through.
397///
398/// `nros_cpp_timer_create` / `_on_clock` / `_oneshot` / `_in_group` are four
399/// entry points with four semantics (a oneshot fires once; a clock timer follows
400/// `/clock`), and a contract that says `rate_hz` means a repeating wall timer.
401/// The recorder used to fold all four into one `period_ms`, so a census could
402/// not see that a "timer" was a one-shot delay -- or that it was a guard
403/// condition at all, which the C++ hooks recorded as a timer of period 0.
404///
405/// A guard condition is [`GuardCondition`](Self::GuardCondition) here rather
406/// than a variant of [`EntityKind`], on purpose: it occupies one callback slot
407/// exactly like a timer, every sizing consumer counts the `timers[]` array,
408/// and the runtime's declarative path matches on `EntityKind` exhaustively.
409/// The KIND is what a census reads; the slot is what sizing reads; neither
410/// changes for the other. Meaningful only for [`EntityKind::Timer`]; `Wall`
411/// for every timer declared through the Rust producer, which has no oneshot,
412/// group or guard entry.
413#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
414pub enum TimerKind {
415    /// A repeating timer on the platform steady clock.
416    #[default]
417    Wall,
418    /// A repeating timer driven by a caller-supplied clock (`create_timer(node, clock, ...)`).
419    Clock,
420    /// A timer that fires once after its delay.
421    Oneshot,
422    /// A repeating wall timer registered into a named callback group.
423    InGroup,
424    /// A guard condition: one callback slot, no period.
425    GuardCondition,
426}
427
428/// Optional callback effect relation.
429#[derive(Debug, Clone, Copy, PartialEq, Eq)]
430pub enum CallbackEffectKind {
431    Reads,
432    Publishes,
433    Writes,
434}
435
436/// Metadata recorder/runtime error.
437#[derive(Debug, Clone, Copy, PartialEq, Eq)]
438pub enum NodeMetadataError {
439    /// Fixed recorder capacity exhausted.
440    Capacity,
441    /// Stable ID, node name, namespace, topic, service, action, or parameter name was too long.
442    NameTooLong,
443    /// Entity references a node ID that has not been declared.
444    UnknownNode,
445    /// Callback effect references an entity ID that has not been declared.
446    UnknownEntity,
447    /// Stable ID already exists in the same component metadata.
448    DuplicateId,
449}
450
451/// Recorded node declaration.
452#[derive(Debug, Clone, PartialEq, Eq)]
453pub struct NodeMetadata {
454    pub slot: NodeSlot,
455    pub id: MetadataString,
456    pub source_default_name: MetadataString,
457    pub name: MetadataString,
458    pub namespace: MetadataString,
459    pub domain_id: u32,
460    /// Did this node's OWN code register a
461    /// lifecycle state machine while the probe ran it?
462    ///
463    /// Set only by [`MetadataRecorder::observe_lifecycle_registration`], i.e.
464    /// by the executor's lifecycle funnel, never by an adapter declaring it.
465    /// `false` is "no registration was observed", which is exactly the run-time
466    /// rule: a node with no machine is plain.
467    pub code_managed: bool,
468}
469
470/// Recorded entity declaration.
471#[derive(Debug, Clone, PartialEq, Eq)]
472pub struct EntityMetadata {
473    pub slot: Option<EntitySlot>,
474    pub id: MetadataString,
475    pub node_slot: Option<NodeSlot>,
476    pub node_id: MetadataString,
477    pub kind: EntityKind,
478    pub source_name: MetadataString,
479    pub source_name_kind: SourceNameKind,
480    pub type_name: &'static str,
481    pub type_hash: &'static str,
482    /// The hash each endpoint of an ACTION entity is keyed on
483    /// (`None` for every other kind). Set by the typed declarations in
484    /// `node.rs`, which know `A`; the runtime replays it into the raw spec.
485    /// Not emitted in the metadata JSON.
486    pub action_hashes: Option<nros_node::ActionEndpointHashes<'static>>,
487    pub qos: QoSProfile,
488    pub callback_slot: Option<CallbackSlot>,
489    pub callback_id: Option<MetadataString>,
490    pub callback_source: SourceLocationMetadata,
491    pub callback_group: Option<MetadataString>,
492    pub action_cancel_callback_slot: Option<CallbackSlot>,
493    pub action_cancel_callback_id: Option<MetadataString>,
494    pub action_cancel_source: SourceLocationMetadata,
495    pub action_accepted_callback_slot: Option<CallbackSlot>,
496    pub action_accepted_callback_id: Option<MetadataString>,
497    pub action_accepted_source: SourceLocationMetadata,
498    pub period_ms: Option<u64>,
499    /// The timer period at the executor's own resolution.
500    /// `period_ms` is kept (and still emitted) for consumers of the
501    /// metadata JSON, but it truncates: a declared 33.333 ms timer used
502    /// to reach the runtime as 33 ms, a 1% permanent rate error, and a
503    /// sub-millisecond period reached it as zero.
504    pub period_us: Option<u64>,
505    /// Which clock advances this timer. `Steady` — the default
506    /// and every timer declared before W4 — is the WALL case: the runtime
507    /// registers it exactly as it always did. `Ros` makes the timer follow
508    /// `/clock`, so a `nros::main!` component can own a simulated-time timer
509    /// without reaching for the executor.
510    ///
511    /// Meaningless for every other entity kind, and deliberately NOT emitted in
512    /// the metadata JSON: the runtime reads this struct directly from the
513    /// component's `declare()`, so the sidecar schema does not have to move for
514    /// the capability to work.
515    pub timer_clock: TimerClockSource,
516    /// Whether the declared timer starts ARMED (`true`, the
517    /// default and every timer declared before 2038) or is registered
518    /// cancelled (`false`, rcl's `rcl_timer_init2(..., autostart = false)`),
519    /// firing only once something resets it. Read by the runtime with
520    /// `timer_clock`, and like it not emitted in the metadata JSON.
521    ///
522    /// Meaningless for every other entity kind.
523    pub timer_autostart: bool,
524    /// The ABI entry the timer came through (see [`TimerKind`]).
525    /// Emitted as `kind` on the timer row; `Wall` for every other entity kind.
526    pub timer_kind: TimerKind,
527    pub parameter_type: Option<ParameterType>,
528    pub parameter_default: Option<ParameterDefault>,
529    pub parameter_read_only: bool,
530    // Issue 2589.
531    /// A parameter row the code READ (`NodeContext::param`, a
532    /// launch value looked up by name) rather than declared. It has no type
533    /// and no default, and is emitted as `"read": true`.
534    pub parameter_read: bool,
535    /// A subscription that opted into E2E message-integrity
536    /// validation (`.safety()`): the runtime registers it via
537    /// `create_generic_subscription_with_integrity` and surfaces
538    /// [`IntegrityStatus`](crate::IntegrityStatus) through `CallbackCtx::integrity()`.
539    /// Ungated (a plain flag) — only the runtime branch that reads it is gated on
540    /// `safety-e2e`, so when the capability is off the flag is simply ignored
541    /// (the subscription registers as a basic one). `false` for every other entity.
542    pub safety: bool,
543    /// A subscription that asked for the message's metadata
544    /// (`create_subscription_for_callback_name_with_message_info`): the
545    /// runtime registers it on the info path and surfaces
546    /// [`MessageInfo`](crate::MessageInfo) through
547    /// `CallbackCtx::message_info()`. `false` for every other entity.
548    pub message_info: bool,
549    /// Can THIS subscription's registration dispatch out of the
550    /// backend's own receive slot?
551    ///
552    /// The CALL SITE's half of a subscription's `registration_path`,
553    /// reported by
554    /// `nros_node::executor::registration_observer` from
555    /// `Executor::open_subscription` — the one site in the tree that reads it.
556    /// **Not** conjoined with the backend's own answer: a probe links the
557    /// RECORDING backend, so the conjunction would describe the probe rather
558    /// than the image, and the consumer knows the shipped backend from the
559    /// image's `rmw` name.
560    ///
561    /// `None` is **"nobody observed this"** and is a REFUSAL at every consumer,
562    /// never a `false`. It is the state of every row on a road whose probe
563    /// declares without registering — the Rust producer runs `register()`
564    /// against a recording `NodeContext` and opens no executor — and of every
565    /// non-subscription row, which claims no receive slot at all.
566    pub in_place_capable: Option<bool>,
567    /// The BUFFERED row the registration claimed. Set by the
568    /// same observation as [`Self::in_place_capable`], so the two are present
569    /// together or not at all; `None` is "nobody observed this".
570    pub buffered_row: Option<BufferedRow>,
571    /// The subscription's message-type bound
572    /// (`RosMessage::MAX_SERIALIZED_BOUND`), recorded where the type is
573    /// known so the type-erased registration can still hand the backend its
574    /// `rx_buffer_hint`. The typed executor path passes the same number
575    /// (`rmw_type_registry::subscription_rx_hint`). `None` for an unbounded
576    /// type and for every other entity kind: "stated nothing", never zero.
577    pub rx_bound: Option<usize>,
578    pub source: SourceLocationMetadata,
579}
580
581impl EntityMetadata {
582    /// Which registration entry point this
583    /// DECLARED subscription will reach.
584    ///
585    /// **THE classifier**, in the sense
586    /// [`DeclaredSubscriptionShape`](nros_node::executor::declared_shape::DeclaredSubscriptionShape)'s
587    /// module docs give it: the declarative registrar
588    /// (`node_runtime`'s `EntityKind::Subscription` arm) dispatches on this
589    /// answer, and the metadata recorder states
590    /// [`in_place_capable`](Self::in_place_capable) from the same answer. Two
591    /// readers of one function is not a second opinion; two functions would
592    /// be, which is the drift removed from the CLI.
593    ///
594    /// The `safety-e2e` mask lives HERE and nowhere else. With the capability
595    /// off the runtime ignores [`safety`](Self::safety) and registers the
596    /// basic path (see that field's doc), so a probe built the same way must
597    /// say the same thing — and a second `#[cfg]` at either reader is the
598    /// disagreement this function exists to prevent.
599    ///
600    /// Meaningful only for [`EntityKind::Subscription`]; no other kind reaches
601    /// a subscription entry point, and no caller asks.
602    pub fn declared_subscription_shape(
603        &self,
604    ) -> nros_node::executor::declared_shape::DeclaredSubscriptionShape {
605        #[cfg(feature = "safety-e2e")]
606        let safety = self.safety;
607        #[cfg(not(feature = "safety-e2e"))]
608        let safety = false;
609        nros_node::executor::declared_shape::DeclaredSubscriptionShape::of_declaration(
610            safety,
611            self.message_info,
612        )
613    }
614}
615
616/// Recorded optional callback effect.
617#[derive(Debug, Clone, PartialEq, Eq)]
618pub struct CallbackEffectMetadata {
619    pub callback_id: MetadataString,
620    pub callback_slot: Option<CallbackSlot>,
621    pub kind: CallbackEffectKind,
622    pub entity_id: MetadataString,
623    pub entity_slot: Option<EntitySlot>,
624}
625
626/// Source metadata document settings used by the std JSON emitter.
627#[cfg(feature = "alloc")]
628#[derive(Debug, Clone)]
629pub struct SourceMetadataExport<'a> {
630    pub package: &'a str,
631    pub component: &'a str,
632    pub executable: Option<&'a str>,
633    pub exported_symbol: Option<&'a str>,
634    pub package_manifest: &'a str,
635    pub source_artifacts: &'a [&'a str],
636    /// The source language the sidecar describes (`"rust"`,
637    /// `"c"`, `"cpp"`). It was a hardcoded `"rust"` literal in the serializer
638    /// while Rust was the only producer; the C/C++ producer reaches this SAME
639    /// serializer, so the value has to come from the caller. The consumption
640    /// side keys on `(package, executable)` and never branches on it, but the
641    /// schema declares it and a wrong value is a lie in the artifact.
642    pub language: &'a str,
643}
644
645#[cfg(feature = "alloc")]
646impl<'a> SourceMetadataExport<'a> {
647    /// Create export settings with ROS package and component names.
648    pub const fn new(package: &'a str, component: &'a str) -> Self {
649        Self {
650            package,
651            component,
652            executable: None,
653            exported_symbol: None,
654            package_manifest: "package.xml",
655            source_artifacts: &[],
656            language: "rust",
657        }
658    }
659
660    /// Set the source language (`"c"` / `"cpp"`; defaults to `"rust"`).
661    pub const fn language(mut self, language: &'a str) -> Self {
662        self.language = language;
663        self
664    }
665
666    /// Set executable name.
667    pub const fn executable(mut self, executable: &'a str) -> Self {
668        self.executable = Some(executable);
669        self
670    }
671
672    /// Set exported symbol name.
673    pub const fn exported_symbol(mut self, exported_symbol: &'a str) -> Self {
674        self.exported_symbol = Some(exported_symbol);
675        self
676    }
677
678    /// Set package manifest path.
679    pub const fn package_manifest(mut self, package_manifest: &'a str) -> Self {
680        self.package_manifest = package_manifest;
681        self
682    }
683
684    /// Set source artifact paths.
685    pub const fn source_artifacts(mut self, source_artifacts: &'a [&'a str]) -> Self {
686        self.source_artifacts = source_artifacts;
687        self
688    }
689}
690
691/// `pub` for metadata-mode adapters (see
692/// [`MetadataRecorder::push_node`]); the capacity error is theirs to surface.
693pub fn metadata_string(value: &str) -> Result<MetadataString, NodeMetadataError> {
694    copy_str(value)
695}
696
697/// `copy_str`, but for a value whose TAIL is the informative end — a source
698/// path. Keeps the last whole path components that fit, marked with a leading
699/// `…/` so a reader can tell it was cut.
700///
701/// Issue 0699: the only caller is `SourceLocation::caller()`, whose input is
702/// `core::panic::Location::file()`. That is an absolute path in the metadata
703/// harness, so its length is set by where the USER put the workspace — not by
704/// anything this tree controls, and not something a fixed buffer can bound.
705pub(crate) fn copy_str_keep_tail(value: &str) -> Result<MetadataString, NodeMetadataError> {
706    if value.len() <= METADATA_STRING_CAPACITY {
707        return copy_str(value);
708    }
709    // Room for the marker, then the longest component-aligned tail that fits.
710    const MARK: &str = "…/";
711    let budget = METADATA_STRING_CAPACITY - MARK.len();
712    let tail = value
713        .char_indices()
714        .find(|(i, _)| value.len() - i <= budget)
715        .map(|(i, _)| &value[i..])
716        .unwrap_or("");
717    // Prefer a component boundary so the result reads as a path.
718    let tail = match tail.find('/') {
719        Some(cut) => &tail[cut + 1..],
720        None => tail,
721    };
722    let mut out = MetadataString::new();
723    out.push_str(MARK)
724        .map_err(|_| NodeMetadataError::NameTooLong)?;
725    out.push_str(tail)
726        .map_err(|_| NodeMetadataError::NameTooLong)?;
727    Ok(out)
728}
729
730pub(crate) fn copy_str(value: &str) -> Result<MetadataString, NodeMetadataError> {
731    let mut out = MetadataString::new();
732    out.push_str(value)
733        .map_err(|_| NodeMetadataError::NameTooLong)?;
734    Ok(out)
735}
736
737/// The rows of a [`MetadataRecorder`] (issue 2166).
738///
739/// With `alloc` they GROW: every producer of source metadata is a host
740/// process (the C/C++ metadata probe, the Rust metadata binary), and a real
741/// component declares far more than a fixed default holds. Autoware's
742/// trajectory follower declares 149 parameters, and each one is an entity
743/// row, so a 32-row recorder made the probe panic and `nros configure`
744/// report `no producer`. Without `alloc` they are a `heapless::Vec<T, N>`, and
745/// `N` is the recorder's const parameter, as before.
746#[derive(Debug)]
747pub(crate) struct Rows<T, const N: usize> {
748    #[cfg(feature = "alloc")]
749    inner: alloc::vec::Vec<T>,
750    #[cfg(not(feature = "alloc"))]
751    inner: Vec<T, N>,
752}
753
754impl<T, const N: usize> Rows<T, N> {
755    pub(crate) const fn new() -> Self {
756        Self {
757            #[cfg(feature = "alloc")]
758            inner: alloc::vec::Vec::new(),
759            #[cfg(not(feature = "alloc"))]
760            inner: Vec::new(),
761        }
762    }
763
764    /// Append a row. `Err` only without `alloc`, when the fixed capacity `N`
765    /// is spent.
766    pub(crate) fn push(&mut self, value: T) -> Result<(), T> {
767        #[cfg(feature = "alloc")]
768        {
769            self.inner.push(value);
770            Ok(())
771        }
772        #[cfg(not(feature = "alloc"))]
773        {
774            self.inner.push(value)
775        }
776    }
777}
778
779impl<T, const N: usize> core::ops::Deref for Rows<T, N> {
780    type Target = [T];
781    fn deref(&self) -> &[T] {
782        &self.inner
783    }
784}
785
786impl<'a, T, const N: usize> IntoIterator for &'a Rows<T, N> {
787    type Item = &'a T;
788    type IntoIter = core::slice::Iter<'a, T>;
789    fn into_iter(self) -> Self::IntoIter {
790        self.iter()
791    }
792}
793
794impl<T, const N: usize> core::ops::DerefMut for Rows<T, N> {
795    fn deref_mut(&mut self) -> &mut [T] {
796        &mut self.inner
797    }
798}
799
800/// In-memory metadata sink used by host discovery. It never opens transport.
801///
802/// With `alloc` (every host producer) it records any number of nodes,
803/// entities and callback effects, and the const parameters are unused. Without
804/// `alloc` they are fixed capacities, and a full recorder refuses with
805/// [`NodeMetadataError::Capacity`].
806#[derive(Debug)]
807pub struct MetadataRecorder<
808    const MAX_NODES: usize = DEFAULT_MAX_METADATA_NODES,
809    const MAX_ENTITIES: usize = DEFAULT_MAX_METADATA_ENTITIES,
810    const MAX_CALLBACKS: usize = DEFAULT_MAX_METADATA_CALLBACKS,
811> {
812    nodes: Rows<NodeMetadata, MAX_NODES>,
813    entities: Rows<EntityMetadata, MAX_ENTITIES>,
814    callback_effects: Rows<CallbackEffectMetadata, MAX_CALLBACKS>,
815    /// The longest parameter `description` the code set while the probe
816    /// watched, in bytes. `None` when nothing watched (no observer was armed),
817    /// which is not the same fact as `Some(0)`: a probe that watched and saw
818    /// no text. Serialised only when `Some` (schema v6).
819    description_max_len: Option<usize>,
820    /// The same for `additional_constraints`, which has its own knob.
821    constraints_max_len: Option<usize>,
822    // Issue 2964.
823    /// Whether `parameters` is the whole declaration set. `None` when nothing
824    /// watched; `Some(false)` when the watch was broken (a refused row, or a
825    /// node that opted into undeclared parameters). Serialised only when
826    /// `Some` (schema v7).
827    parameter_declarations_watched: Option<bool>,
828}
829
830impl<const MAX_NODES: usize, const MAX_ENTITIES: usize, const MAX_CALLBACKS: usize> Default
831    for MetadataRecorder<MAX_NODES, MAX_ENTITIES, MAX_CALLBACKS>
832{
833    fn default() -> Self {
834        Self::new()
835    }
836}
837
838impl<const MAX_NODES: usize, const MAX_ENTITIES: usize, const MAX_CALLBACKS: usize>
839    MetadataRecorder<MAX_NODES, MAX_ENTITIES, MAX_CALLBACKS>
840{
841    /// Create an empty metadata recorder.
842    pub const fn new() -> Self {
843        Self {
844            nodes: Rows::new(),
845            entities: Rows::new(),
846            callback_effects: Rows::new(),
847            description_max_len: None,
848            constraints_max_len: None,
849            parameter_declarations_watched: None,
850        }
851    }
852
853    // Issue 2964.
854    /// Start watching parameter declarations: from now on the sidecar states
855    /// whether its `parameters` list is complete. Idempotent; a broken watch
856    /// stays broken.
857    pub fn arm_parameter_declarations(&mut self) {
858        self.parameter_declarations_watched.get_or_insert(true);
859    }
860
861    /// The `parameters` list can no longer be the whole declaration set: a
862    /// row was refused, or a node opted into undeclared parameters. Ignored
863    /// unless the watch is armed, since an unwatched recorder says nothing.
864    pub fn break_parameter_declarations(&mut self) {
865        if let Some(watched) = self.parameter_declarations_watched.as_mut() {
866            *watched = false;
867        }
868    }
869
870    /// `Some(true)` when the recorded parameters are the whole declaration
871    /// set, `Some(false)` when the watch broke, `None` when nothing watched.
872    pub fn parameter_declarations_watched(&self) -> Option<bool> {
873        self.parameter_declarations_watched
874    }
875
876    /// Start watching descriptor prose: from now on the sidecar states the
877    /// longest description and constraints text seen, `0` for one never set.
878    /// Idempotent; keeps what was seen.
879    pub fn arm_descriptor_text(&mut self) {
880        self.description_max_len.get_or_insert(0);
881        self.constraints_max_len.get_or_insert(0);
882    }
883
884    /// The code set a `description` (`constraints == false`) or an
885    /// `additional_constraints` text of `len` bytes. Ignored unless
886    /// [`arm_descriptor_text`](Self::arm_descriptor_text) ran: an unarmed
887    /// recorder states nothing about prose.
888    pub fn observe_descriptor_text(&mut self, constraints: bool, len: usize) {
889        let slot = if constraints {
890            &mut self.constraints_max_len
891        } else {
892            &mut self.description_max_len
893        };
894        if let Some(max) = slot.as_mut() {
895            *max = (*max).max(len);
896        }
897    }
898
899    /// The longest `description` seen, or `None` when nothing watched.
900    pub fn description_max_len(&self) -> Option<usize> {
901        self.description_max_len
902    }
903
904    /// The longest `additional_constraints` seen, or `None` when nothing
905    /// watched.
906    pub fn constraints_max_len(&self) -> Option<usize> {
907        self.constraints_max_len
908    }
909
910    /// Recorded nodes in declaration order.
911    pub fn nodes(&self) -> &[NodeMetadata] {
912        &self.nodes
913    }
914
915    /// Recorded entities in declaration order.
916    pub fn entities(&self) -> &[EntityMetadata] {
917        &self.entities
918    }
919
920    /// Recorded optional callback effects in declaration order.
921    pub fn callback_effects(&self) -> &[CallbackEffectMetadata] {
922        &self.callback_effects
923    }
924
925    /// Attach an OBSERVED registration fact to the subscription
926    /// row that registered it.
927    ///
928    /// A subscription is recorded when the backend creates it and observed when
929    /// the executor registers it, which are two moments in one call — the RMW
930    /// seam runs inside `Executor::open_subscription`. So the row exists and the
931    /// fact arrives afterwards; this is the join.
932    ///
933    /// Keyed on `(source_name, type_name)` and taking the LAST unset match,
934    /// which is the row that was just created: two subscriptions on one topic of
935    /// one type are indistinguishable at this seam, and taking them in order is
936    /// the only attribution available. Returns `false` when no such row is
937    /// waiting — a caller that drops that has silently lost a fact, which is why
938    /// this is `#[must_use]` like every other recorder entry point.
939    ///
940    /// **Refuses to overwrite.** A row whose fact is already set is not a match,
941    /// so a second observation lands on the next unset row rather than
942    /// re-stating the first — the difference matters exactly when two rows
943    /// disagree, which is the case this whole field exists for.
944    /// The join for a lifecycle registration:
945    /// mark the recorded node the executor named as code-managed.
946    ///
947    /// Matched on the final name and on the namespace without its leading and
948    /// trailing `/` (the executor's `managed_node_id` rule), so `""`, `/` and
949    /// `/` + `/` are one root namespace. Returns `false` when no recorded node
950    /// matches: a registration the sidecar cannot attribute is a fact lost, and
951    /// the caller must say so rather than drop it.
952    #[must_use]
953    pub fn observe_lifecycle_registration(&mut self, name: &str, namespace: &str) -> bool {
954        let want = namespace.trim_matches('/');
955        for node in self.nodes.iter_mut() {
956            if node.name.as_str() == name && node.namespace.as_str().trim_matches('/') == want {
957                node.code_managed = true;
958                return true;
959            }
960        }
961        false
962    }
963
964    #[must_use]
965    pub fn observe_subscription_registration(
966        &mut self,
967        source_name: &str,
968        type_name: &str,
969        in_place_capable: bool,
970        buffered_row: BufferedRow,
971    ) -> bool {
972        for entity in self.entities.iter_mut() {
973            if entity.kind == EntityKind::Subscription
974                && entity.in_place_capable.is_none()
975                && entity.source_name.as_str() == source_name
976                && entity.type_name == type_name
977            {
978                entity.in_place_capable = Some(in_place_capable);
979                entity.buffered_row = Some(buffered_row);
980                return true;
981            }
982        }
983        false
984    }
985
986    /// Emit source metadata JSON ([`SOURCE_METADATA_SCHEMA_VERSION`]) without
987    /// opening transport.
988    #[cfg(feature = "alloc")]
989    pub fn to_source_metadata_json(
990        &self,
991        export: &SourceMetadataExport<'_>,
992    ) -> Result<StdString, core::fmt::Error> {
993        let mut out = StdString::new();
994        self.write_source_metadata_json(export, &mut out)?;
995        Ok(out)
996    }
997
998    /// Write source metadata JSON ([`SOURCE_METADATA_SCHEMA_VERSION`]) without
999    /// opening transport.
1000    #[cfg(feature = "alloc")]
1001    pub fn write_source_metadata_json(
1002        &self,
1003        export: &SourceMetadataExport<'_>,
1004        out: &mut impl core::fmt::Write,
1005    ) -> core::fmt::Result {
1006        write!(out, "{{")?;
1007        write!(out, "\"version\":{},", SOURCE_METADATA_SCHEMA_VERSION)?;
1008        write_json_field(out, "package", export.package)?;
1009        out.write_char(',')?;
1010        write_json_field(out, "component", export.component)?;
1011        out.write_char(',')?;
1012        write_json_field(out, "language", export.language)?;
1013        out.write_char(',')?;
1014        write_json_opt_field(out, "executable", export.executable)?;
1015        out.write_char(',')?;
1016        write_json_opt_field(out, "exported_symbol", export.exported_symbol)?;
1017        out.write_char(',')?;
1018        self.write_nodes_json(out)?;
1019        out.write_char(',')?;
1020        self.write_callbacks_json(out)?;
1021        out.write_char(',')?;
1022        self.write_parameters_json(out)?;
1023        out.write_char(',')?;
1024        if let Some(len) = self.description_max_len {
1025            write!(out, "\"parameter_description_max_len\":{len},")?;
1026        }
1027        if let Some(len) = self.constraints_max_len {
1028            write!(out, "\"parameter_constraints_max_len\":{len},")?;
1029        }
1030        if let Some(watched) = self.parameter_declarations_watched {
1031            write!(out, "\"parameter_declarations_watched\":{watched},")?;
1032        }
1033        self.write_trace_json(export, out)?;
1034        write!(out, "}}")
1035    }
1036
1037    /// Record a node.
1038    ///
1039    /// `pub` because the recorder is the ONE recorder: the Rust
1040    /// adapter (a `NodeContext` sink) and the C/C++ adapter (a recording RMW
1041    /// backend + the timer/guard hooks in `nros-cpp`) both feed it, so there is
1042    /// one definition of what a slot is and one schema emitter. Only the
1043    /// adapter is per-language. Not a general-purpose API — it exists for
1044    /// metadata-mode adapters, and misuse produces a sidecar that lies about
1045    /// what the component declares.
1046    pub fn push_node(
1047        &mut self,
1048        id: NodeId<'_>,
1049        name: &str,
1050        namespace: &str,
1051        domain_id: u32,
1052    ) -> Result<(), NodeMetadataError> {
1053        if self.has_node(id.as_str()) {
1054            return Err(NodeMetadataError::DuplicateId);
1055        }
1056
1057        self.nodes
1058            .push(NodeMetadata {
1059                slot: NodeSlot::new(self.nodes.len()),
1060                id: copy_str(id.as_str())?,
1061                source_default_name: copy_str(name)?,
1062                name: copy_str(name)?,
1063                namespace: copy_str(namespace)?,
1064                domain_id,
1065                code_managed: false,
1066            })
1067            .map_err(|_| NodeMetadataError::Capacity)
1068    }
1069
1070    /// Record an entity against an already-recorded node. See [`push_node`]
1071    /// for why this is public.
1072    ///
1073    /// [`push_node`]: Self::push_node
1074    pub fn push_entity(&mut self, mut entity: EntityMetadata) -> Result<(), NodeMetadataError> {
1075        if !self.has_node(&entity.node_id) {
1076            return Err(NodeMetadataError::UnknownNode);
1077        }
1078        if self.has_entity(&entity.id) {
1079            return Err(NodeMetadataError::DuplicateId);
1080        }
1081
1082        entity.slot = Some(EntitySlot::new(self.entities.len()));
1083        entity.node_slot = self.node_slot_for_id(&entity.node_id);
1084        let mut current_callbacks = Vec::<MetadataString, 3>::new();
1085        let mut next_callback_slot = self.callback_slot_count();
1086        entity.callback_slot = entity.callback_id.as_ref().map(|callback_id| {
1087            self.callback_slot_for_current_entity(
1088                callback_id.as_str(),
1089                &mut current_callbacks,
1090                &mut next_callback_slot,
1091            )
1092        });
1093        entity.action_cancel_callback_slot =
1094            entity
1095                .action_cancel_callback_id
1096                .as_ref()
1097                .map(|callback_id| {
1098                    self.callback_slot_for_current_entity(
1099                        callback_id.as_str(),
1100                        &mut current_callbacks,
1101                        &mut next_callback_slot,
1102                    )
1103                });
1104        entity.action_accepted_callback_slot =
1105            entity
1106                .action_accepted_callback_id
1107                .as_ref()
1108                .map(|callback_id| {
1109                    self.callback_slot_for_current_entity(
1110                        callback_id.as_str(),
1111                        &mut current_callbacks,
1112                        &mut next_callback_slot,
1113                    )
1114                });
1115
1116        self.entities
1117            .push(entity)
1118            .map_err(|_| NodeMetadataError::Capacity)
1119    }
1120
1121    pub(crate) fn push_callback_effect(
1122        &mut self,
1123        callback_id: CallbackId<'_>,
1124        kind: CallbackEffectKind,
1125        entity_id: EntityId<'_>,
1126    ) -> Result<(), NodeMetadataError> {
1127        if !self.has_entity(entity_id.as_str()) {
1128            return Err(NodeMetadataError::UnknownEntity);
1129        }
1130
1131        self.callback_effects
1132            .push(CallbackEffectMetadata {
1133                callback_id: copy_str(callback_id.as_str())?,
1134                callback_slot: self.callback_slot_for_id(callback_id.as_str()),
1135                kind,
1136                entity_id: copy_str(entity_id.as_str())?,
1137                entity_slot: self.entity_slot_for_id(entity_id.as_str()),
1138            })
1139            .map_err(|_| NodeMetadataError::Capacity)
1140    }
1141
1142    pub(crate) fn has_node(&self, id: &str) -> bool {
1143        self.nodes.iter().any(|node| node.id.as_str() == id)
1144    }
1145
1146    pub(crate) fn has_entity(&self, id: &str) -> bool {
1147        self.entities.iter().any(|entity| entity.id.as_str() == id)
1148    }
1149
1150    fn node_slot_for_id(&self, id: &str) -> Option<NodeSlot> {
1151        self.nodes
1152            .iter()
1153            .find(|node| node.id.as_str() == id)
1154            .map(|node| node.slot)
1155    }
1156
1157    fn entity_slot_for_id(&self, id: &str) -> Option<EntitySlot> {
1158        self.entities
1159            .iter()
1160            .find(|entity| entity.id.as_str() == id)
1161            .and_then(|entity| entity.slot)
1162    }
1163
1164    fn callback_slot_for_current_entity(
1165        &self,
1166        id: &str,
1167        current_callbacks: &mut Vec<MetadataString, 3>,
1168        next_callback_slot: &mut usize,
1169    ) -> CallbackSlot {
1170        if let Some(slot) = self.callback_slot_for_id(id) {
1171            return slot;
1172        }
1173        if let Some((index, _)) = current_callbacks
1174            .iter()
1175            .enumerate()
1176            .find(|(_, callback_id)| callback_id.as_str() == id)
1177        {
1178            return CallbackSlot::new(self.callback_slot_count() + index);
1179        }
1180        let slot = CallbackSlot::new(*next_callback_slot);
1181        let _ = current_callbacks
1182            .push(copy_str(id).expect("callback ID already fits metadata string capacity"));
1183        *next_callback_slot += 1;
1184        slot
1185    }
1186
1187    fn callback_slot_for_id(&self, id: &str) -> Option<CallbackSlot> {
1188        // Issue 2166: a `Rows`, so past MAX_CALLBACKS distinct callbacks the
1189        // slot numbering does not silently stop counting (`let _ = push`).
1190        let mut seen = Rows::<&str, MAX_CALLBACKS>::new();
1191        for entity in &self.entities {
1192            for callback_id in entity_callback_ids(entity) {
1193                let Some(callback_id) = callback_id else {
1194                    continue;
1195                };
1196                let callback_id = callback_id.as_str();
1197                if seen.contains(&callback_id) {
1198                    continue;
1199                }
1200                if callback_id == id {
1201                    return Some(CallbackSlot::new(seen.len()));
1202                }
1203                let _ = seen.push(callback_id);
1204            }
1205        }
1206        None
1207    }
1208
1209    fn callback_slot_count(&self) -> usize {
1210        // Issue 2166: a `Rows`, so past MAX_CALLBACKS distinct callbacks the
1211        // slot numbering does not silently stop counting (`let _ = push`).
1212        let mut seen = Rows::<&str, MAX_CALLBACKS>::new();
1213        for entity in &self.entities {
1214            for callback_id in entity_callback_ids(entity) {
1215                let Some(callback_id) = callback_id else {
1216                    continue;
1217                };
1218                let callback_id = callback_id.as_str();
1219                if !seen.contains(&callback_id) {
1220                    let _ = seen.push(callback_id);
1221                }
1222            }
1223        }
1224        seen.len()
1225    }
1226
1227    #[cfg(feature = "alloc")]
1228    fn write_nodes_json(&self, out: &mut impl core::fmt::Write) -> core::fmt::Result {
1229        write!(out, "\"nodes\":[")?;
1230        for (index, node) in self.nodes.iter().enumerate() {
1231            if index > 0 {
1232                out.write_char(',')?;
1233            }
1234            write!(out, "{{")?;
1235            write_json_field(out, "id", node.id.as_str())?;
1236            out.write_char(',')?;
1237            write!(out, "\"declaration_slot\":{},", node.slot.index())?;
1238            write_json_field(
1239                out,
1240                "source_default_name",
1241                node.source_default_name.as_str(),
1242            )?;
1243            out.write_char(',')?;
1244            write!(out, "\"unresolved_name\":")?;
1245            write_source_name(
1246                out,
1247                node.name.as_str(),
1248                SourceNameKind::from_source_name(&node.name),
1249            )?;
1250            out.write_char(',')?;
1251            if node.namespace.as_str() == "/" {
1252                write!(out, "\"namespace\":null,")?;
1253            } else {
1254                write_json_field(out, "namespace", node.namespace.as_str())?;
1255                out.write_char(',')?;
1256            }
1257            // Schema v5 (phase-554 W2.b): written only when the executor's
1258            // lifecycle funnel reported this node, so a reader's default
1259            // (`false`, plain) is the run-time rule for every other node.
1260            if node.code_managed {
1261                write!(out, "\"lifecycle\":true,")?;
1262            }
1263            self.write_node_entities(out, node.id.as_str())?;
1264            write!(out, "}}")?;
1265        }
1266        write!(out, "]")
1267    }
1268
1269    #[cfg(feature = "alloc")]
1270    fn write_node_entities(
1271        &self,
1272        out: &mut impl core::fmt::Write,
1273        node_id: &str,
1274    ) -> core::fmt::Result {
1275        self.write_entity_array(out, "publishers", node_id, EntityKind::Publisher)?;
1276        out.write_char(',')?;
1277        self.write_entity_array(out, "subscribers", node_id, EntityKind::Subscription)?;
1278        out.write_char(',')?;
1279        // phase-463 W1 -- guard conditions ride in `timers[]` with their own
1280        // `kind` (see `TimerKind::GuardCondition`), so `sidecar_slots` and the
1281        // leaf entity env keep counting one slot each.
1282        self.write_entity_array(out, "timers", node_id, EntityKind::Timer)?;
1283        out.write_char(',')?;
1284        self.write_entity_array(out, "services", node_id, EntityKind::ServiceServer)?;
1285        out.write_char(',')?;
1286        self.write_entity_array(out, "actions", node_id, EntityKind::ActionServer)?;
1287        // issue 0900 — the CLIENT halves. `record_entity` has always captured
1288        // them (`EntityKind::{ActionClient,ServiceClient}`, set in node.rs) and
1289        // this writer dropped them on the way out, so a sidecar described only
1290        // what a component SERVES. The executor arena is sized from the client
1291        // count, which is why the omission had a size cost and not just a
1292        // descriptive one.
1293        out.write_char(',')?;
1294        self.write_entity_array(out, "action_clients", node_id, EntityKind::ActionClient)?;
1295        out.write_char(',')?;
1296        self.write_entity_array(out, "service_clients", node_id, EntityKind::ServiceClient)
1297    }
1298
1299    #[cfg(feature = "alloc")]
1300    fn write_entity_array(
1301        &self,
1302        out: &mut impl core::fmt::Write,
1303        field: &str,
1304        node_id: &str,
1305        kind: EntityKind,
1306    ) -> core::fmt::Result {
1307        write!(out, "\"{}\":[", field)?;
1308        for (index, entity) in self
1309            .entities
1310            .iter()
1311            .filter(|entity| entity.node_id.as_str() == node_id && entity.kind == kind)
1312            .enumerate()
1313        {
1314            if index > 0 {
1315                out.write_char(',')?;
1316            }
1317            match kind {
1318                EntityKind::Publisher => write_publisher_json(out, entity)?,
1319                EntityKind::Subscription => write_subscriber_json(out, entity)?,
1320                EntityKind::Timer => write_timer_json(out, entity)?,
1321                EntityKind::ServiceServer => write_service_json(out, entity)?,
1322                EntityKind::ActionServer => write_action_json(out, entity)?,
1323                // issue 0900 — a client registers no callbacks, so it needs
1324                // none of the server writers' callback fields. One writer
1325                // serves both client kinds.
1326                EntityKind::ActionClient | EntityKind::ServiceClient => {
1327                    write_client_json(out, entity)?
1328                }
1329                _ => {}
1330            }
1331        }
1332        write!(out, "]")
1333    }
1334
1335    #[cfg(feature = "alloc")]
1336    fn write_callbacks_json(&self, out: &mut impl core::fmt::Write) -> core::fmt::Result {
1337        let callbacks = self.source_callbacks();
1338        write!(out, "\"callbacks\":[")?;
1339        for (index, callback) in callbacks.iter().enumerate() {
1340            if index > 0 {
1341                out.write_char(',')?;
1342            }
1343            write!(out, "{{")?;
1344            write_json_field(out, "id", callback.id.as_str())?;
1345            out.write_char(',')?;
1346            if let Some(slot) = callback.slot {
1347                write!(out, "\"declaration_slot\":{},", slot.index())?;
1348            }
1349            write_json_field(out, "kind", callback.kind)?;
1350            out.write_char(',')?;
1351            if let Some(group) = callback.group.as_ref() {
1352                write_json_field(out, "group", group)?;
1353                out.write_char(',')?;
1354            } else {
1355                write!(out, "\"group\":null,")?;
1356            }
1357            write!(out, "\"effects\":[")?;
1358            for (effect_index, effect) in self
1359                .callback_effects
1360                .iter()
1361                .filter(|effect| effect.callback_id.as_str() == callback.id)
1362                .enumerate()
1363            {
1364                if effect_index > 0 {
1365                    out.write_char(',')?;
1366                }
1367                write!(out, "{{")?;
1368                write_json_field(out, "kind", effect_json_kind(effect.kind))?;
1369                out.write_char(',')?;
1370                write_json_field(out, "entity", effect.entity_id.as_str())?;
1371                if let Some(entity_slot) = effect.entity_slot {
1372                    write!(out, ",\"entity_slot\":{}", entity_slot.index())?;
1373                }
1374                write!(out, "}}")?;
1375            }
1376            write!(out, "],")?;
1377            write_source_location(out, &callback.source)?;
1378            write!(out, "}}")?;
1379        }
1380        write!(out, "]")
1381    }
1382
1383    #[cfg(feature = "alloc")]
1384    fn write_parameters_json(&self, out: &mut impl core::fmt::Write) -> core::fmt::Result {
1385        write!(out, "\"parameters\":[")?;
1386        for (index, entity) in self
1387            .entities
1388            .iter()
1389            .filter(|entity| entity.kind == EntityKind::Parameter)
1390            .enumerate()
1391        {
1392            if index > 0 {
1393                out.write_char(',')?;
1394            }
1395            write!(out, "{{")?;
1396            write_json_field(out, "node", entity.node_id.as_str())?;
1397            out.write_char(',')?;
1398            if let Some(slot) = entity.slot {
1399                write!(out, "\"declaration_slot\":{},", slot.index())?;
1400            }
1401            write_json_field(out, "name", entity.source_name.as_str())?;
1402            out.write_char(',')?;
1403            // phase-463 W1 (schema v2) -- the declared type, so a census can
1404            // compare it with the contract's without inferring it from the
1405            // default's JSON shape (an integer default and a double default of
1406            // `0` are indistinguishable there).
1407            let parameter_type = entity.parameter_type.unwrap_or_else(|| {
1408                entity
1409                    .parameter_default
1410                    .as_ref()
1411                    .map(ParameterDefault::parameter_type)
1412                    .unwrap_or(ParameterType::NotSet)
1413            });
1414            write_json_field(out, "type", parameter_type_json(parameter_type))?;
1415            out.write_char(',')?;
1416            write!(out, "\"default\":")?;
1417            write_parameter_default(out, entity.parameter_default.as_ref())?;
1418            out.write_char(',')?;
1419            write!(out, "\"read_only\":{},", entity.parameter_read_only)?;
1420            if entity.parameter_read {
1421                write!(out, "\"read\":true,")?;
1422            }
1423            write_source_location(out, &entity.source)?;
1424            write!(out, "}}")?;
1425        }
1426        write!(out, "]")
1427    }
1428
1429    #[cfg(feature = "alloc")]
1430    fn write_trace_json(
1431        &self,
1432        export: &SourceMetadataExport<'_>,
1433        out: &mut impl core::fmt::Write,
1434    ) -> core::fmt::Result {
1435        write!(out, "\"trace\":{{")?;
1436        write_json_field(out, "generator", "nros-metadata-rust")?;
1437        out.write_char(',')?;
1438        write_json_field(out, "package_manifest", export.package_manifest)?;
1439        out.write_char(',')?;
1440        write!(out, "\"source_artifacts\":[")?;
1441        for (index, artifact) in export.source_artifacts.iter().enumerate() {
1442            if index > 0 {
1443                out.write_char(',')?;
1444            }
1445            write_json_string(out, artifact)?;
1446        }
1447        write!(out, "]}}")
1448    }
1449
1450    #[cfg(feature = "alloc")]
1451    fn source_callbacks(&self) -> StdVec<SourceCallbackRef> {
1452        let mut callbacks = StdVec::new();
1453        for entity in &self.entities {
1454            let Some(callback_id) = entity.callback_id.as_ref() else {
1455                continue;
1456            };
1457            let kind = match entity.kind {
1458                EntityKind::Subscription => "subscription",
1459                EntityKind::Timer if entity.timer_kind == TimerKind::GuardCondition => {
1460                    "guard_condition"
1461                }
1462                EntityKind::Timer => "timer",
1463                EntityKind::ServiceServer => "service",
1464                EntityKind::ActionServer => "action_goal",
1465                _ => continue,
1466            };
1467            if !callbacks
1468                .iter()
1469                .any(|callback: &SourceCallbackRef| callback.id == callback_id.as_str())
1470            {
1471                callbacks.push(SourceCallbackRef {
1472                    id: callback_id.as_str().into(),
1473                    slot: entity.callback_slot,
1474                    kind,
1475                    source: entity.callback_source.clone(),
1476                    group: entity
1477                        .callback_group
1478                        .as_ref()
1479                        .map(|group| group.as_str().into()),
1480                });
1481            }
1482            if entity.kind == EntityKind::ActionServer {
1483                if let Some(cancel_id) = entity.action_cancel_callback_id.as_ref()
1484                    && !callbacks
1485                        .iter()
1486                        .any(|callback: &SourceCallbackRef| callback.id == cancel_id.as_str())
1487                {
1488                    callbacks.push(SourceCallbackRef {
1489                        id: cancel_id.as_str().into(),
1490                        slot: entity.action_cancel_callback_slot,
1491                        kind: "action_cancel",
1492                        source: entity.action_cancel_source.clone(),
1493                        group: entity
1494                            .callback_group
1495                            .as_ref()
1496                            .map(|group| group.as_str().into()),
1497                    });
1498                }
1499                if let Some(accepted_id) = entity.action_accepted_callback_id.as_ref()
1500                    && !callbacks
1501                        .iter()
1502                        .any(|callback: &SourceCallbackRef| callback.id == accepted_id.as_str())
1503                {
1504                    callbacks.push(SourceCallbackRef {
1505                        id: accepted_id.as_str().into(),
1506                        slot: entity.action_accepted_callback_slot,
1507                        kind: "action_accepted",
1508                        source: entity.action_accepted_source.clone(),
1509                        group: entity
1510                            .callback_group
1511                            .as_ref()
1512                            .map(|group| group.as_str().into()),
1513                    });
1514                }
1515            }
1516        }
1517        callbacks
1518    }
1519}
1520
1521#[cfg(feature = "alloc")]
1522struct SourceCallbackRef {
1523    id: StdString,
1524    slot: Option<CallbackSlot>,
1525    kind: &'static str,
1526    source: SourceLocationMetadata,
1527    group: Option<StdString>,
1528}
1529
1530pub(crate) fn entity_callback_ids(entity: &EntityMetadata) -> [Option<&MetadataString>; 3] {
1531    [
1532        entity.callback_id.as_ref(),
1533        entity.action_cancel_callback_id.as_ref(),
1534        entity.action_accepted_callback_id.as_ref(),
1535    ]
1536}
1537
1538/// Inputs for [`entity_metadata`]. Collapses the seven positional
1539/// arguments — three of them adjacent `&str` (`source_name` /
1540/// `type_name` / `type_hash`) that are trivially transposable at a
1541/// call site — into one named-field struct.
1542/// `pub` alongside [`MetadataRecorder::push_entity`]: metadata-mode
1543/// adapters for other languages build entities through this ONE constructor so
1544/// the defaults (and therefore the recorded shape) cannot diverge per language.
1545pub struct EntityMetadataSpec<'a> {
1546    pub id: EntityId<'a>,
1547    pub node_id: NodeId<'a>,
1548    pub kind: EntityKind,
1549    pub source_name: &'a str,
1550    pub type_name: &'static str,
1551    pub type_hash: &'static str,
1552    pub qos: QoSProfile,
1553}
1554
1555/// Build an [`EntityMetadata`] from its identifying fields, defaulting the
1556/// rest. See [`EntityMetadataSpec`] for why this is public.
1557pub fn entity_metadata(spec: EntityMetadataSpec<'_>) -> Result<EntityMetadata, NodeMetadataError> {
1558    let EntityMetadataSpec {
1559        id,
1560        node_id,
1561        kind,
1562        source_name,
1563        type_name,
1564        type_hash,
1565        qos,
1566    } = spec;
1567    Ok(EntityMetadata {
1568        slot: None,
1569        id: copy_str(id.as_str())?,
1570        node_slot: None,
1571        node_id: copy_str(node_id.as_str())?,
1572        kind,
1573        source_name: copy_str(source_name)?,
1574        source_name_kind: SourceNameKind::from_source_name(source_name),
1575        type_name,
1576        type_hash,
1577        action_hashes: None,
1578        qos,
1579        callback_slot: None,
1580        callback_id: None,
1581        callback_source: SourceLocationMetadata::empty(),
1582        callback_group: None,
1583        action_cancel_callback_slot: None,
1584        action_cancel_callback_id: None,
1585        action_cancel_source: SourceLocationMetadata::empty(),
1586        action_accepted_callback_slot: None,
1587        action_accepted_callback_id: None,
1588        action_accepted_source: SourceLocationMetadata::empty(),
1589        period_ms: None,
1590        period_us: None,
1591        timer_clock: TimerClockSource::Steady,
1592        timer_autostart: true,
1593        timer_kind: TimerKind::Wall,
1594        parameter_type: None,
1595        parameter_default: None,
1596        parameter_read_only: false,
1597        parameter_read: false,
1598        safety: false,
1599        message_info: false,
1600        // phase-457 W3 -- "nobody observed this". Set later, and only for a
1601        // subscription, by `metadata_mode::record_subscription_registration`.
1602        in_place_capable: None,
1603        buffered_row: None,
1604        rx_bound: None,
1605        source: SourceLocationMetadata::empty(),
1606    })
1607}
1608
1609#[cfg(feature = "alloc")]
1610fn write_publisher_json(
1611    out: &mut impl core::fmt::Write,
1612    entity: &EntityMetadata,
1613) -> core::fmt::Result {
1614    write!(out, "{{")?;
1615    write_json_field(out, "id", entity.id.as_str())?;
1616    out.write_char(',')?;
1617    if let Some(slot) = entity.slot {
1618        write!(out, "\"declaration_slot\":{},", slot.index())?;
1619    }
1620    write!(out, "\"unresolved_topic\":")?;
1621    write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1622    out.write_char(',')?;
1623    write_interface(out, entity.type_name, "message")?;
1624    out.write_char(',')?;
1625    write_qos(out, entity.qos)?;
1626    write!(out, "}}")
1627}
1628
1629#[cfg(feature = "alloc")]
1630fn write_subscriber_json(
1631    out: &mut impl core::fmt::Write,
1632    entity: &EntityMetadata,
1633) -> core::fmt::Result {
1634    write!(out, "{{")?;
1635    write_json_field(out, "id", entity.id.as_str())?;
1636    out.write_char(',')?;
1637    if let Some(slot) = entity.slot {
1638        write!(out, "\"declaration_slot\":{},", slot.index())?;
1639    }
1640    write!(out, "\"unresolved_topic\":")?;
1641    write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1642    out.write_char(',')?;
1643    write_interface(out, entity.type_name, "message")?;
1644    out.write_char(',')?;
1645    write_qos(out, entity.qos)?;
1646    out.write_char(',')?;
1647    write_json_field(
1648        out,
1649        "callback",
1650        entity
1651            .callback_id
1652            .as_ref()
1653            .map(|id| id.as_str())
1654            .unwrap_or(""),
1655    )?;
1656    if let Some(callback_slot) = entity.callback_slot {
1657        write!(out, ",\"callback_slot\":{}", callback_slot.index())?;
1658    }
1659    // phase-457 W3 (schema v3) -- the CALL SITE's half of this subscription's
1660    // registration path, when something observed it. Written only when known:
1661    // an absent key is "nobody observed this", which every consumer must read
1662    // as a refusal rather than as `false` (see `in_place_capable`).
1663    if let Some(in_place) = entity.in_place_capable {
1664        write!(out, ",\"in_place\":{in_place}")?;
1665    }
1666    // Issue 1648 (schema v4) -- the buffered row the same registration
1667    // claimed; absent exactly when `in_place` is.
1668    if let Some(row) = entity.buffered_row {
1669        write!(out, ",\"buffered\":\"{}\"", row.as_str())?;
1670    }
1671    write!(out, "}}")
1672}
1673
1674#[cfg(feature = "alloc")]
1675fn write_timer_json(out: &mut impl core::fmt::Write, entity: &EntityMetadata) -> core::fmt::Result {
1676    write!(out, "{{")?;
1677    write_json_field(out, "id", entity.id.as_str())?;
1678    out.write_char(',')?;
1679    if let Some(slot) = entity.slot {
1680        write!(out, "\"declaration_slot\":{},", slot.index())?;
1681    }
1682    // phase-463 W1 (schema v2) -- the row's kind. A guard condition is a row
1683    // of this array (one callback slot, like a timer) whose period is
1684    // meaningless; the kind is what tells a reader so.
1685    write_json_field(out, "kind", timer_kind_json(entity.timer_kind))?;
1686    out.write_char(',')?;
1687    write!(out, "\"period_ms\":{},", entity.period_ms.unwrap_or(0))?;
1688    write!(out, "\"period_us\":{},", entity.period_us.unwrap_or(0))?;
1689    write_json_field(
1690        out,
1691        "callback",
1692        entity
1693            .callback_id
1694            .as_ref()
1695            .map(|id| id.as_str())
1696            .unwrap_or(""),
1697    )?;
1698    if let Some(callback_slot) = entity.callback_slot {
1699        write!(out, ",\"callback_slot\":{}", callback_slot.index())?;
1700    }
1701    write!(out, "}}")
1702}
1703
1704#[cfg(feature = "alloc")]
1705fn write_service_json(
1706    out: &mut impl core::fmt::Write,
1707    entity: &EntityMetadata,
1708) -> core::fmt::Result {
1709    write!(out, "{{")?;
1710    write_json_field(out, "id", entity.id.as_str())?;
1711    out.write_char(',')?;
1712    if let Some(slot) = entity.slot {
1713        write!(out, "\"declaration_slot\":{},", slot.index())?;
1714    }
1715    write!(out, "\"unresolved_name\":")?;
1716    write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1717    out.write_char(',')?;
1718    write_interface(out, entity.type_name, "service")?;
1719    out.write_char(',')?;
1720    // phase-463 W1 (schema v2) -- every endpoint kind carries its QoS.
1721    write_qos(out, entity.qos)?;
1722    out.write_char(',')?;
1723    write_json_field(
1724        out,
1725        "callback",
1726        entity
1727            .callback_id
1728            .as_ref()
1729            .map(|id| id.as_str())
1730            .unwrap_or(""),
1731    )?;
1732    if let Some(callback_slot) = entity.callback_slot {
1733        write!(out, ",\"callback_slot\":{}", callback_slot.index())?;
1734    }
1735    write!(out, "}}")
1736}
1737
1738/// issue 0900 — a client entity: identity, name and interface, no callbacks.
1739///
1740/// Deliberately ONE writer for both `ActionClient` and `ServiceClient`. They
1741/// differ only in the interface KIND word, and the server-side pair is already
1742/// two near-identical functions; a third and fourth would be the second
1743/// spelling this repo keeps paying for.
1744#[cfg(feature = "alloc")]
1745fn write_client_json(
1746    out: &mut impl core::fmt::Write,
1747    entity: &EntityMetadata,
1748) -> core::fmt::Result {
1749    let interface_kind = if entity.kind == EntityKind::ActionClient {
1750        "action"
1751    } else {
1752        "service"
1753    };
1754    write!(out, "{{")?;
1755    write_json_field(out, "id", entity.id.as_str())?;
1756    out.write_char(',')?;
1757    if let Some(slot) = entity.slot {
1758        write!(out, "\"declaration_slot\":{},", slot.index())?;
1759    }
1760    write!(out, "\"unresolved_name\":")?;
1761    write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1762    out.write_char(',')?;
1763    write_interface(out, entity.type_name, interface_kind)?;
1764    out.write_char(',')?;
1765    // phase-463 W1 (schema v2) -- every endpoint kind carries its QoS.
1766    write_qos(out, entity.qos)?;
1767    write!(out, "}}")
1768}
1769
1770#[cfg(feature = "alloc")]
1771fn write_action_json(
1772    out: &mut impl core::fmt::Write,
1773    entity: &EntityMetadata,
1774) -> core::fmt::Result {
1775    let goal_callback = entity
1776        .callback_id
1777        .as_ref()
1778        .map(|id| id.as_str())
1779        .unwrap_or("");
1780    let cancel_callback = entity
1781        .action_cancel_callback_id
1782        .as_ref()
1783        .map(|id| id.as_str())
1784        .unwrap_or(goal_callback);
1785    let accepted_callback = entity
1786        .action_accepted_callback_id
1787        .as_ref()
1788        .map(|id| id.as_str())
1789        .unwrap_or(goal_callback);
1790    write!(out, "{{")?;
1791    write_json_field(out, "id", entity.id.as_str())?;
1792    out.write_char(',')?;
1793    if let Some(slot) = entity.slot {
1794        write!(out, "\"declaration_slot\":{},", slot.index())?;
1795    }
1796    write!(out, "\"unresolved_name\":")?;
1797    write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1798    out.write_char(',')?;
1799    write_interface(out, entity.type_name, "action")?;
1800    out.write_char(',')?;
1801    // phase-463 W1 (schema v2) -- every endpoint kind carries its QoS.
1802    write_qos(out, entity.qos)?;
1803    out.write_char(',')?;
1804    write_json_field(out, "goal_callback", goal_callback)?;
1805    if let Some(callback_slot) = entity.callback_slot {
1806        write!(out, ",\"goal_callback_slot\":{}", callback_slot.index())?;
1807    }
1808    out.write_char(',')?;
1809    write_json_field(out, "cancel_callback", cancel_callback)?;
1810    if let Some(callback_slot) = entity.action_cancel_callback_slot {
1811        write!(out, ",\"cancel_callback_slot\":{}", callback_slot.index())?;
1812    }
1813    out.write_char(',')?;
1814    write_json_field(out, "accepted_callback", accepted_callback)?;
1815    if let Some(callback_slot) = entity.action_accepted_callback_slot {
1816        write!(out, ",\"accepted_callback_slot\":{}", callback_slot.index())?;
1817    }
1818    write!(out, "}}")
1819}
1820
1821#[cfg(feature = "alloc")]
1822fn write_source_name(
1823    out: &mut impl core::fmt::Write,
1824    value: &str,
1825    kind: SourceNameKind,
1826) -> core::fmt::Result {
1827    write!(out, "{{")?;
1828    write_json_field(out, "value", value)?;
1829    out.write_char(',')?;
1830    write_json_field(out, "kind", source_name_kind_json(kind))?;
1831    write!(out, "}}")
1832}
1833
1834#[cfg(feature = "alloc")]
1835fn write_interface(
1836    out: &mut impl core::fmt::Write,
1837    type_name: &str,
1838    fallback_kind: &'static str,
1839) -> core::fmt::Result {
1840    let interface = parse_interface(type_name, fallback_kind);
1841    write!(out, "\"interface\":{{")?;
1842    write_json_field(out, "package", &interface.package)?;
1843    out.write_char(',')?;
1844    write_json_field(out, "name", &interface.name)?;
1845    out.write_char(',')?;
1846    write_json_field(out, "kind", interface.kind)?;
1847    write!(out, "}}")
1848}
1849
1850#[cfg(feature = "alloc")]
1851fn write_qos(out: &mut impl core::fmt::Write, qos: QoSProfile) -> core::fmt::Result {
1852    write!(out, "\"qos\":{{")?;
1853    write_json_field(out, "reliability", reliability_json(qos.reliability))?;
1854    out.write_char(',')?;
1855    write_json_field(out, "durability", durability_json(qos.durability))?;
1856    out.write_char(',')?;
1857    write_json_field(out, "history", history_json(qos.history))?;
1858    out.write_char(',')?;
1859    write!(out, "\"depth\":{},", qos.depth)?;
1860    write_optional_ms(out, "deadline_ms", qos.deadline_ms)?;
1861    out.write_char(',')?;
1862    write_optional_ms(out, "lifespan_ms", qos.lifespan_ms)?;
1863    out.write_char(',')?;
1864    write_json_field(out, "liveliness", liveliness_json(qos.liveliness_kind))?;
1865    out.write_char(',')?;
1866    write_optional_ms(out, "liveliness_lease_duration_ms", qos.liveliness_lease_ms)?;
1867    write!(out, ",\"extensions\":{{}}}}")
1868}
1869
1870#[cfg(feature = "alloc")]
1871fn write_source_location(
1872    out: &mut impl core::fmt::Write,
1873    source: &SourceLocationMetadata,
1874) -> core::fmt::Result {
1875    write!(out, "\"source\":{{")?;
1876    write_json_field(out, "artifact", source.artifact.as_str())?;
1877    out.write_char(',')?;
1878    write!(out, "\"line\":")?;
1879    write_optional_u32(out, source.line)?;
1880    out.write_char(',')?;
1881    write!(out, "\"column\":")?;
1882    write_optional_u32(out, source.column)?;
1883    write!(out, "}}")
1884}
1885
1886#[cfg(feature = "alloc")]
1887fn write_parameter_default(
1888    out: &mut impl core::fmt::Write,
1889    default: Option<&ParameterDefault>,
1890) -> core::fmt::Result {
1891    match default {
1892        Some(ParameterDefault::Bool(value)) => write!(out, "{}", value),
1893        Some(ParameterDefault::Integer(value)) => write!(out, "{}", value),
1894        // JSON has no literal for infinity or NaN: a bare `inf` (what `{:?}`
1895        // prints for `f64::INFINITY`) makes the whole sidecar unparseable.
1896        // A non-finite default is recorded as a string; `type` still says
1897        // double.
1898        Some(ParameterDefault::Double(value)) => {
1899            let text = value.as_str();
1900            if text.parse::<f64>().is_ok_and(f64::is_finite) {
1901                write!(out, "{}", text)
1902            } else {
1903                write_json_string(out, text)
1904            }
1905        }
1906        Some(ParameterDefault::String(value)) => write_json_string(out, value.as_str()),
1907        Some(ParameterDefault::BoolArray)
1908        | Some(ParameterDefault::IntegerArray)
1909        | Some(ParameterDefault::DoubleArray)
1910        | Some(ParameterDefault::StringArray)
1911        | None => write!(out, "[]"),
1912    }
1913}
1914
1915#[cfg(feature = "alloc")]
1916fn write_json_field(out: &mut impl core::fmt::Write, name: &str, value: &str) -> core::fmt::Result {
1917    write_json_string(out, name)?;
1918    out.write_char(':')?;
1919    write_json_string(out, value)
1920}
1921
1922#[cfg(feature = "alloc")]
1923fn write_json_opt_field(
1924    out: &mut impl core::fmt::Write,
1925    name: &str,
1926    value: Option<&str>,
1927) -> core::fmt::Result {
1928    write_json_string(out, name)?;
1929    out.write_char(':')?;
1930    if let Some(value) = value {
1931        write_json_string(out, value)
1932    } else {
1933        write!(out, "null")
1934    }
1935}
1936
1937#[cfg(feature = "alloc")]
1938fn write_json_string(out: &mut impl core::fmt::Write, value: &str) -> core::fmt::Result {
1939    out.write_char('"')?;
1940    for ch in value.chars() {
1941        match ch {
1942            '"' => write!(out, "\\\"")?,
1943            '\\' => write!(out, "\\\\")?,
1944            '\n' => write!(out, "\\n")?,
1945            '\r' => write!(out, "\\r")?,
1946            '\t' => write!(out, "\\t")?,
1947            ch if ch.is_control() => write!(out, "\\u{:04x}", ch as u32)?,
1948            ch => out.write_char(ch)?,
1949        }
1950    }
1951    out.write_char('"')
1952}
1953
1954#[cfg(feature = "alloc")]
1955fn write_optional_ms(out: &mut impl core::fmt::Write, name: &str, value: u32) -> core::fmt::Result {
1956    write_json_string(out, name)?;
1957    out.write_char(':')?;
1958    if value == 0 {
1959        write!(out, "null")
1960    } else {
1961        write!(out, "{}", value)
1962    }
1963}
1964
1965#[cfg(feature = "alloc")]
1966fn write_optional_u32(out: &mut impl core::fmt::Write, value: Option<u32>) -> core::fmt::Result {
1967    if let Some(value) = value {
1968        write!(out, "{}", value)
1969    } else {
1970        write!(out, "null")
1971    }
1972}
1973
1974#[cfg(feature = "alloc")]
1975fn source_name_kind_json(kind: SourceNameKind) -> &'static str {
1976    match kind {
1977        SourceNameKind::Absolute => "absolute",
1978        SourceNameKind::Relative => "relative",
1979        SourceNameKind::Private => "private",
1980    }
1981}
1982
1983#[cfg(feature = "alloc")]
1984fn timer_kind_json(kind: TimerKind) -> &'static str {
1985    match kind {
1986        TimerKind::Wall => "wall",
1987        TimerKind::Clock => "clock",
1988        TimerKind::Oneshot => "oneshot",
1989        TimerKind::InGroup => "in_group",
1990        TimerKind::GuardCondition => "guard_condition",
1991    }
1992}
1993
1994/// phase-463 W1 -- the `type` word on a parameter row. The spellings are the
1995/// orchestration IR's (`nros-cli-core/src/orchestration/source_metadata.rs`,
1996/// `SourceParameterType`), snake_case.
1997#[cfg(feature = "alloc")]
1998fn parameter_type_json(value: ParameterType) -> &'static str {
1999    match value {
2000        ParameterType::NotSet => "not_set",
2001        ParameterType::Bool => "bool",
2002        ParameterType::Integer => "integer",
2003        ParameterType::Double => "double",
2004        ParameterType::String => "string",
2005        ParameterType::ByteArray => "byte_array",
2006        ParameterType::BoolArray => "bool_array",
2007        ParameterType::IntegerArray => "integer_array",
2008        ParameterType::DoubleArray => "double_array",
2009        ParameterType::StringArray => "string_array",
2010    }
2011}
2012
2013#[cfg(feature = "alloc")]
2014fn effect_json_kind(kind: CallbackEffectKind) -> &'static str {
2015    match kind {
2016        CallbackEffectKind::Publishes => "publishes",
2017        CallbackEffectKind::Reads => "reads_parameter",
2018        CallbackEffectKind::Writes => "writes_parameter",
2019    }
2020}
2021
2022// issue 0829 — `"system_default"` is the spelling `liveliness_json` below
2023// already uses for the same sentinel, and the one the orchestration IR emits
2024// for an unstated policy (`nros-cli-core/src/orchestration/schema.rs:58-88`,
2025// `planner.rs:1657-1671`). The metadata reports what the node REQUESTED, so a
2026// sentinel must survive to the JSON: printing the resolved value here would
2027// claim the node asked for something it left to the backend.
2028#[cfg(feature = "alloc")]
2029fn reliability_json(value: QoSReliabilityPolicy) -> &'static str {
2030    match value {
2031        QoSReliabilityPolicy::SystemDefault => "system_default",
2032        QoSReliabilityPolicy::Reliable => "reliable",
2033        QoSReliabilityPolicy::BestEffort => "best_effort",
2034        // issue 1437 — a read-back sentinel, which this function's INPUT can
2035        // never be: the metadata reports what a node REQUESTED and
2036        // `validate_against` refuses `UNKNOWN` as a request. Spelled out
2037        // rather than `_` so a new policy value is a decision here.
2038        QoSReliabilityPolicy::Unknown => "unknown",
2039        // issue 1973 — a REQUEST, so it is exactly what this reports: the
2040        // node asked for the graph to decide, and the decision happens at
2041        // creation on the target, not here. Upstream's own spelling.
2042        QoSReliabilityPolicy::BestAvailable => "best_available",
2043    }
2044}
2045
2046#[cfg(feature = "alloc")]
2047fn durability_json(value: QoSDurabilityPolicy) -> &'static str {
2048    match value {
2049        QoSDurabilityPolicy::SystemDefault => "system_default",
2050        QoSDurabilityPolicy::Volatile => "volatile",
2051        QoSDurabilityPolicy::TransientLocal => "transient_local",
2052        // See `reliability_json`.
2053        QoSDurabilityPolicy::Unknown => "unknown",
2054        QoSDurabilityPolicy::BestAvailable => "best_available",
2055    }
2056}
2057
2058#[cfg(feature = "alloc")]
2059fn history_json(value: QoSHistoryPolicy) -> &'static str {
2060    match value {
2061        QoSHistoryPolicy::SystemDefault => "system_default",
2062        QoSHistoryPolicy::KeepLast => "keep_last",
2063        QoSHistoryPolicy::KeepAll => "keep_all",
2064        // See `reliability_json`.
2065        QoSHistoryPolicy::Unknown => "unknown",
2066    }
2067}
2068
2069#[cfg(feature = "alloc")]
2070fn liveliness_json(value: QoSLivelinessPolicy) -> &'static str {
2071    match value {
2072        QoSLivelinessPolicy::None => "system_default",
2073        QoSLivelinessPolicy::Automatic => "automatic",
2074        QoSLivelinessPolicy::ManualByTopic => "manual_by_topic",
2075        QoSLivelinessPolicy::ManualByNode => "manual_by_node",
2076        // See `reliability_json`.
2077        QoSLivelinessPolicy::Unknown => "unknown",
2078        QoSLivelinessPolicy::BestAvailable => "best_available",
2079    }
2080}
2081
2082#[cfg(feature = "alloc")]
2083struct ParsedInterface {
2084    package: StdString,
2085    name: StdString,
2086    kind: &'static str,
2087}
2088
2089#[cfg(feature = "alloc")]
2090fn parse_interface(type_name: &str, fallback_kind: &'static str) -> ParsedInterface {
2091    let parts: StdVec<&str> = type_name.split("::").collect();
2092    if parts.len() >= 4 {
2093        let package = parts[0].into();
2094        let kind = match parts[1] {
2095            "msg" => "message",
2096            "srv" => "service",
2097            "action" => "action",
2098            _ => fallback_kind,
2099        };
2100        let mut type_leaf = parts[3].trim_end_matches('_');
2101        if type_leaf.is_empty() {
2102            type_leaf = parts.last().copied().unwrap_or("");
2103        }
2104        return ParsedInterface {
2105            package,
2106            name: format!("{}/{}", parts[1], type_leaf),
2107            kind,
2108        };
2109    }
2110
2111    ParsedInterface {
2112        package: StdString::new(),
2113        name: type_name.into(),
2114        kind: fallback_kind,
2115    }
2116}
2117
2118#[cfg(test)]
2119mod tests {
2120    // Issue 2964.
2121    /// The declaration watch has three states, as descriptor prose does: not
2122    /// watched (no key), watched whole (`true`), and watched but broken
2123    /// (`false`). A broken watch stays broken, and an unwatched recorder
2124    /// ignores a break, so it never claims a watch it did not arm.
2125    #[cfg(feature = "alloc")]
2126    #[test]
2127    fn the_declaration_watch_is_stated_only_when_armed_and_stays_broken() {
2128        let export = super::SourceMetadataExport::new("p", "c");
2129        let mut r: super::MetadataRecorder = super::MetadataRecorder::new();
2130        r.break_parameter_declarations();
2131        assert_eq!(r.parameter_declarations_watched(), None);
2132        let json = r.to_source_metadata_json(&export).unwrap();
2133        assert!(!json.contains("parameter_declarations_watched"), "{json}");
2134
2135        r.arm_parameter_declarations();
2136        let json = r.to_source_metadata_json(&export).unwrap();
2137        assert!(
2138            json.contains("\"parameter_declarations_watched\":true,"),
2139            "{json}"
2140        );
2141
2142        r.break_parameter_declarations();
2143        r.arm_parameter_declarations();
2144        assert_eq!(r.parameter_declarations_watched(), Some(false));
2145        let json = r.to_source_metadata_json(&export).unwrap();
2146        assert!(
2147            json.contains("\"parameter_declarations_watched\":false,"),
2148            "{json}"
2149        );
2150    }
2151
2152    /// Issue 0699 — a source path longer than the buffer must RECORD, not fail.
2153    ///
2154    /// `nros sync` died with `Metadata(NameTooLong)` purely because the user's
2155    /// workspace sat ~100 chars deep: rustc emits `Location::file()` absolute
2156    /// for a path dependency, so this field's length is set by where the user
2157    /// keeps their files. The tail is what the CLI keeps anyway.
2158    #[test]
2159    fn a_path_longer_than_the_buffer_keeps_its_tail() {
2160        // A literal, not `format!`: this crate is `no_std` and the test cfg has
2161        // no allocator — the same constraint the buffer itself exists under.
2162        let deep = concat!(
2163            "/deep/nested/nested/nested/nested/nested/nested/nested/nested/",
2164            "nested/nested/nested/nested/nested/nested/nested/nested/nested/",
2165            "ws/build/nros-metadata/metadata-probe/listener/src/lib.rs"
2166        );
2167        assert!(deep.len() > super::METADATA_STRING_CAPACITY);
2168
2169        let got = super::copy_str_keep_tail(deep).expect("must not error on depth");
2170        assert!(got.len() <= super::METADATA_STRING_CAPACITY);
2171        assert!(
2172            got.ends_with("src/lib.rs"),
2173            "the informative tail must survive, got {got:?}"
2174        );
2175        assert!(got.starts_with('…'), "a cut must be visible, got {got:?}");
2176
2177        // A path that fits is untouched — no marker, no loss.
2178        let short = "src/lib.rs";
2179        assert_eq!(super::copy_str_keep_tail(short).unwrap().as_str(), short);
2180    }
2181
2182    use super::*;
2183    use crate::qos;
2184
2185    /// A non-finite double default (an "unbounded" timeout declared as
2186    /// `std::numeric_limits<double>::infinity()`) must still produce valid
2187    /// JSON; a finite one stays a JSON number.
2188    #[cfg(feature = "alloc")]
2189    #[test]
2190    fn a_non_finite_double_default_is_valid_json() {
2191        let mut out = StdString::new();
2192        for (value, want) in [
2193            (f64::INFINITY, "\"inf\""),
2194            (f64::NEG_INFINITY, "\"-inf\""),
2195            (f64::NAN, "\"NaN\""),
2196            (1.5, "1.5"),
2197        ] {
2198            out.clear();
2199            let default = ParameterDefault::from_value(&ParameterValue::Double(value)).unwrap();
2200            write_parameter_default(&mut out, Some(&default)).unwrap();
2201            assert_eq!(out, want);
2202        }
2203    }
2204
2205    #[test]
2206    fn source_name_kind_preserves_unresolved_names() {
2207        assert_eq!(
2208            SourceNameKind::from_source_name("/scan"),
2209            SourceNameKind::Absolute
2210        );
2211        assert_eq!(
2212            SourceNameKind::from_source_name("~/scan"),
2213            SourceNameKind::Private
2214        );
2215        assert_eq!(
2216            SourceNameKind::from_source_name("scan"),
2217            SourceNameKind::Relative
2218        );
2219    }
2220
2221    // Phase 305 W3 (issue 0255) — the expansion/remap seam as re-exported here.
2222    // The exhaustive rule matrix lives with the impl (`nros_node::names`);
2223    // these pin the metadata-level contract each `SourceNameKind` maps to.
2224    #[test]
2225    fn expand_name_covers_each_source_name_kind() {
2226        // Absolute: unchanged.
2227        assert_eq!(
2228            expand_name("/scan", "lidar", "/sensing").unwrap().as_str(),
2229            "/scan"
2230        );
2231        // Private: node-FQN prefixed; ns=/ collapses.
2232        assert_eq!(
2233            expand_name("~/scan", "lidar", "/sensing").unwrap().as_str(),
2234            "/sensing/lidar/scan"
2235        );
2236        assert_eq!(
2237            expand_name("~/scan", "lidar", "/").unwrap().as_str(),
2238            "/lidar/scan"
2239        );
2240        // Relative: namespace prefixed; ns=/ collapses.
2241        assert_eq!(
2242            expand_name("scan", "lidar", "/sensing").unwrap().as_str(),
2243            "/sensing/scan"
2244        );
2245        assert_eq!(expand_name("scan", "lidar", "/").unwrap().as_str(), "/scan");
2246    }
2247
2248    #[test]
2249    fn resolve_name_substitutes_first_matching_rule() {
2250        let remaps = [
2251            ("~/scan", "/points_raw"),
2252            ("/sensing/lidar/scan", "/ignored"),
2253        ];
2254        assert_eq!(
2255            resolve_name("~/scan", "lidar", "/sensing", remaps)
2256                .unwrap()
2257                .as_str(),
2258            "/points_raw"
2259        );
2260        // No match → the expansion stands.
2261        assert_eq!(
2262            resolve_name("other", "lidar", "/sensing", [("/x", "/y")])
2263                .unwrap()
2264                .as_str(),
2265            "/sensing/other"
2266        );
2267    }
2268
2269    #[test]
2270    fn recorder_rejects_duplicate_stable_ids() {
2271        let mut recorder = MetadataRecorder::<1, 2, 1>::new();
2272        recorder
2273            .push_node(NodeId::new("node"), "talker", "/", 0)
2274            .unwrap();
2275
2276        let first = entity_metadata(EntityMetadataSpec {
2277            id: EntityId::new("pub"),
2278            node_id: NodeId::new("node"),
2279            kind: EntityKind::Publisher,
2280            source_name: "chatter",
2281            type_name: "std_msgs::msg::dds_::String_",
2282            type_hash: "hash",
2283            qos: qos::DEFAULT,
2284        })
2285        .unwrap();
2286        recorder.push_entity(first.clone()).unwrap();
2287
2288        assert_eq!(
2289            recorder.push_entity(first),
2290            Err(NodeMetadataError::DuplicateId)
2291        );
2292    }
2293
2294    #[test]
2295    fn recorder_rejects_duplicate_nodes_and_unknown_node_entities() {
2296        let mut recorder = MetadataRecorder::<1, 1, 1>::new();
2297        recorder
2298            .push_node(NodeId::new("node"), "talker", "/", 0)
2299            .unwrap();
2300
2301        assert_eq!(
2302            recorder.push_node(NodeId::new("node"), "other", "/", 0),
2303            Err(NodeMetadataError::DuplicateId)
2304        );
2305
2306        let entity = entity_metadata(EntityMetadataSpec {
2307            id: EntityId::new("pub"),
2308            node_id: NodeId::new("missing_node"),
2309            kind: EntityKind::Publisher,
2310            source_name: "chatter",
2311            type_name: "std_msgs::msg::dds_::String_",
2312            type_hash: "hash",
2313            qos: qos::DEFAULT,
2314        })
2315        .unwrap();
2316
2317        assert_eq!(
2318            recorder.push_entity(entity),
2319            Err(NodeMetadataError::UnknownNode)
2320        );
2321    }
2322
2323    #[test]
2324    fn recorder_assigns_slots_and_source_default_names_by_declaration_order() {
2325        let mut recorder = MetadataRecorder::<2, 4, 3>::new();
2326        recorder
2327            .push_node(NodeId::new("node_alpha"), "talker", "/", 0)
2328            .unwrap();
2329        recorder
2330            .push_node(NodeId::new("node_beta"), "listener", "/demo", 42)
2331            .unwrap();
2332
2333        assert_eq!(recorder.nodes()[0].slot, NodeSlot::new(0));
2334        assert_eq!(recorder.nodes()[0].source_default_name.as_str(), "talker");
2335        assert_eq!(recorder.nodes()[1].slot, NodeSlot::new(1));
2336        assert_eq!(recorder.nodes()[1].source_default_name.as_str(), "listener");
2337
2338        recorder
2339            .push_entity(
2340                entity_metadata(EntityMetadataSpec {
2341                    id: EntityId::new("pub_chatter"),
2342                    node_id: NodeId::new("node_alpha"),
2343                    kind: EntityKind::Publisher,
2344                    source_name: "/chatter",
2345                    type_name: "std_msgs::msg::dds_::String_",
2346                    type_hash: "hash",
2347                    qos: qos::DEFAULT,
2348                })
2349                .unwrap(),
2350            )
2351            .unwrap();
2352        let mut subscription = entity_metadata(EntityMetadataSpec {
2353            id: EntityId::new("sub_chatter"),
2354            node_id: NodeId::new("node_beta"),
2355            kind: EntityKind::Subscription,
2356            source_name: "/chatter",
2357            type_name: "std_msgs::msg::dds_::String_",
2358            type_hash: "hash",
2359            qos: qos::DEFAULT,
2360        })
2361        .unwrap();
2362        subscription.callback_id = Some(copy_str("on_message").unwrap());
2363        recorder.push_entity(subscription).unwrap();
2364        let mut timer = entity_metadata(EntityMetadataSpec {
2365            id: EntityId::new("timer_tick"),
2366            node_id: NodeId::new("node_alpha"),
2367            kind: EntityKind::Timer,
2368            source_name: "",
2369            type_name: "",
2370            type_hash: "",
2371            qos: qos::DEFAULT,
2372        })
2373        .unwrap();
2374        timer.callback_id = Some(copy_str("on_tick").unwrap());
2375        recorder.push_entity(timer).unwrap();
2376
2377        assert_eq!(recorder.entities()[0].slot, Some(EntitySlot::new(0)));
2378        assert_eq!(recorder.entities()[0].node_slot, Some(NodeSlot::new(0)));
2379        assert_eq!(recorder.entities()[0].callback_slot, None);
2380        assert_eq!(recorder.entities()[1].slot, Some(EntitySlot::new(1)));
2381        assert_eq!(recorder.entities()[1].node_slot, Some(NodeSlot::new(1)));
2382        assert_eq!(
2383            recorder.entities()[1].callback_slot,
2384            Some(CallbackSlot::new(0))
2385        );
2386        assert_eq!(
2387            recorder.entities()[2].callback_slot,
2388            Some(CallbackSlot::new(1))
2389        );
2390
2391        recorder
2392            .push_callback_effect(
2393                CallbackId::new("on_tick"),
2394                CallbackEffectKind::Publishes,
2395                EntityId::new("pub_chatter"),
2396            )
2397            .unwrap();
2398        assert_eq!(
2399            recorder.callback_effects()[0].callback_slot,
2400            Some(CallbackSlot::new(1))
2401        );
2402        assert_eq!(
2403            recorder.callback_effects()[0].entity_slot,
2404            Some(EntitySlot::new(0))
2405        );
2406    }
2407
2408    #[test]
2409    fn recorder_assigns_distinct_callback_slots_within_one_action_entity() {
2410        let mut recorder = MetadataRecorder::<1, 1, 3>::new();
2411        recorder
2412            .push_node(NodeId::new("node"), "action_node", "/", 0)
2413            .unwrap();
2414        let mut action = entity_metadata(EntityMetadataSpec {
2415            id: EntityId::new("act_count"),
2416            node_id: NodeId::new("node"),
2417            kind: EntityKind::ActionServer,
2418            source_name: "/count",
2419            type_name: "example_interfaces::action::dds_::Fibonacci_",
2420            type_hash: "hash",
2421            qos: qos::DEFAULT,
2422        })
2423        .unwrap();
2424        action.callback_id = Some(copy_str("on_goal").unwrap());
2425        action.action_cancel_callback_id = Some(copy_str("on_cancel").unwrap());
2426        action.action_accepted_callback_id = Some(copy_str("on_accepted").unwrap());
2427
2428        recorder.push_entity(action).unwrap();
2429
2430        assert_eq!(
2431            recorder.entities()[0].callback_slot,
2432            Some(CallbackSlot::new(0))
2433        );
2434        assert_eq!(
2435            recorder.entities()[0].action_cancel_callback_slot,
2436            Some(CallbackSlot::new(1))
2437        );
2438        assert_eq!(
2439            recorder.entities()[0].action_accepted_callback_slot,
2440            Some(CallbackSlot::new(2))
2441        );
2442    }
2443
2444    #[cfg(feature = "alloc")]
2445    #[test]
2446    fn source_metadata_json_uses_agent_a_schema_shape() {
2447        // 7 entity slots, not 5: issue 0900 added the two CLIENT kinds to this
2448        // fixture. The recorder is fixed-capacity by design (`no_std`, static
2449        // storage), so a new entity here is a deliberate widening.
2450        let mut recorder = MetadataRecorder::<1, 7, 1>::new();
2451        recorder
2452            .push_node(NodeId::new("node_talker"), "talker", "/", 0)
2453            .unwrap();
2454        recorder
2455            .push_entity(
2456                entity_metadata(EntityMetadataSpec {
2457                    id: EntityId::new("pub_chatter"),
2458                    node_id: NodeId::new("node_talker"),
2459                    kind: EntityKind::Publisher,
2460                    source_name: "chatter",
2461                    type_name: "std_msgs::msg::dds_::String_",
2462                    type_hash: "hash",
2463                    qos: crate::qos::DEFAULT,
2464                })
2465                .unwrap(),
2466            )
2467            .unwrap();
2468        let mut timer = entity_metadata(EntityMetadataSpec {
2469            id: EntityId::new("timer_publish"),
2470            node_id: NodeId::new("node_talker"),
2471            kind: EntityKind::Timer,
2472            source_name: "",
2473            type_name: "",
2474            type_hash: "",
2475            qos: crate::qos::DEFAULT,
2476        })
2477        .unwrap();
2478        timer.callback_id = Some(copy_str("cb_timer").unwrap());
2479        timer.callback_source = SourceLocationMetadata {
2480            artifact: copy_str("src/talker.rs").unwrap(),
2481            line: Some(42),
2482            column: Some(5),
2483        };
2484        timer.period_ms = Some(100);
2485        recorder.push_entity(timer).unwrap();
2486        let mut param = entity_metadata(EntityMetadataSpec {
2487            id: EntityId::new("param_rate"),
2488            node_id: NodeId::new("node_talker"),
2489            kind: EntityKind::Parameter,
2490            source_name: "rate_hz",
2491            type_name: "",
2492            type_hash: "",
2493            qos: crate::qos::DEFAULT,
2494        })
2495        .unwrap();
2496        param.parameter_type = Some(ParameterType::Integer);
2497        param.parameter_default = Some(ParameterDefault::Integer(10));
2498        param.source = SourceLocationMetadata {
2499            artifact: copy_str("src/talker.rs").unwrap(),
2500            line: Some(25),
2501            column: Some(9),
2502        };
2503        recorder.push_entity(param).unwrap();
2504        let mut action = entity_metadata(EntityMetadataSpec {
2505            id: EntityId::new("act_count"),
2506            node_id: NodeId::new("node_talker"),
2507            kind: EntityKind::ActionServer,
2508            source_name: "~/count",
2509            type_name: "example_interfaces::action::dds_::Fibonacci_",
2510            type_hash: "hash",
2511            qos: crate::qos::DEFAULT,
2512        })
2513        .unwrap();
2514        action.callback_id = Some(copy_str("cb_count_goal").unwrap());
2515        action.callback_source = SourceLocationMetadata {
2516            artifact: copy_str("src/talker.rs").unwrap(),
2517            line: Some(90),
2518            column: Some(5),
2519        };
2520        action.action_cancel_callback_id = Some(copy_str("cb_count_cancel").unwrap());
2521        action.action_cancel_source = SourceLocationMetadata {
2522            artifact: copy_str("src/talker.rs").unwrap(),
2523            line: Some(96),
2524            column: Some(5),
2525        };
2526        action.action_accepted_callback_id = Some(copy_str("cb_count_accepted").unwrap());
2527        action.action_accepted_source = SourceLocationMetadata {
2528            artifact: copy_str("src/talker.rs").unwrap(),
2529            line: Some(104),
2530            column: Some(5),
2531        };
2532        recorder.push_entity(action).unwrap();
2533        recorder
2534            .push_callback_effect(
2535                CallbackId::new("cb_timer"),
2536                CallbackEffectKind::Publishes,
2537                EntityId::new("pub_chatter"),
2538            )
2539            .unwrap();
2540
2541        // Issue 0900 — one of each client kind, on the node that also SERVES
2542        // (it owns the action server above), so this would catch a writer that
2543        // filtered by node rather than by kind.
2544        recorder
2545            .push_entity(
2546                entity_metadata(EntityMetadataSpec {
2547                    id: EntityId::new("client_fib"),
2548                    node_id: NodeId::new("node_talker"),
2549                    kind: EntityKind::ActionClient,
2550                    source_name: "/fibonacci",
2551                    type_name: "example_interfaces::action::dds_::Fibonacci_",
2552                    type_hash: "hash",
2553                    qos: crate::qos::DEFAULT,
2554                })
2555                .unwrap(),
2556            )
2557            .unwrap();
2558        recorder
2559            .push_entity(
2560                entity_metadata(EntityMetadataSpec {
2561                    id: EntityId::new("client_add"),
2562                    node_id: NodeId::new("node_talker"),
2563                    kind: EntityKind::ServiceClient,
2564                    source_name: "/add_two_ints",
2565                    type_name: "example_interfaces::srv::dds_::AddTwoInts_",
2566                    type_hash: "hash",
2567                    qos: crate::qos::DEFAULT,
2568                })
2569                .unwrap(),
2570            )
2571            .unwrap();
2572
2573        let json = recorder
2574            .to_source_metadata_json(
2575                &SourceMetadataExport::new("demo_nodes_rs", "talker")
2576                    .executable("talker")
2577                    .exported_symbol("nros_node_talker")
2578                    .source_artifacts(&["src/talker.rs"]),
2579            )
2580            .unwrap();
2581
2582        // READ, not restated: the schema is ADDITIVE, so the shape this asserts
2583        // is a claim about the CURRENT version. phase-457 W3 moved it to 3 and
2584        // this literal is what noticed.
2585        assert!(
2586            json.contains(&format!("\"version\":{SOURCE_METADATA_SCHEMA_VERSION}")),
2587            "the current schema version, got {json}"
2588        );
2589        assert!(json.contains("\"language\":\"rust\""));
2590        assert!(json.contains("\"unresolved_name\":{\"value\":\"talker\",\"kind\":\"relative\"}"));
2591        assert!(json.contains(
2592            "\"interface\":{\"package\":\"std_msgs\",\"name\":\"msg/String\",\"kind\":\"message\"}"
2593        ));
2594        assert!(json.contains("\"kind\":\"publishes\",\"entity\":\"pub_chatter\""));
2595        assert!(
2596            json.contains("\"source\":{\"artifact\":\"src/talker.rs\",\"line\":42,\"column\":5}")
2597        );
2598        // v2: the declared type sits between the name and the default.
2599        assert!(
2600            json.contains(
2601                "\"name\":\"rate_hz\",\"type\":\"integer\",\"default\":10,\"read_only\":false"
2602            ),
2603            "got {json}"
2604        );
2605        assert!(json.contains("\"goal_callback\":\"cb_count_goal\""));
2606        assert!(json.contains("\"cancel_callback\":\"cb_count_cancel\""));
2607        assert!(json.contains("\"accepted_callback\":\"cb_count_accepted\""));
2608        assert!(json.contains("\"kind\":\"action_cancel\""));
2609        assert!(json.contains("\"kind\":\"action_accepted\""));
2610
2611        // Issue 0900 — the CLIENT halves must reach the JSON, not just the
2612        // recorder. `record_entity` always captured them and the writer dropped
2613        // them, so the sidecar described only what a component SERVES. The
2614        // executor arena is sized from the client count, so the omission cost
2615        // bytes on a task stack and not merely description.
2616        //
2617        // Asserted on the SERIALISED form rather than on `recorder.entities()`:
2618        // the defect was entirely in the writer, so a test that stops at the
2619        // recorder passes against the broken tree — the vacuous shape this repo
2620        // keeps finding.
2621        assert!(
2622            json.contains("\"action_clients\":[{"),
2623            "an action client must reach the sidecar, got {json}"
2624        );
2625        assert!(
2626            json.contains("\"service_clients\":[{"),
2627            "a service client must reach the sidecar, got {json}"
2628        );
2629        // Scoped to the client ARRAYS, not to the whole document. The first
2630        // version of these asserts searched all of `json` and passed against a
2631        // broken emitter: this fixture's action SERVER carries the same
2632        // Fibonacci interface, so "the string appears somewhere" was true
2633        // whatever `write_client_json` did. A test that cannot fail is the
2634        // shape `check-no-vacuous-tests` exists to catch.
2635        let action_clients = &json[json.find("\"action_clients\":").expect("array present")..];
2636        let action_clients = &action_clients[..action_clients.find(']').unwrap()];
2637        let service_clients = &json[json.find("\"service_clients\":").expect("array present")..];
2638        let service_clients = &service_clients[..service_clients.find(']').unwrap()];
2639
2640        // The interface must be PARSED, not echoed as a Rust path. `write_
2641        // client_json` shares `write_interface` with the server writers, and
2642        // `parse_interface` only splits the 4-segment DDS-mangled form — which
2643        // is what `A::ACTION_NAME` actually supplies. Pinning the parsed shape
2644        // is what would catch a client writer that bypassed that helper.
2645        assert!(
2646            action_clients.contains(
2647                "\"interface\":{\"package\":\"example_interfaces\",\"name\":\"action/Fibonacci\",\"kind\":\"action\"}"
2648            ),
2649            "action client interface must be parsed, got {action_clients}"
2650        );
2651        assert!(
2652            service_clients.contains(
2653                "\"interface\":{\"package\":\"example_interfaces\",\"name\":\"srv/AddTwoInts\",\"kind\":\"service\"}"
2654            ),
2655            "service client interface must be parsed, got {service_clients}"
2656        );
2657        // The KIND word is the only thing `write_client_json` branches on, so
2658        // the two arrays must not agree on it.
2659        assert!(
2660            !action_clients.contains("\"kind\":\"service\"")
2661                && !service_clients.contains("\"kind\":\"action\""),
2662            "the client kind word is what distinguishes the arrays"
2663        );
2664        // A client registers no callbacks, so it must carry none of the server
2665        // writers' callback fields.
2666        assert!(
2667            !action_clients.contains("callback") && !service_clients.contains("callback"),
2668            "a client registers no callback; emitting one would misdescribe it"
2669        );
2670        assert!(json.contains("\"generator\":\"nros-metadata-rust\""));
2671    }
2672
2673    /// RFC-0128 D2 (phase-554 W2.b) -- the sidecar states `lifecycle` for
2674    /// exactly the node whose code registered, in both directions: the
2675    /// registered node carries it, the plain one does not, and a
2676    /// registration naming no recorded node is refused rather than dropped.
2677    #[cfg(feature = "alloc")]
2678    #[test]
2679    fn only_the_node_whose_code_registered_a_machine_is_stated_managed() {
2680        let mut recorder = MetadataRecorder::<2, 1, 1>::new();
2681        recorder
2682            .push_node(NodeId::new("plain"), "talker", "/", 0)
2683            .unwrap();
2684        recorder
2685            .push_node(NodeId::new("coded"), "managed", "/demo", 0)
2686            .unwrap();
2687
2688        // Nothing observed: no node is stated managed.
2689        let json = recorder
2690            .to_source_metadata_json(&SourceMetadataExport::new("p", "c"))
2691            .unwrap();
2692        assert!(
2693            !json.contains("\"lifecycle\""),
2694            "nothing registered, got {json}"
2695        );
2696
2697        // The executor names the namespace as its node table holds it; the
2698        // join ignores leading/trailing `/` the way `managed_node_id` does.
2699        assert!(recorder.observe_lifecycle_registration("managed", "/demo/"));
2700        assert!(
2701            !recorder.observe_lifecycle_registration("ghost", "/"),
2702            "a registration naming no recorded node is refused"
2703        );
2704        assert!(
2705            !recorder.observe_lifecycle_registration("managed", "/"),
2706            "the namespace is part of the key"
2707        );
2708
2709        let json = recorder
2710            .to_source_metadata_json(&SourceMetadataExport::new("p", "c"))
2711            .unwrap();
2712        assert_eq!(json.matches("\"lifecycle\":true").count(), 1, "got {json}");
2713        let coded = json.find("\"id\":\"coded\"").unwrap();
2714        let mark = json.find("\"lifecycle\":true").unwrap();
2715        let plain = json.find("\"id\":\"plain\"").unwrap();
2716        assert!(
2717            plain < coded && coded < mark,
2718            "the mark is on the coded node's row, got {json}"
2719        );
2720    }
2721
2722    /// Issue 2689 -- the GOLDEN probe sidecar the CLI parses.
2723    ///
2724    /// The producer (this crate) and the reader (`nros-cli-core`'s
2725    /// `SourceMetadata`, `deny_unknown_fields`) share no cargo workspace, so a
2726    /// schema bump here was invisible to every test there: issue 2650's v6
2727    /// keys made every sidecar fail the CLI's parse, and so read as stale on
2728    /// every configure. The file is the bridge. This test writes it with the
2729    /// REAL serializer over a recorder holding every row kind and every
2730    /// optional key the writer can emit, and fails when the output differs;
2731    /// the CLI's `golden_probe_sidecar_round_trips_through_source_metadata`
2732    /// parses it strictly. A new key or a changed type on this side fails one
2733    /// of the two. `NROS_BLESS_PROBE_SIDECAR=1` rewrites the file; commit the
2734    /// result with the CLI's mirror updated in the same change.
2735    #[cfg(feature = "alloc")]
2736    #[test]
2737    fn the_golden_probe_sidecar_is_what_the_recorder_writes() {
2738        extern crate std;
2739
2740        let mut recorder = MetadataRecorder::<2, 12, 2>::new();
2741        recorder
2742            .push_node(NodeId::new("node_planner"), "planner", "/demo", 0)
2743            .unwrap();
2744        recorder
2745            .push_node(NodeId::new("node_plain"), "plain", "/", 0)
2746            .unwrap();
2747        // v5: a node whose own code registered a lifecycle state machine.
2748        assert!(recorder.observe_lifecycle_registration("planner", "/demo"));
2749
2750        let spec = |id: &'static str, kind, source_name, type_name| EntityMetadataSpec {
2751            id: EntityId::new(id),
2752            node_id: NodeId::new("node_planner"),
2753            kind,
2754            source_name,
2755            type_name,
2756            type_hash: "hash",
2757            qos: crate::qos::DEFAULT,
2758        };
2759        let at = |line| SourceLocationMetadata {
2760            artifact: copy_str("src/planner.cpp").unwrap(),
2761            line: Some(line),
2762            column: Some(5),
2763        };
2764
2765        recorder
2766            .push_entity(
2767                entity_metadata(spec(
2768                    "pub_path",
2769                    EntityKind::Publisher,
2770                    "path",
2771                    "nav_msgs::msg::dds_::Path_",
2772                ))
2773                .unwrap(),
2774            )
2775            .unwrap();
2776
2777        // v3/v4: a subscription the executor observed registering, with its
2778        // `in_place` and `buffered` facts, in a named callback group.
2779        let mut sub = entity_metadata(spec(
2780            "sub_odom",
2781            EntityKind::Subscription,
2782            "/odom",
2783            "nav_msgs::msg::dds_::Odometry_",
2784        ))
2785        .unwrap();
2786        sub.callback_id = Some(copy_str("cb_odom").unwrap());
2787        sub.callback_source = at(30);
2788        sub.callback_group = Some(copy_str("sensors").unwrap());
2789        recorder.push_entity(sub).unwrap();
2790        assert!(recorder.observe_subscription_registration(
2791            "/odom",
2792            "nav_msgs::msg::dds_::Odometry_",
2793            true,
2794            BufferedRow::TypedBound,
2795        ));
2796
2797        let mut timer = entity_metadata(spec("timer_plan", EntityKind::Timer, "", "")).unwrap();
2798        timer.callback_id = Some(copy_str("cb_plan").unwrap());
2799        timer.callback_source = at(40);
2800        timer.period_ms = Some(33);
2801        timer.period_us = Some(33_333);
2802        recorder.push_entity(timer).unwrap();
2803
2804        // v2: a guard condition is a `timers[]` row of its own kind.
2805        let mut guard = entity_metadata(spec("guard_wake", EntityKind::Timer, "", "")).unwrap();
2806        guard.callback_id = Some(copy_str("cb_wake").unwrap());
2807        guard.callback_source = at(45);
2808        guard.timer_kind = TimerKind::GuardCondition;
2809        recorder.push_entity(guard).unwrap();
2810
2811        let mut srv = entity_metadata(spec(
2812            "srv_reset",
2813            EntityKind::ServiceServer,
2814            "~/reset",
2815            "std_srvs::srv::dds_::Trigger_",
2816        ))
2817        .unwrap();
2818        srv.callback_id = Some(copy_str("cb_reset").unwrap());
2819        srv.callback_source = at(50);
2820        recorder.push_entity(srv).unwrap();
2821
2822        let mut action = entity_metadata(spec(
2823            "act_route",
2824            EntityKind::ActionServer,
2825            "route",
2826            "example_interfaces::action::dds_::Fibonacci_",
2827        ))
2828        .unwrap();
2829        action.callback_id = Some(copy_str("cb_route_goal").unwrap());
2830        action.callback_source = at(60);
2831        action.action_cancel_callback_id = Some(copy_str("cb_route_cancel").unwrap());
2832        action.action_cancel_source = at(61);
2833        action.action_accepted_callback_id = Some(copy_str("cb_route_accepted").unwrap());
2834        action.action_accepted_source = at(62);
2835        recorder.push_entity(action).unwrap();
2836
2837        recorder
2838            .push_entity(
2839                entity_metadata(spec(
2840                    "client_fib",
2841                    EntityKind::ActionClient,
2842                    "/fibonacci",
2843                    "example_interfaces::action::dds_::Fibonacci_",
2844                ))
2845                .unwrap(),
2846            )
2847            .unwrap();
2848        recorder
2849            .push_entity(
2850                entity_metadata(spec(
2851                    "client_add",
2852                    EntityKind::ServiceClient,
2853                    "/add_two_ints",
2854                    "example_interfaces::srv::dds_::AddTwoInts_",
2855                ))
2856                .unwrap(),
2857            )
2858            .unwrap();
2859
2860        let mut declared =
2861            entity_metadata(spec("param_rate", EntityKind::Parameter, "rate_hz", "")).unwrap();
2862        declared.parameter_type = Some(ParameterType::Double);
2863        declared.parameter_default = Some(ParameterDefault::Double(copy_str("30.0").unwrap()));
2864        declared.parameter_read_only = true;
2865        declared.source = at(20);
2866        recorder.push_entity(declared).unwrap();
2867
2868        // Issue 2589: a parameter the code READ by name, not declared.
2869        let mut read =
2870            entity_metadata(spec("param_period", EntityKind::Parameter, "period_ms", "")).unwrap();
2871        read.parameter_read = true;
2872        read.source = at(21);
2873        recorder.push_entity(read).unwrap();
2874
2875        recorder
2876            .push_callback_effect(
2877                CallbackId::new("cb_plan"),
2878                CallbackEffectKind::Publishes,
2879                EntityId::new("pub_path"),
2880            )
2881            .unwrap();
2882
2883        // v6 (issue 2650): the probe watched descriptor prose.
2884        recorder.arm_descriptor_text();
2885        recorder.observe_descriptor_text(false, 42);
2886        recorder.observe_descriptor_text(true, 7);
2887        // v7 (issue 2964): the probe watched every declaration route.
2888        recorder.arm_parameter_declarations();
2889
2890        let json = recorder
2891            .to_source_metadata_json(
2892                &SourceMetadataExport::new("demo_planner", "planner")
2893                    .language("cpp")
2894                    .executable("planner_node")
2895                    .exported_symbol("nros_component_planner")
2896                    .source_artifacts(&["src/planner.cpp"]),
2897            )
2898            .unwrap();
2899        let json = std::format!("{json}\n");
2900
2901        let golden = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2902            .join("../../cli/nros-cli-core/tests/fixtures/orchestration/probe_sidecar_golden.json");
2903        if std::env::var_os("NROS_BLESS_PROBE_SIDECAR").is_some() {
2904            std::fs::write(&golden, &json).unwrap();
2905        }
2906        let committed = std::fs::read_to_string(&golden).unwrap_or_else(|e| {
2907            panic!(
2908                "{}: {e} -- the golden sidecar moved; update this path",
2909                golden.display()
2910            )
2911        });
2912        assert_eq!(
2913            committed,
2914            json,
2915            "the recorder's output moved off the golden sidecar {}. Re-run with \
2916             NROS_BLESS_PROBE_SIDECAR=1, and teach the CLI's SourceMetadata \
2917             (packages/cli/nros-cli-core/src/orchestration/source_metadata.rs) \
2918             any new key in the same change (issue 2689)",
2919            golden.display()
2920        );
2921        // Some rows only a set field produces: their VALUES, not just keys.
2922        for row in [
2923            "\"lifecycle\":true",
2924            "\"in_place\":true",
2925            "\"buffered\":\"typed_bound\"",
2926            "\"kind\":\"guard_condition\"",
2927            "\"read\":true",
2928            "\"action_clients\":[{",
2929            "\"service_clients\":[{",
2930            "\"parameter_description_max_len\":42,",
2931            "\"parameter_constraints_max_len\":7,",
2932            "\"parameter_declarations_watched\":true,",
2933        ] {
2934            assert!(
2935                json.contains(row),
2936                "the golden must carry {row}, got {json}"
2937            );
2938        }
2939
2940        // EVERY key the writer can emit is in the golden, derived from the
2941        // writer's own source text, never a hand list: a key this test's
2942        // recorder never sets would otherwise be absent from the golden, and
2943        // the CLI would never see it -- issue 2689's exact shape.
2944        let keys = writer_keys(include_str!("node_metadata.rs"));
2945        assert!(
2946            keys.len() >= 50,
2947            "the writer scan found only {} keys ({keys:?}); the writer's \
2948             spelling moved, so teach `writer_keys` it",
2949            keys.len()
2950        );
2951        let missing: std::vec::Vec<&str> = keys
2952            .iter()
2953            .map(std::string::String::as_str)
2954            .filter(|k| !json.contains(&std::format!("\"{k}\":")))
2955            .collect();
2956        assert!(
2957            missing.is_empty(),
2958            "writer key(s) {missing:?} are absent from the golden sidecar: set \
2959             them on this test's recorder and re-bless, so the CLI's strict \
2960             parse sees them (issue 2689)"
2961        );
2962    }
2963
2964    /// Every JSON object key the sidecar writer spells, read from its source
2965    /// text above `mod tests` (comment lines skipped): an escaped literal
2966    /// `\"key\":` inside a `write!` format string, or the first string
2967    /// argument of a `write_*(out, "key", ...)` helper call
2968    /// (`write_json_field`, `write_json_opt_field`, `write_optional_ms`,
2969    /// `write_entity_array`, ...). Issue 2689.
2970    #[cfg(feature = "alloc")]
2971    fn writer_keys(source: &str) -> std::collections::BTreeSet<std::string::String> {
2972        extern crate std;
2973        use std::string::String;
2974
2975        let writer = &source[..source
2976            .find("\nmod tests {")
2977            .expect("the tests module marker")];
2978        let code: String = writer
2979            .lines()
2980            .filter(|l| !l.trim_start().starts_with("//"))
2981            .flat_map(|l| [l, "\n"])
2982            .collect();
2983        let is_key = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_';
2984        let mut keys = std::collections::BTreeSet::new();
2985
2986        // `\"key\":` -- the backslash-escaped quotes of a format string.
2987        let mut rest = code.as_str();
2988        while let Some(at) = rest.find("\\\"") {
2989            rest = &rest[at + 2..];
2990            let end = rest.find(|c: char| !is_key(c)).unwrap_or(rest.len());
2991            if end > 0 && rest[end..].starts_with("\\\":") {
2992                keys.insert(String::from(&rest[..end]));
2993            }
2994        }
2995
2996        // `write_<x>(out, "key"` -- whitespace (rustfmt's line breaks) allowed.
2997        let mut rest = code.as_str();
2998        while let Some(at) = rest.find("write_") {
2999            rest = &rest[at + "write_".len()..];
3000            let name_end = rest.find(|c: char| !is_key(c)).unwrap_or(rest.len());
3001            let args = rest[name_end..].trim_start();
3002            let Some(args) = args.strip_prefix('(') else {
3003                continue;
3004            };
3005            let Some(args) = args.trim_start().strip_prefix("out") else {
3006                continue;
3007            };
3008            let Some(args) = args.trim_start().strip_prefix(',') else {
3009                continue;
3010            };
3011            let Some(args) = args.trim_start().strip_prefix('"') else {
3012                continue;
3013            };
3014            let end = args.find(|c: char| !is_key(c)).unwrap_or(args.len());
3015            if end > 0 && args[end..].starts_with('"') {
3016                keys.insert(String::from(&args[..end]));
3017            }
3018        }
3019        keys
3020    }
3021}