matter-interaction 0.4.0

Matter Interaction Model message framing: invoke, read, and write request/response encoding.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
//! `InvokeRequestMessage` / `InvokeResponseMessage` framing — Matter §10.7.

#![forbid(unsafe_code)]

use crate::error::ImError;
use crate::path::CommandPath;
use crate::status::ImStatus;
use crate::{expect_message_struct, skip_container, IM_REVISION};
use matter_codec::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value};

/// Write a `CommandPathIB` (a TLV **list**: 0=endpoint, 1=cluster,
/// 2=command) under `tag`.
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub(crate) fn write_command_path(w: &mut TlvWriter<'_>, tag: Tag, path: CommandPath) {
    w.start_list(tag).expect("infallible: vec writer");
    w.put_uint(Tag::Context(0), u64::from(path.endpoint))
        .expect("infallible: vec writer");
    w.put_uint(Tag::Context(1), u64::from(path.cluster))
        .expect("infallible: vec writer");
    w.put_uint(Tag::Context(2), u64::from(path.command))
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer");
}

/// Build an `InvokeRequestMessage` carrying a single command.
///
/// `command_fields_tlv` is the already-encoded command-fields struct
/// (e.g. the output of `crate::noc::encode_csr_request`); it is embedded
/// verbatim as the `CommandFields` member. `SuppressResponse` and
/// `TimedRequest` are both `false`.
///
/// # Panics
///
/// Panics if `command_fields_tlv` is not a valid anonymous-tagged TLV
/// element (i.e. not the output of a codec encode call). The function is
/// otherwise infallible; `Vec`-backed `TlvWriter` never fails.
#[must_use]
pub fn build_invoke_request(path: CommandPath, command_fields_tlv: &[u8]) -> Vec<u8> {
    build_invoke_request_inner(path, command_fields_tlv, false, false)
}

/// Like [`build_invoke_request`] but sets `TimedRequest = true` — the action half
/// of a timed interaction, sent on the same exchange after a `TimedRequest`
/// message (see [`crate::build_timed_request`]).
///
/// # Panics
///
/// As [`build_invoke_request`] (invalid `command_fields_tlv`).
#[must_use]
pub fn build_invoke_request_timed(path: CommandPath, command_fields_tlv: &[u8]) -> Vec<u8> {
    build_invoke_request_inner(path, command_fields_tlv, true, false)
}

/// Like [`build_invoke_request`] but sets `SuppressResponse = true` — the form
/// used for **group** (multicast) invokes. Group commands are unacknowledged at
/// the IM layer: there is no return path for a multicast send, so the request
/// must instruct the receiving devices to suppress any `InvokeResponse`
/// (Matter Core Spec §8.9.2 / §10.7.2 — group commands carry `SuppressResponse`).
/// `TimedRequest` is `false` (timed interactions are not available on group
/// sends).
///
/// # Panics
///
/// As [`build_invoke_request`] (invalid `command_fields_tlv`).
#[must_use]
pub fn build_invoke_request_group(path: CommandPath, command_fields_tlv: &[u8]) -> Vec<u8> {
    build_invoke_request_inner(path, command_fields_tlv, false, true)
}

#[allow(clippy::expect_used)] // Vec-backed TlvWriter is infallible.
fn build_invoke_request_inner(
    path: CommandPath,
    command_fields_tlv: &[u8],
    timed: bool,
    suppress_response: bool,
) -> Vec<u8> {
    let mut buf = Vec::with_capacity(48 + command_fields_tlv.len());
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_bool(Tag::Context(0), suppress_response)
        .expect("infallible: vec writer"); // SuppressResponse
    w.put_bool(Tag::Context(1), timed)
        .expect("infallible: vec writer"); // TimedRequest
    w.start_array(Tag::Context(2))
        .expect("infallible: vec writer"); // InvokeRequests
    {
        w.start_structure(Tag::Anonymous)
            .expect("infallible: vec writer"); // CommandDataIB
        write_command_path(&mut w, Tag::Context(0), path);
        w.put_preencoded(Tag::Context(1), command_fields_tlv)
            .expect("infallible: caller passes a valid anonymous-tagged struct");
        w.end_container().expect("infallible: vec writer"); // CommandDataIB
    }
    w.end_container().expect("infallible: vec writer"); // InvokeRequests array
    w.put_uint(Tag::Context(0xFF), u64::from(IM_REVISION))
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer"); // message struct
    buf
}

/// Build an `InvokeRequestMessage` carrying **multiple** commands, each tagged
/// with a sequential `CommandRef` (`CommandDataIB` tag 2) so the device's
/// responses can be matched back. `SuppressResponse` and `TimedRequest` are
/// `false`. Each tuple is `(path, command_fields_tlv)`, the fields an
/// anonymous-tagged TLV blob (e.g. a `matter-clusters` command encoder output).
///
/// NB: the wire format permits a batch, but a device only accepts more than one
/// command if it advertises `MaxPathsPerInvoke > 1` in its `SessionParameters`;
/// the controller-side gating is deferred (M9-B5 scope) — callers must respect it.
///
/// # Panics
///
/// As [`build_invoke_request`] (a `command_fields_tlv` that is not a valid
/// anonymous-tagged TLV element).
#[must_use]
#[allow(clippy::expect_used)] // Vec-backed TlvWriter is infallible.
pub fn build_invoke_request_batch(commands: &[(CommandPath, &[u8])]) -> Vec<u8> {
    let mut buf = Vec::with_capacity(32 + commands.iter().map(|c| 32 + c.1.len()).sum::<usize>());
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_bool(Tag::Context(0), false)
        .expect("infallible: vec writer"); // SuppressResponse
    w.put_bool(Tag::Context(1), false)
        .expect("infallible: vec writer"); // TimedRequest
    w.start_array(Tag::Context(2))
        .expect("infallible: vec writer"); // InvokeRequests
    for (i, (path, fields)) in commands.iter().enumerate() {
        w.start_structure(Tag::Anonymous)
            .expect("infallible: vec writer"); // CommandDataIB
        write_command_path(&mut w, Tag::Context(0), *path);
        w.put_preencoded(Tag::Context(1), fields)
            .expect("infallible: caller passes a valid anonymous-tagged struct");
        // CommandRef (tag 2): the index. `try_from` is total for any realistic
        // batch; cap defensively rather than panic on an absurd one.
        let cref = u16::try_from(i).unwrap_or(u16::MAX);
        w.put_uint(Tag::Context(2), u64::from(cref))
            .expect("infallible: vec writer");
        w.end_container().expect("infallible: vec writer"); // CommandDataIB
    }
    w.end_container().expect("infallible: vec writer"); // InvokeRequests array
    w.put_uint(Tag::Context(0xFF), u64::from(IM_REVISION))
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer"); // message struct
    buf
}

/// Outcome of parsing a single-command `InvokeResponseMessage`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InvokeResponse {
    /// The device returned a response command. `fields_tlv` is the
    /// re-anonymised `CommandFields` struct, ready to hand to
    /// `Commissioner::on_response`.
    Command {
        /// Path of the response command (`(endpoint, cluster, command)`).
        path: CommandPath,
        /// The device's original `CommandFields` bytes, **verbatim**, under
        /// a fresh anonymous tag: only the container's own control/tag bytes
        /// are replaced, the body is copied unexamined. Original integer
        /// widths are preserved, and so is everything else the device sent —
        /// which has three consequences for consumers:
        ///
        /// - A localized-string suffix (element type `0x1F`, IS1) survives in
        ///   the blob rather than being dropped by a re-encode. Decoded
        ///   `Value`s are unchanged: the downstream decoder still truncates at
        ///   the IS1 separator.
        /// - Invalid UTF-8 inside `CommandFields` is **not** rejected here —
        ///   the copy never decodes it — so it surfaces from your own decoder
        ///   instead of from IM parsing.
        /// - An off-spec `Array` whose children carry non-anonymous tags is
        ///   copied through as-is and fails in your decoder with
        ///   `NonAnonymousArrayTag`; the older decode-then-re-encode path
        ///   silently normalised those tags away.
        fields_tlv: Vec<u8>,
    },
    /// The device returned a bare status (no response command payload).
    Status(ImStatus),
}

/// One parsed `InvokeResponseIB` from a batched response, with its `CommandRef`
/// (`CommandDataIB` / `CommandStatusIB` tag 2) for matching to the request command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InvokeResponseEntry {
    /// The `CommandRef` echoed by the device, if present.
    pub command_ref: Option<u16>,
    /// The response: a command payload or a status.
    pub response: InvokeResponse,
}

/// Copy the body of the container whose `ContainerStart` was just returned
/// (reader positioned right after it) under a fresh **anonymous** header of
/// the same kind. The copied span excludes the original element's control
/// and tag bytes and includes its end-of-container marker, so the result is
/// a standalone anonymous-tagged TLV blob with the device's original byte
/// widths preserved verbatim.
///
/// The copied bytes are NOT UTF-8-revalidated here: string payloads inside
/// the span pass through verbatim, and validation defers to whatever decoder
/// eventually consumes the blob.
///
/// # Errors
///
/// Any error from [`TlvReader::skip_container_span`] — including its
/// precondition: the immediately preceding `next()` must have returned the
/// `ContainerStart` being retagged. After an error the reader state is
/// unspecified; abandon the parse.
#[allow(clippy::expect_used)] // Vec-backed TlvWriter is infallible (repo idiom).
pub(crate) fn retag_container_anonymous(
    r: &mut TlvReader<'_>,
    kind: ContainerKind,
) -> Result<Vec<u8>, ImError> {
    let span = r.skip_container_span().map_err(ImError::Codec)?;
    let body = r.span_bytes(span.body());
    let mut out = Vec::with_capacity(1 + body.len());
    {
        let mut w = TlvWriter::new(&mut out);
        match kind {
            ContainerKind::Structure => w.start_structure(Tag::Anonymous),
            ContainerKind::Array => w.start_array(Tag::Anonymous),
            // List and any future non-exhaustive kinds re-emit as a list,
            // mirroring read_container_value's fallback.
            _ => w.start_list(Tag::Anonymous),
        }
        .expect("infallible: vec writer");
    }
    out.extend_from_slice(body);
    Ok(out)
}

/// An anonymous empty structure (`0x15 0x18`) — the canonical stand-in when
/// a `CommandDataIB` carries no `CommandFields` member, so callers always
/// receive a valid TLV blob.
#[allow(clippy::expect_used)] // Vec-backed TlvWriter is infallible (repo idiom).
fn empty_anonymous_struct() -> Vec<u8> {
    let mut out = Vec::with_capacity(2);
    {
        let mut w = TlvWriter::new(&mut out);
        w.start_structure(Tag::Anonymous)
            .expect("infallible: vec writer");
        w.end_container().expect("infallible: vec writer");
    }
    out
}

/// Consume a `CommandPathIB` list body (reader positioned just after the
/// list's `ContainerStart`) into a [`CommandPath`], without materialising
/// the members.
pub(crate) fn command_path_from_reader(r: &mut TlvReader<'_>) -> Result<CommandPath, ImError> {
    let mut endpoint = None;
    let mut cluster = None;
    let mut command = None;
    loop {
        match r.next()? {
            None => {
                return Err(ImError::Codec(matter_codec::Error::UnclosedContainer));
            }
            Some(Element::ContainerEnd) => break,
            Some(Element::Scalar {
                tag: Tag::Context(0),
                value: Value::Uint(n),
            }) => {
                endpoint =
                    Some(u16::try_from(n).map_err(|_| {
                        ImError::UnexpectedValue("CommandPath.endpoint exceeds u16")
                    })?);
            }
            Some(Element::Scalar {
                tag: Tag::Context(1),
                value: Value::Uint(n),
            }) => {
                cluster =
                    Some(u32::try_from(n).map_err(|_| {
                        ImError::UnexpectedValue("CommandPath.cluster exceeds u32")
                    })?);
            }
            Some(Element::Scalar {
                tag: Tag::Context(2),
                value: Value::Uint(n),
            }) => {
                command =
                    Some(u32::try_from(n).map_err(|_| {
                        ImError::UnexpectedValue("CommandPath.command exceeds u32")
                    })?);
            }
            Some(Element::ContainerStart { .. }) => crate::skip_container(r)?,
            Some(_) => {}
        }
    }
    Ok(CommandPath {
        endpoint: endpoint.ok_or(ImError::MissingField("CommandPath.endpoint"))?,
        cluster: cluster.ok_or(ImError::MissingField("CommandPath.cluster"))?,
        command: command.ok_or(ImError::MissingField("CommandPath.command"))?,
    })
}

/// Parse a single-command `InvokeResponseMessage`.
///
/// Reads the first `InvokeResponseIB` in the `InvokeResponses` array and
/// returns either its response-command payload or its status. Additional
/// `InvokeResponseIB`s (not produced by commissioning) are ignored.
///
/// # Errors
///
/// Returns [`ImError`] if the message is not a struct, lacks the
/// `InvokeResponses` array, or the first IB has neither Command nor Status.
pub fn parse_invoke_response(bytes: &[u8]) -> Result<InvokeResponse, ImError> {
    let mut r = TlvReader::new(bytes);
    expect_message_struct(&mut r)?;

    loop {
        match r.next()? {
            None | Some(Element::ContainerEnd) => {
                return Err(ImError::MissingField("InvokeResponses"))
            }
            Some(Element::ContainerStart {
                tag: Tag::Context(1),
                kind: ContainerKind::Array,
            }) => break,
            Some(Element::ContainerStart { .. }) => skip_container(&mut r)?,
            Some(_) => {}
        }
    }

    match r.next()? {
        Some(Element::ContainerStart {
            kind: ContainerKind::Structure,
            ..
        }) => {}
        _ => return Err(ImError::MissingField("InvokeResponseIB")),
    }

    loop {
        match r.next()? {
            None | Some(Element::ContainerEnd) => return Err(ImError::EmptyInvokeResponse),
            Some(Element::ContainerStart {
                tag: Tag::Context(0),
                kind: ContainerKind::Structure,
            }) => {
                return parse_command_data(&mut r).map(|(path, fields)| InvokeResponse::Command {
                    path,
                    fields_tlv: fields,
                });
            }
            Some(Element::ContainerStart {
                tag: Tag::Context(1),
                kind: ContainerKind::Structure,
            }) => {
                return parse_command_status(&mut r).map(InvokeResponse::Status);
            }
            Some(Element::ContainerStart { .. }) => skip_container(&mut r)?,
            Some(_) => {}
        }
    }
}

/// Parse a multi-command `InvokeResponseMessage`: every `InvokeResponseIB`, each
/// with its `CommandRef`. The single-command [`parse_invoke_response`] is retained
/// for the commissioning path (reads only the first IB, ignores `CommandRef`).
///
/// # Errors
///
/// Returns [`ImError`] if the message is not a struct, lacks the
/// `InvokeResponses` array, or an IB has neither Command nor Status.
pub fn parse_invoke_response_batch(bytes: &[u8]) -> Result<Vec<InvokeResponseEntry>, ImError> {
    let mut r = TlvReader::new(bytes);
    expect_message_struct(&mut r)?;
    // Advance to the InvokeResponses array (context tag 1).
    loop {
        match r.next()? {
            None | Some(Element::ContainerEnd) => {
                return Err(ImError::MissingField("InvokeResponses"))
            }
            Some(Element::ContainerStart {
                tag: Tag::Context(1),
                kind: ContainerKind::Array,
            }) => break,
            Some(Element::ContainerStart { .. }) => skip_container(&mut r)?,
            Some(_) => {}
        }
    }
    let mut out = Vec::new();
    loop {
        match r.next()? {
            None => return Err(ImError::Codec(matter_codec::Error::UnclosedContainer)),
            Some(Element::ContainerEnd) => return Ok(out), // end of array
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => out.push(parse_invoke_response_ib(&mut r)?),
            Some(Element::ContainerStart { .. }) => skip_container(&mut r)?,
            Some(_) => {}
        }
    }
}

/// Parse one `InvokeResponseIB` body into an [`InvokeResponseEntry`] (reader
/// positioned just after its struct start). Drains the **entire** IB (through its
/// matching `ContainerEnd`) so the caller's array walk stays in sync.
fn parse_invoke_response_ib(r: &mut TlvReader<'_>) -> Result<InvokeResponseEntry, ImError> {
    let mut entry: Option<InvokeResponseEntry> = None;
    loop {
        match r.next()? {
            None => return Err(ImError::Codec(matter_codec::Error::UnclosedContainer)),
            Some(Element::ContainerEnd) => break, // end of this InvokeResponseIB
            // Command = CommandDataIB
            Some(Element::ContainerStart {
                tag: Tag::Context(0),
                kind: ContainerKind::Structure,
            }) => {
                let (path, fields, command_ref) = parse_command_data_ref(r)?;
                entry = Some(InvokeResponseEntry {
                    command_ref,
                    response: InvokeResponse::Command {
                        path,
                        fields_tlv: fields,
                    },
                });
            }
            // Status = CommandStatusIB
            Some(Element::ContainerStart {
                tag: Tag::Context(1),
                kind: ContainerKind::Structure,
            }) => {
                let (status, command_ref) = parse_command_status_ref(r)?;
                entry = Some(InvokeResponseEntry {
                    command_ref,
                    response: InvokeResponse::Status(status),
                });
            }
            Some(Element::ContainerStart { .. }) => skip_container(r)?,
            Some(_) => {}
        }
    }
    entry.ok_or(ImError::EmptyInvokeResponse)
}

/// Parse a `CommandDataIB` body (reader positioned just after its struct
/// start), returning `(path, anonymous-tagged CommandFields bytes)`. The single-
/// command path ignores the `CommandRef`; [`parse_command_data_ref`] captures it.
fn parse_command_data(r: &mut TlvReader<'_>) -> Result<(CommandPath, Vec<u8>), ImError> {
    let (path, fields, _ref) = parse_command_data_ref(r)?;
    Ok((path, fields))
}

/// Like [`parse_command_data`] but also captures the `CommandRef` (tag 2).
fn parse_command_data_ref(
    r: &mut TlvReader<'_>,
) -> Result<(CommandPath, Vec<u8>, Option<u16>), ImError> {
    let mut path = None;
    let mut fields = Vec::new();
    let mut command_ref = None;
    loop {
        match r.next()? {
            None => return Err(ImError::MissingField("CommandDataIB.body")),
            Some(Element::ContainerEnd) => break,
            Some(Element::ContainerStart {
                tag: Tag::Context(0),
                kind: ContainerKind::List,
            }) => {
                path = Some(command_path_from_reader(r)?);
            }
            Some(Element::ContainerStart {
                tag: Tag::Context(1),
                kind,
            }) => {
                fields = retag_container_anonymous(r, kind)?;
            }
            // CommandRef (tag 2), a scalar uint.
            Some(Element::Scalar {
                tag: Tag::Context(2),
                value: Value::Uint(n),
            }) => command_ref = u16::try_from(n).ok(),
            Some(Element::ContainerStart { .. }) => skip_container(r)?,
            Some(_) => {}
        }
    }
    // If no CommandFields member was present, `fields` is an empty Vec, which
    // is not valid TLV. Canonicalize to an anonymous empty struct so callers
    // always receive a valid TLV blob.
    let fields = if fields.is_empty() {
        empty_anonymous_struct()
    } else {
        fields
    };
    Ok((
        path.ok_or(ImError::MissingField("CommandDataIB.CommandPath"))?,
        fields,
        command_ref,
    ))
}

/// Parse a `CommandStatusIB` body, returning the `StatusIB.Status` mapped
/// to [`ImStatus`]. The single-command path ignores the `CommandRef`;
/// [`parse_command_status_ref`] captures it.
fn parse_command_status(r: &mut TlvReader<'_>) -> Result<ImStatus, ImError> {
    let (status, _ref) = parse_command_status_ref(r)?;
    Ok(status)
}

/// Like [`parse_command_status`] but also captures the `CommandRef` (tag 2).
fn parse_command_status_ref(r: &mut TlvReader<'_>) -> Result<(ImStatus, Option<u16>), ImError> {
    // `None` ⇒ the Status member was never seen (genuinely missing).
    // `Some(raw)` ⇒ the member was present; `raw` is the verbatim wire value,
    // which we range-check to a `u8` only after the parse loop so an
    // out-of-range value reports as `InvalidStatusCode`, not `MissingField`.
    let mut status: Option<u64> = None;
    let mut command_ref = None;
    loop {
        match r.next()? {
            None => return Err(ImError::MissingField("CommandStatusIB.body")),
            Some(Element::ContainerEnd) => break,
            Some(Element::ContainerStart {
                tag: Tag::Context(1),
                kind: ContainerKind::Structure,
            }) => {
                // StatusIB body: last Status (ctx 0) wins; range-checked to u8
                // only after the parse loop (see `status` doc above).
                loop {
                    match r.next()? {
                        None => return Err(ImError::Codec(matter_codec::Error::UnclosedContainer)),
                        Some(Element::ContainerEnd) => break,
                        Some(Element::Scalar {
                            tag: Tag::Context(0),
                            value: Value::Uint(n),
                        }) => status = Some(n),
                        Some(Element::ContainerStart { .. }) => skip_container(r)?,
                        Some(_) => {}
                    }
                }
            }
            // CommandRef (tag 2), a scalar uint.
            Some(Element::Scalar {
                tag: Tag::Context(2),
                value: Value::Uint(n),
            }) => command_ref = u16::try_from(n).ok(),
            Some(Element::ContainerStart { .. }) => skip_container(r)?,
            Some(_) => {}
        }
    }
    let raw = status.ok_or(ImError::MissingField("StatusIB.Status"))?;
    let code = u8::try_from(raw).map_err(|_| ImError::InvalidStatusCode { code: raw })?;
    Ok((ImStatus::from_u8(code), command_ref))
}

#[cfg(test)]
mod tests {
    // Test-code carve-out: see CLAUDE.md.
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;
    use matter_codec::{ContainerKind, Element, Tag, TlvReader, Value};

    #[test]
    fn invoke_request_has_expected_structure() {
        // ArmFailSafe-like: endpoint 0, cluster 0x0030, command 0x00,
        // command fields = an empty anonymous struct (0x15 0x18).
        let fields = vec![0x15, 0x18];
        let bytes = build_invoke_request(
            CommandPath {
                endpoint: 0,
                cluster: 0x0030,
                command: 0x00,
            },
            &fields,
        );

        let mut r = TlvReader::new(&bytes);
        // Top-level InvokeRequestMessage struct (anonymous).
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::ContainerStart {
                tag: Tag::Anonymous,
                kind: ContainerKind::Structure
            })
        ));
        // SuppressResponse = false.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::Scalar {
                tag: Tag::Context(0),
                value: Value::Bool(false)
            })
        ));
        // TimedRequest = false.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::Scalar {
                tag: Tag::Context(1),
                value: Value::Bool(false)
            })
        ));
        // InvokeRequests array start.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::ContainerStart {
                tag: Tag::Context(2),
                kind: ContainerKind::Array
            })
        ));
        // CommandDataIB anonymous struct start.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::ContainerStart {
                tag: Tag::Anonymous,
                kind: ContainerKind::Structure
            })
        ));
        // CommandPathIB list at context tag 0.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::ContainerStart {
                tag: Tag::Context(0),
                kind: ContainerKind::List
            })
        ));
        // Endpoint = 0 at context tag 0.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::Scalar {
                tag: Tag::Context(0),
                value: Value::Uint(0)
            })
        ));
        // Cluster = 0x0030 at context tag 1.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::Scalar {
                tag: Tag::Context(1),
                value: Value::Uint(0x0030)
            })
        ));
        // Command = 0x00 at context tag 2.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::Scalar {
                tag: Tag::Context(2),
                value: Value::Uint(0)
            })
        ));
        // End CommandPathIB list.
        assert!(matches!(r.next().unwrap(), Some(Element::ContainerEnd)));
        // CommandFields (empty struct) at context tag 1 — ContainerStart then end.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::ContainerStart {
                tag: Tag::Context(1),
                kind: ContainerKind::Structure
            })
        ));
        assert!(matches!(r.next().unwrap(), Some(Element::ContainerEnd)));
        // End CommandDataIB struct.
        assert!(matches!(r.next().unwrap(), Some(Element::ContainerEnd)));
        // End InvokeRequests array.
        assert!(matches!(r.next().unwrap(), Some(Element::ContainerEnd)));
        // InteractionModelRevision = IM_REVISION at context tag 0xFF.
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::Scalar { tag: Tag::Context(0xFF), value: Value::Uint(v) })
                if v == u64::from(IM_REVISION)
        ));
        // End top-level struct.
        assert!(matches!(r.next().unwrap(), Some(Element::ContainerEnd)));
        // No more elements.
        assert!(r.next().unwrap().is_none());
    }

    #[test]
    fn invoke_request_carries_command_path_and_fields() {
        // `put_preencoded` re-tags the anonymous-struct control byte (0x15)
        // to a context-1 struct (0x35 0x01), then appends the body (0x18).
        // Verify that the re-tagged representation [0x35, 0x01, 0x18] is
        // present in the output (i.e. the fields blob was embedded).
        let fields = vec![0x15u8, 0x18]; // anonymous empty struct
        let bytes = build_invoke_request(
            CommandPath {
                endpoint: 1,
                cluster: 0x0031,
                command: 0x06,
            },
            &fields,
        );
        // Retagged form: context-1 struct start (0x35, 0x01) then body (0x18).
        let retagged = [0x35u8, 0x01, 0x18];
        assert!(
            bytes.windows(retagged.len()).any(|w| w == retagged),
            "command fields not embedded (expected retagged bytes {retagged:02X?} in {bytes:02X?})",
        );
    }

    #[test]
    fn parses_command_response_payload() {
        use matter_codec::{Tag, TlvWriter};
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap(); // SuppressResponse
        w.start_array(Tag::Context(1)).unwrap(); // InvokeResponses
        {
            w.start_structure(Tag::Anonymous).unwrap(); // InvokeResponseIB
            w.start_structure(Tag::Context(0)).unwrap(); // Command = CommandDataIB
            w.start_list(Tag::Context(0)).unwrap(); // CommandPath
            w.put_uint(Tag::Context(0), 0).unwrap();
            w.put_uint(Tag::Context(1), 0x0030).unwrap();
            w.put_uint(Tag::Context(2), 0x05).unwrap();
            w.end_container().unwrap();
            w.start_structure(Tag::Context(1)).unwrap(); // CommandFields (empty)
            w.end_container().unwrap();
            w.end_container().unwrap(); // CommandDataIB
            w.end_container().unwrap(); // InvokeResponseIB
        }
        w.end_container().unwrap(); // array
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        let parsed = parse_invoke_response(&buf).unwrap();
        match parsed {
            InvokeResponse::Command { path, fields_tlv } => {
                assert_eq!(path.endpoint, 0);
                assert_eq!(path.cluster, 0x0030);
                assert_eq!(path.command, 0x05);
                assert_eq!(fields_tlv, vec![0x15, 0x18]); // re-anonymised empty struct
            }
            InvokeResponse::Status(_) => panic!("expected Command, got Status"),
        }
    }

    #[test]
    fn parses_command_with_nonempty_fields() {
        use matter_codec::{Tag, TlvWriter};

        // Build the expected anonymous struct bytes independently for comparison:
        // anonymous struct containing one scalar: Context(0) = 0x2A (uint).
        let mut expected_buf = Vec::new();
        {
            let mut w = TlvWriter::new(&mut expected_buf);
            w.start_structure(Tag::Anonymous).unwrap();
            w.put_uint(Tag::Context(0), 0x2A).unwrap();
            w.end_container().unwrap();
        }

        // Build an InvokeResponseMessage whose CommandFields is that same struct.
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap(); // SuppressResponse
        w.start_array(Tag::Context(1)).unwrap(); // InvokeResponses
        {
            w.start_structure(Tag::Anonymous).unwrap(); // InvokeResponseIB
            w.start_structure(Tag::Context(0)).unwrap(); // CommandDataIB
            w.start_list(Tag::Context(0)).unwrap(); // CommandPath
            w.put_uint(Tag::Context(0), 1).unwrap(); // endpoint
            w.put_uint(Tag::Context(1), 0x0050).unwrap(); // cluster
            w.put_uint(Tag::Context(2), 0x01).unwrap(); // command
            w.end_container().unwrap(); // CommandPath
                                        // CommandFields at Context(1): a struct with one member
            w.start_structure(Tag::Context(1)).unwrap();
            w.put_uint(Tag::Context(0), 0x2A).unwrap();
            w.end_container().unwrap(); // CommandFields
            w.end_container().unwrap(); // CommandDataIB
            w.end_container().unwrap(); // InvokeResponseIB
        }
        w.end_container().unwrap(); // array
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        let parsed = parse_invoke_response(&buf).unwrap();
        match parsed {
            InvokeResponse::Command { path, fields_tlv } => {
                assert_eq!(path.endpoint, 1);
                assert_eq!(path.cluster, 0x0050);
                assert_eq!(path.command, 0x01);
                assert_eq!(
                    fields_tlv, expected_buf,
                    "fields_tlv should decode to the same struct content as the original"
                );
            }
            InvokeResponse::Status(_) => panic!("expected Command, got Status"),
        }
    }

    #[test]
    fn rejects_out_of_range_endpoint() {
        use crate::error::ImError;
        use matter_codec::{Tag, TlvWriter};

        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap();
        w.start_array(Tag::Context(1)).unwrap();
        {
            w.start_structure(Tag::Anonymous).unwrap(); // InvokeResponseIB
            w.start_structure(Tag::Context(0)).unwrap(); // CommandDataIB
            w.start_list(Tag::Context(0)).unwrap(); // CommandPath
            w.put_uint(Tag::Context(0), 0x0001_0000).unwrap(); // endpoint exceeds u16
            w.put_uint(Tag::Context(1), 0x0030).unwrap();
            w.put_uint(Tag::Context(2), 0x00).unwrap();
            w.end_container().unwrap();
            w.start_structure(Tag::Context(1)).unwrap(); // CommandFields (empty)
            w.end_container().unwrap();
            w.end_container().unwrap(); // CommandDataIB
            w.end_container().unwrap(); // InvokeResponseIB
        }
        w.end_container().unwrap();
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        let result = parse_invoke_response(&buf);
        assert!(
            matches!(result, Err(ImError::UnexpectedValue(_))),
            "expected UnexpectedValue for out-of-range endpoint, got {result:?}"
        );
    }

    #[test]
    fn empty_invoke_responses_array_errors() {
        use crate::error::ImError;
        use matter_codec::{Tag, TlvWriter};

        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap();
        w.start_array(Tag::Context(1)).unwrap(); // empty InvokeResponses array
        w.end_container().unwrap();
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        let result = parse_invoke_response(&buf);
        assert!(
            matches!(result, Err(ImError::MissingField(_))),
            "expected MissingField for empty InvokeResponses, got {result:?}"
        );
    }

    #[test]
    fn parses_status_response() {
        use matter_codec::{Tag, TlvWriter};
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap();
        w.start_array(Tag::Context(1)).unwrap();
        {
            w.start_structure(Tag::Anonymous).unwrap(); // InvokeResponseIB
            w.start_structure(Tag::Context(1)).unwrap(); // Status = CommandStatusIB
            w.start_list(Tag::Context(0)).unwrap(); // CommandPath
            w.put_uint(Tag::Context(0), 0).unwrap();
            w.put_uint(Tag::Context(1), 0x0030).unwrap();
            w.put_uint(Tag::Context(2), 0x00).unwrap();
            w.end_container().unwrap();
            w.start_structure(Tag::Context(1)).unwrap(); // StatusIB
            w.put_uint(Tag::Context(0), 0x01).unwrap(); // Status = FAILURE
            w.end_container().unwrap();
            w.end_container().unwrap(); // CommandStatusIB
            w.end_container().unwrap(); // InvokeResponseIB
        }
        w.end_container().unwrap();
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        let parsed = parse_invoke_response(&buf).unwrap();
        assert!(matches!(
            parsed,
            InvokeResponse::Status(ImStatus::Failure(0x01))
        ));
    }

    /// Build an `InvokeResponseMessage` whose single `InvokeResponseIB` carries
    /// a `CommandStatusIB`. `status` controls the `StatusIB.Status` member:
    /// `Some(v)` writes that raw uint, `None` omits the member entirely.
    fn invoke_status_response(status: Option<u64>) -> Vec<u8> {
        use matter_codec::{Tag, TlvWriter};
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap();
        w.start_array(Tag::Context(1)).unwrap();
        w.start_structure(Tag::Anonymous).unwrap(); // InvokeResponseIB
        w.start_structure(Tag::Context(1)).unwrap(); // Status = CommandStatusIB
        w.start_list(Tag::Context(0)).unwrap(); // CommandPath
        w.put_uint(Tag::Context(0), 0).unwrap();
        w.put_uint(Tag::Context(1), 0x0030).unwrap();
        w.put_uint(Tag::Context(2), 0x00).unwrap();
        w.end_container().unwrap();
        w.start_structure(Tag::Context(1)).unwrap(); // StatusIB
        if let Some(v) = status {
            w.put_uint(Tag::Context(0), v).unwrap();
        }
        w.end_container().unwrap();
        w.end_container().unwrap(); // CommandStatusIB
        w.end_container().unwrap(); // InvokeResponseIB
        w.end_container().unwrap(); // array
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();
        buf
    }

    #[test]
    fn command_status_out_of_range_is_invalid_status_code() {
        // StatusIB.Status = 0x100 — present on the wire but exceeds the single
        // octet a Matter status code occupies. Must surface as the distinct
        // InvalidStatusCode error, NOT MissingField.
        let buf = invoke_status_response(Some(0x100));
        match parse_invoke_response(&buf) {
            Err(ImError::InvalidStatusCode { code }) => assert_eq!(code, 0x100),
            other => panic!("expected InvalidStatusCode {{ code: 0x100 }}, got {other:?}"),
        }
    }

    #[test]
    fn command_status_valid_code_still_parses() {
        let buf = invoke_status_response(Some(0x88));
        assert!(matches!(
            parse_invoke_response(&buf),
            Ok(InvokeResponse::Status(ImStatus::Failure(0x88)))
        ));
    }

    #[test]
    fn command_status_missing_field_still_missing_field() {
        // No Status member at all — genuinely missing, so MissingField is right.
        let buf = invoke_status_response(None);
        assert!(matches!(
            parse_invoke_response(&buf),
            Err(ImError::MissingField("StatusIB.Status"))
        ));
    }

    #[test]
    fn invoke_response_ib_with_no_command_or_status_errors() {
        use matter_codec::{Tag, TlvWriter};
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap();
        w.start_array(Tag::Context(1)).unwrap(); // InvokeResponses
        w.start_structure(Tag::Anonymous).unwrap(); // InvokeResponseIB with no Command/Status
        w.put_uint(Tag::Context(7), 0).unwrap(); // unrelated field
        w.end_container().unwrap();
        w.end_container().unwrap(); // array
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        assert!(matches!(
            parse_invoke_response(&buf),
            Err(ImError::EmptyInvokeResponse)
        ));
    }

    #[test]
    fn batch_request_carries_command_refs() {
        let fields = vec![0x15u8, 0x18]; // anonymous empty struct
        let bytes = build_invoke_request_batch(&[
            (
                CommandPath {
                    endpoint: 1,
                    cluster: 0x06,
                    command: 0x02,
                },
                &fields,
            ),
            (
                CommandPath {
                    endpoint: 2,
                    cluster: 0x06,
                    command: 0x00,
                },
                &fields,
            ),
        ]);
        // The InvokeRequests array (ctx 2) holds two CommandDataIB structs, each
        // ending with CommandRef (ctx 2) = 0 then 1. Parse the whole thing back
        // through the batch response parser shape is not applicable (this is a
        // request), so just confirm both refs appear in order in the stream.
        let mut r = TlvReader::new(&bytes);
        let mut refs = Vec::new();
        let mut depth = 0i32;
        while let Some(el) = r.next().unwrap() {
            match el {
                Element::ContainerStart { .. } => depth += 1,
                Element::ContainerEnd => depth -= 1,
                // CommandRef sits at depth 2 (struct > array > CommandDataIB), tag 2.
                Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Uint(n),
                } if depth == 3 => refs.push(n),
                _ => {}
            }
        }
        assert_eq!(refs, vec![0, 1], "CommandRefs must be 0 then 1");
    }

    #[test]
    fn command_fields_preserve_device_integer_widths() {
        // Device encodes CommandFields with a NON-minimal width (uint16 42).
        // Span-copy + retag must return those bytes verbatim under a fresh
        // anonymous tag — the old Value round-trip collapsed them to uint8.
        // Hand-assembled fields: anon struct { ctx0: uint16 0x2A } =
        // [0x15, 0x25, 0x00, 0x2A, 0x00, 0x18]; embedded at ctx1 via
        // put_preencoded (which keeps the body bytes verbatim).
        let nonminimal_fields = [0x15u8, 0x25, 0x00, 0x2A, 0x00, 0x18];
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap();
        w.start_array(Tag::Context(1)).unwrap();
        w.start_structure(Tag::Anonymous).unwrap(); // InvokeResponseIB
        w.start_structure(Tag::Context(0)).unwrap(); // CommandDataIB
        w.start_list(Tag::Context(0)).unwrap();
        w.put_uint(Tag::Context(0), 0).unwrap();
        w.put_uint(Tag::Context(1), 0x0030).unwrap();
        w.put_uint(Tag::Context(2), 0x05).unwrap();
        w.end_container().unwrap();
        w.put_preencoded(Tag::Context(1), &nonminimal_fields)
            .unwrap();
        w.end_container().unwrap();
        w.end_container().unwrap();
        w.end_container().unwrap();
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        match parse_invoke_response(&buf).unwrap() {
            InvokeResponse::Command { fields_tlv, .. } => {
                assert_eq!(
                    fields_tlv, nonminimal_fields,
                    "device widths must be preserved verbatim"
                );
            }
            InvokeResponse::Status(_) => panic!("expected Command"),
        }
    }

    #[test]
    fn batch_response_parses_all_ibs_with_refs() {
        use matter_codec::{Tag, TlvWriter};
        // Two InvokeResponseIBs: a Command (ref 0) and a Status (ref 1).
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap(); // SuppressResponse
        w.start_array(Tag::Context(1)).unwrap(); // InvokeResponses
        {
            // IB 1: Command = CommandDataIB { path, fields(empty), ref=0 }
            w.start_structure(Tag::Anonymous).unwrap();
            w.start_structure(Tag::Context(0)).unwrap(); // Command
            w.start_list(Tag::Context(0)).unwrap();
            w.put_uint(Tag::Context(0), 1).unwrap();
            w.put_uint(Tag::Context(1), 0x06).unwrap();
            w.put_uint(Tag::Context(2), 0x02).unwrap();
            w.end_container().unwrap();
            w.start_structure(Tag::Context(1)).unwrap();
            w.end_container().unwrap(); // empty fields
            w.put_uint(Tag::Context(2), 0).unwrap(); // CommandRef
            w.end_container().unwrap(); // Command
            w.end_container().unwrap(); // IB 1
                                        // IB 2: Status = CommandStatusIB { path, status=SUCCESS, ref=1 }
            w.start_structure(Tag::Anonymous).unwrap();
            w.start_structure(Tag::Context(1)).unwrap(); // Status
            w.start_list(Tag::Context(0)).unwrap();
            w.put_uint(Tag::Context(0), 2).unwrap();
            w.put_uint(Tag::Context(1), 0x06).unwrap();
            w.put_uint(Tag::Context(2), 0x00).unwrap();
            w.end_container().unwrap();
            w.start_structure(Tag::Context(1)).unwrap(); // StatusIB
            w.put_uint(Tag::Context(0), 0).unwrap(); // SUCCESS
            w.end_container().unwrap();
            w.put_uint(Tag::Context(2), 1).unwrap(); // CommandRef
            w.end_container().unwrap(); // Status
            w.end_container().unwrap(); // IB 2
        }
        w.end_container().unwrap(); // array
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        let entries = parse_invoke_response_batch(&buf).unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].command_ref, Some(0));
        assert!(matches!(
            entries[0].response,
            InvokeResponse::Command { ref path, .. } if path.endpoint == 1 && path.command == 0x02
        ));
        assert_eq!(entries[1].command_ref, Some(1));
        assert_eq!(
            entries[1].response,
            InvokeResponse::Status(ImStatus::Success)
        );

        // Back-compat: the single-command parser reads the first IB only.
        match parse_invoke_response(&buf).unwrap() {
            InvokeResponse::Command { path, .. } => assert_eq!(path.endpoint, 1),
            InvokeResponse::Status(_) => panic!("expected the first IB (a Command)"),
        }
    }

    /// Drive `command_path_from_reader` over a writer-built `CommandPathIB`.
    fn parse_cmd_path(build: impl FnOnce(&mut TlvWriter<'_>)) -> Result<CommandPath, ImError> {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_list(Tag::Anonymous).unwrap();
        build(&mut w);
        w.end_container().unwrap();
        let mut r = TlvReader::new(&buf);
        assert!(matches!(
            r.next().unwrap(),
            Some(Element::ContainerStart { .. })
        ));
        command_path_from_reader(&mut r)
    }

    #[test]
    fn command_path_parses_members_and_errors() {
        let p = parse_cmd_path(|w| {
            w.put_uint(Tag::Context(0), 1).unwrap();
            w.put_uint(Tag::Context(1), 6).unwrap();
            w.put_uint(Tag::Context(2), 2).unwrap();
        })
        .unwrap();
        assert_eq!((p.endpoint, p.cluster, p.command), (1, 6, 2));

        assert!(matches!(
            parse_cmd_path(|w| {
                w.put_uint(Tag::Context(0), 1).unwrap();
                w.put_uint(Tag::Context(1), 6).unwrap();
            }),
            Err(ImError::MissingField("CommandPath.command"))
        ));

        assert!(matches!(
            parse_cmd_path(|w| {
                w.put_uint(Tag::Context(0), u64::from(u16::MAX) + 1)
                    .unwrap();
                w.put_uint(Tag::Context(1), 6).unwrap();
                w.put_uint(Tag::Context(2), 2).unwrap();
            }),
            Err(ImError::UnexpectedValue(_))
        ));
    }

    #[test]
    fn empty_command_fields_fallback_to_anonymous_empty_struct() {
        // Same shape as `parses_command_response_payload`, but the CommandFields
        // (ctx1) member is OMITTED entirely — exercises the fallback at
        // `parse_command_data_ref` that canonicalizes an absent CommandFields to
        // the anonymous empty struct `[0x15, 0x18]`.
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_bool(Tag::Context(0), false).unwrap(); // SuppressResponse
        w.start_array(Tag::Context(1)).unwrap(); // InvokeResponses
        {
            w.start_structure(Tag::Anonymous).unwrap(); // InvokeResponseIB
            w.start_structure(Tag::Context(0)).unwrap(); // Command = CommandDataIB
            w.start_list(Tag::Context(0)).unwrap(); // CommandPath
            w.put_uint(Tag::Context(0), 0).unwrap();
            w.put_uint(Tag::Context(1), 0x0030).unwrap();
            w.put_uint(Tag::Context(2), 0x05).unwrap();
            w.end_container().unwrap();
            // No CommandFields (ctx1) member at all.
            w.end_container().unwrap(); // CommandDataIB
            w.end_container().unwrap(); // InvokeResponseIB
        }
        w.end_container().unwrap(); // array
        w.put_uint(Tag::Context(0xFF), 11).unwrap();
        w.end_container().unwrap();

        let parsed = parse_invoke_response(&buf).unwrap();
        match parsed {
            InvokeResponse::Command { fields_tlv, .. } => {
                assert_eq!(fields_tlv, vec![0x15, 0x18]);
            }
            InvokeResponse::Status(_) => panic!("expected Command, got Status"),
        }
    }
}