prikk-object 0.23.0

Prikk object identity, canonical encoding, and object payload types.
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
//! Payload tests.

mod path_validation;
mod proptest_decoders;

use super::{
    AttestationPayload, AttestationStatus, BlobKind, BlobPayload, BlockKind, BlockPayload,
    EditText, MerkleRoot, Operation, OperationKind, PatchPayload, PatchPurpose, PluginResultEntry,
    RECOGNITION_CLAIM_MAX_PATCH_IDS, REF_STATE_CLOSED_SCHEMA, RecognitionClaimPayload, RefKind,
    RefStatePayload, RefUpdatePayload, TagPayload, text_span_hash, validate_text_anchor_id,
};
use crate::{CanonicalEncode, CanonicalWriter, ObjectId, ObjectType, WireType};

#[test]
fn text_anchor_ids_are_validated() {
    assert!(validate_text_anchor_id("anchor-1").is_ok());
    assert!(validate_text_anchor_id("").is_err());
    assert!(validate_text_anchor_id("with space").is_err());
}

#[test]
fn text_span_hash_is_stable() {
    let a = text_span_hash(b"hello");
    let b = text_span_hash(b"hello");
    let c = text_span_hash(b"world");
    assert_eq!(a, b);
    assert_ne!(a, c);
}

#[test]
fn edit_text_rejects_hash_binding_violation() {
    // FDD-03 §9.3: old_span_hash must equal SHA-256(old_span_text).
    let op = EditText {
        node_id: crate::NodeId::from_bytes([0x22; 32]),
        span_id: [0x10; 32],
        old_span_hash: [0x00; 32], // wrong: not SHA-256(old_span_text)
        left_anchor_hash: [0x11; 32],
        right_anchor_hash: [0x12; 32],
        replacement_text: b"hello".to_vec(),
        presentation_hint_line: None,
        presentation_hint_column: None,
        old_span_text: b"old".to_vec(),
    };
    assert!(op.validate().is_err());
    assert!(op.to_canonical_bytes().is_err());
}

#[test]
fn patch_operations_must_be_contiguous() {
    let patch = PatchPayload {
        operations: vec![Operation {
            op_seq: 2,
            op_id: None,
            preconditions: Vec::new(),
            kind: OperationKind::EditText(EditText {
                node_id: crate::NodeId::from_bytes([0x22; 32]),
                span_id: [0x10; 32],
                old_span_hash: text_span_hash(b"old"),
                left_anchor_hash: [0x11; 32],
                right_anchor_hash: [0x12; 32],
                replacement_text: b"hello".to_vec(),
                presentation_hint_line: None,
                presentation_hint_column: None,
                old_span_text: b"old".to_vec(),
            }),
        }],
        parent_patch_ids: Vec::new(),
        intent: None,
        preconditions: Vec::new(),
        purpose: PatchPurpose::Normal,
    };
    assert!(patch.to_canonical_bytes().is_err());
}

#[test]
fn blob_payload_has_stable_object_id() {
    let payload = BlobPayload::new(BlobKind::Text, b"hello".to_vec());
    let bytes_a = payload.to_canonical_bytes();
    let bytes_b = payload.to_canonical_bytes();
    assert_eq!(bytes_a, bytes_b);
    if let Ok(bytes) = bytes_a {
        let id_a = ObjectId::from_canonical_payload(ObjectType::Blob, 1, &bytes);
        let id_b = ObjectId::from_canonical_payload(ObjectType::Blob, 1, &bytes);
        assert_eq!(id_a, id_b);
    }
}

#[test]
fn ref_state_payload_decodes_its_canonical_bytes() {
    let target = ObjectId::from_canonical_payload(ObjectType::Block, 1, b"block");
    let previous = ObjectId::from_canonical_payload(ObjectType::RefState, 1, b"prev");
    let payload = RefStatePayload {
        ref_name: "heads/main".to_string(),
        kind: RefKind::Branch,
        target_object_id: target,
        update_seq: 2,
        previous_ref_state_id: Some(previous),
        required_attestation_ids: Vec::new(),
        closed: false,
    };
    let bytes = payload.to_canonical_bytes();
    assert!(bytes.is_ok());
    if let Ok(bytes) = bytes {
        let decoded = RefStatePayload::decode_canonical(&bytes, 1);
        assert_eq!(decoded, Ok(payload));
    }
}

/// DC-61 identity claim: an ordinary (open) RefState's canonical bytes carry no trace of field 7
/// at all, structurally — not merely "round-trips," which would also pass for an accidentally
/// emitted `false`. Tag 7 as a big-endian `u16` never appears in the byte stream.
#[allow(clippy::expect_used)]
#[test]
fn ref_state_payload_open_encoding_carries_no_field_seven() {
    let target = ObjectId::from_canonical_payload(ObjectType::Block, 1, b"block");
    let payload = RefStatePayload {
        ref_name: "heads/main".to_string(),
        kind: RefKind::Branch,
        target_object_id: target,
        update_seq: 2,
        previous_ref_state_id: None,
        required_attestation_ids: Vec::new(),
        closed: false,
    };
    let bytes = payload.to_canonical_bytes().expect("open payload encodes");
    let tag_seven = 7_u16.to_be_bytes();
    assert!(
        !bytes.windows(2).any(|window| window == tag_seven),
        "open RefState bytes must not contain a field-7 tag anywhere: {bytes:02x?}"
    );
}

/// The closed counterpart: field 7 is present and its wire-encoded value is exactly `true` (byte
/// `0x01`), never emitted as an explicit `false`.
#[allow(clippy::expect_used)]
#[test]
fn ref_state_payload_closed_encoding_carries_field_seven_true() {
    let target = ObjectId::from_canonical_payload(ObjectType::Block, 1, b"block");
    let payload = RefStatePayload {
        ref_name: "heads/main".to_string(),
        kind: RefKind::Branch,
        target_object_id: target,
        update_seq: 2,
        previous_ref_state_id: None,
        required_attestation_ids: Vec::new(),
        closed: true,
    };
    let bytes = payload
        .to_canonical_bytes()
        .expect("closed payload encodes");
    // tag(2) + wire_type(1) + len(8) + value(1) = 12 trailing bytes: 00 07 01 00..00 01 01
    let mut expected_tail = Vec::new();
    expected_tail.extend_from_slice(&7_u16.to_be_bytes());
    expected_tail.push(WireType::Bool as u8);
    expected_tail.extend_from_slice(&1_u64.to_be_bytes());
    expected_tail.push(1); // true
    assert!(
        bytes.ends_with(&expected_tail),
        "closed RefState bytes must end with an explicit tag-7 true field: {bytes:02x?}"
    );

    let schema_2 = RefStatePayload::decode_canonical(&bytes, REF_STATE_CLOSED_SCHEMA);
    assert_eq!(schema_2, Ok(payload));
}

/// Field 7 is schema-gated: legal only at `REF_STATE_CLOSED_SCHEMA` and above. A schema-1 reader
/// encountering it — the format-transition claim DC-61 makes — must reject it outright.
#[allow(clippy::expect_used)]
#[test]
fn ref_state_payload_rejects_closed_field_at_schema_one() {
    let target = ObjectId::from_canonical_payload(ObjectType::Block, 1, b"block");
    let payload = RefStatePayload {
        ref_name: "heads/main".to_string(),
        kind: RefKind::Branch,
        target_object_id: target,
        update_seq: 2,
        previous_ref_state_id: None,
        required_attestation_ids: Vec::new(),
        closed: true,
    };
    let bytes = payload
        .to_canonical_bytes()
        .expect("closed payload encodes");
    assert!(
        RefStatePayload::decode_canonical(&bytes, 1).is_err(),
        "a schema-1 reader must reject a payload carrying field 7"
    );
}

/// Canonical encoding must have exactly one representation of "closed": absent, never an explicit
/// `false`. A hand-crafted payload spelling "not closed" via `tag 7 = false` must be rejected even
/// at schema 2, the same discipline `patch_purpose_explicit_normal_is_rejected` applies to
/// `PatchPurpose`.
#[allow(clippy::expect_used)]
#[test]
fn ref_state_payload_rejects_explicit_false_closed_field() {
    let target = ObjectId::from_canonical_payload(ObjectType::Block, 1, b"block");
    let open = RefStatePayload {
        ref_name: "heads/main".to_string(),
        kind: RefKind::Branch,
        target_object_id: target,
        update_seq: 2,
        previous_ref_state_id: None,
        required_attestation_ids: Vec::new(),
        closed: false,
    };
    let mut bytes = open.to_canonical_bytes().expect("open payload encodes");
    // Hand-append an explicit tag-7 false field after the legitimate open encoding.
    bytes.extend_from_slice(&7_u16.to_be_bytes());
    bytes.push(WireType::Bool as u8);
    bytes.extend_from_slice(&1_u64.to_be_bytes());
    bytes.push(0); // false
    assert!(
        RefStatePayload::decode_canonical(&bytes, REF_STATE_CLOSED_SCHEMA).is_err(),
        "an explicit tag-7 false must be rejected, not accepted as a second spelling of open"
    );
}

#[test]
fn block_payload_decodes_its_canonical_bytes() {
    let patch = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"patch");
    let payload = BlockPayload {
        parent_block_ids: Vec::new(),
        kind: BlockKind::Root,
        patch_ids: vec![patch],
        state_merkle_root: MerkleRoot([7_u8; 32]),
        snapshot_blob_ref: None,
        mainline_parent_id: None,
        merge_baseline_block_id: None,
    };
    let bytes = payload.to_canonical_bytes();
    assert!(bytes.is_ok());
    if let Ok(bytes) = bytes {
        let decoded = BlockPayload::decode_canonical(&bytes);
        assert_eq!(decoded, Ok(payload));
    }
}

#[test]
fn ref_update_payload_decodes_its_canonical_bytes() {
    let previous = ObjectId::from_canonical_payload(ObjectType::RefState, 1, b"prev");
    let current = ObjectId::from_canonical_payload(ObjectType::RefState, 1, b"current");
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 1, b"block");
    let payload = RefUpdatePayload {
        ref_name: "heads/main".to_string(),
        old_ref_state_id: Some(previous),
        new_ref_state_id: current,
        new_target_object_id: block,
        update_seq: 2,
        created_at: 9,
        author_key_id: "maintainer-key".to_string(),
    };
    let bytes = payload.to_canonical_bytes();
    assert!(bytes.is_ok());
    if let Ok(bytes) = bytes {
        let decoded = RefUpdatePayload::decode_canonical(&bytes);
        assert_eq!(decoded, Ok(payload));
    }
}

#[test]
fn recognition_claim_payload_decodes_its_canonical_bytes() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    let patch_a = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"a");
    let patch_b = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"b");
    let (first, second) = if patch_a < patch_b {
        (patch_a, patch_b)
    } else {
        (patch_b, patch_a)
    };
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids: vec![first, second],
        parent_block_ids: Vec::new(),
    };
    let bytes = payload.to_canonical_bytes();
    assert!(bytes.is_ok());
    if let Ok(bytes) = bytes {
        let decoded = RecognitionClaimPayload::decode_canonical(&bytes);
        assert_eq!(decoded, Ok(payload));
    }
}

/// §4.3 of the order-amendment handoff (D6): a descending, unsorted `patch_ids` sequence now
/// encodes and decodes successfully, with order preserved exactly -- the withdrawn refusal
/// (`recognition_claim_payload_rejects_unsorted_patch_ids_at_encode_and_decode`) asserted the
/// opposite contract.
#[test]
fn recognition_claim_payload_preserves_unsorted_order_through_encode_and_decode() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    let patch_a = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"a");
    let patch_b = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"b");
    let (first, second) = if patch_a < patch_b {
        (patch_a, patch_b)
    } else {
        (patch_b, patch_a)
    };

    // Deliberately descending -- the block's own verbatim order, not sorted.
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids: vec![second, first],
        parent_block_ids: Vec::new(),
    };
    let bytes = payload.to_canonical_bytes();
    assert!(bytes.is_ok());
    if let Ok(bytes) = bytes {
        let decoded = RecognitionClaimPayload::decode_canonical(&bytes);
        assert_eq!(
            decoded.map(|payload| payload.patch_ids),
            Ok(vec![second, first]),
            "decoded order must match the encoded order exactly, not be sorted"
        );
    }
}

/// §4.3: duplicate `patch_ids` are now permitted and preserved, mirroring `Block.patch_ids`'s own
/// lack of a uniqueness invariant -- the withdrawn refusal
/// (`recognition_claim_payload_rejects_duplicate_patch_ids_at_decode`) asserted the opposite.
#[test]
fn recognition_claim_payload_preserves_duplicate_patch_ids_through_encode_and_decode() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    let patch = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"patch");
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids: vec![patch, patch],
        parent_block_ids: Vec::new(),
    };
    let bytes = payload.to_canonical_bytes();
    assert!(bytes.is_ok());
    if let Ok(bytes) = bytes {
        let decoded = RecognitionClaimPayload::decode_canonical(&bytes);
        assert_eq!(
            decoded.map(|payload| payload.patch_ids),
            Ok(vec![patch, patch]),
            "the duplicate must round-trip, not be deduplicated"
        );
    }
}

#[test]
fn recognition_claim_payload_rejects_empty_patch_ids() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids: Vec::new(),
        parent_block_ids: Vec::new(),
    };
    assert!(payload.to_canonical_bytes().is_err());
}

#[allow(clippy::expect_used)]
#[test]
fn recognition_claim_payload_rejects_unknown_field_tag() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    let patch = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"patch");
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids: vec![patch],
        parent_block_ids: Vec::new(),
    };
    let mut bytes = payload.to_canonical_bytes().expect("payload must encode");
    // Append one well-formed but unrecognized field (tag 99, empty string) after the real fields.
    bytes.extend_from_slice(&99_u16.to_be_bytes());
    bytes.push(WireType::String as u8);
    bytes.extend_from_slice(&0_u64.to_be_bytes());
    assert!(RecognitionClaimPayload::decode_canonical(&bytes).is_err());
}

#[allow(clippy::expect_used)]
#[test]
fn recognition_claim_payload_rejects_patch_ids_over_the_declared_limit() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    // RECOGNITION_CLAIM_MAX_PATCH_IDS + 1 strictly ascending patch ids -- exceeds the bound by
    // exactly one, so decode must refuse at the boundary, per §7 row 6.
    let mut patch_ids = Vec::with_capacity(RECOGNITION_CLAIM_MAX_PATCH_IDS + 1);
    for index in 0..=RECOGNITION_CLAIM_MAX_PATCH_IDS {
        let mut seed = [0_u8; 32];
        seed[..8].copy_from_slice(&(index as u64).to_be_bytes());
        patch_ids.push(ObjectId::from_bytes(seed));
    }
    patch_ids.sort();
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids,
        parent_block_ids: Vec::new(),
    };
    let bytes = payload
        .to_canonical_bytes()
        .expect("over-limit payload must still encode -- the bound is enforced on decode");
    let result = RecognitionClaimPayload::decode_canonical(&bytes);
    assert!(result.is_err(), "decode must refuse over-limit patch_ids");
}

/// RFC 116 N3 §7 row 1: `parent_block_ids` round-trips verbatim -- unsorted order and a duplicate
/// both preserved, exactly as D6 already established for `patch_ids`.
#[test]
fn recognition_claim_payload_preserves_parent_block_ids_order_and_duplicates() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    let patch = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"patch");
    let parent_a = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"parent-a");
    let parent_b = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"parent-b");
    // Deliberately descending, with a duplicate -- neither sorted nor deduplicated.
    let (first, second) = if parent_a > parent_b {
        (parent_a, parent_b)
    } else {
        (parent_b, parent_a)
    };
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids: vec![patch],
        parent_block_ids: vec![first, second, first],
    };
    let bytes = payload.to_canonical_bytes();
    assert!(bytes.is_ok());
    if let Ok(bytes) = bytes {
        let decoded = RecognitionClaimPayload::decode_canonical(&bytes);
        assert_eq!(
            decoded.map(|payload| payload.parent_block_ids),
            Ok(vec![first, second, first]),
            "decoded parent order must match the encoded order exactly, duplicate included"
        );
    }
}

/// RFC 116 N3 §7 row 2: an empty `parent_block_ids` -- the root-block case -- round-trips and is
/// not an error. Not a degenerate value; the common case.
#[test]
fn recognition_claim_payload_with_empty_parent_block_ids_is_not_an_error() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    let patch = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"patch");
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids: vec![patch],
        parent_block_ids: Vec::new(),
    };
    let bytes = payload.to_canonical_bytes();
    assert!(
        bytes.is_ok(),
        "an empty parent_block_ids must encode successfully"
    );
    if let Ok(bytes) = bytes {
        let decoded = RecognitionClaimPayload::decode_canonical(&bytes);
        assert_eq!(decoded, Ok(payload));
    }
}

/// RFC 116 N3 §7 row 5: an over-limit declared `parent_block_ids` count is rejected before
/// allocating the over-limit entry -- the same per-push bound `patch_ids` already has.
#[allow(clippy::expect_used)]
#[test]
fn recognition_claim_payload_rejects_parent_block_ids_over_the_declared_limit() {
    let block = ObjectId::from_canonical_payload(ObjectType::Block, 2, b"block");
    let patch = ObjectId::from_canonical_payload(ObjectType::Patch, 1, b"patch");
    let mut parent_block_ids = Vec::with_capacity(RECOGNITION_CLAIM_MAX_PATCH_IDS + 1);
    for index in 0..=RECOGNITION_CLAIM_MAX_PATCH_IDS {
        let mut seed = [0_u8; 32];
        seed[..8].copy_from_slice(&(index as u64).to_be_bytes());
        parent_block_ids.push(ObjectId::from_bytes(seed));
    }
    let payload = RecognitionClaimPayload {
        block_id: block,
        patch_ids: vec![patch],
        parent_block_ids,
    };
    let bytes = payload
        .to_canonical_bytes()
        .expect("over-limit payload must still encode -- the bound is enforced on decode");
    let result = RecognitionClaimPayload::decode_canonical(&bytes);
    assert!(
        result.is_err(),
        "decode must refuse over-limit parent_block_ids"
    );
}

fn plugin_result(plugin_id: &str, plugin_version: &str, report_byte: u8) -> PluginResultEntry {
    PluginResultEntry {
        plugin_id: plugin_id.to_string(),
        plugin_version: plugin_version.to_string(),
        status: AttestationStatus::Pass,
        report_hash: vec![report_byte; 32],
        finding_count: 0,
    }
}

fn attestation_with(results: Vec<PluginResultEntry>) -> AttestationPayload {
    AttestationPayload {
        target_block_id: ObjectId::from_bytes([0x11; 32]),
        policy_version: "v1".to_string(),
        plugin_set_hash: vec![0x22; 32],
        results,
        status: AttestationStatus::Pass,
        created_at: 1,
        is_reproducible_offline: true,
    }
}

#[test]
fn attestation_results_accept_ascending_plugin_id() {
    let att = attestation_with(vec![
        plugin_result("audit-a", "0.1", 1),
        plugin_result("audit-b", "0.1", 1),
    ]);
    assert!(att.to_canonical_bytes().is_ok());
}

#[test]
fn attestation_results_reject_reverse_order() {
    let att = attestation_with(vec![
        plugin_result("audit-b", "0.1", 1),
        plugin_result("audit-a", "0.1", 1),
    ]);
    assert!(att.to_canonical_bytes().is_err());
}

#[test]
fn attestation_results_reject_duplicate_plugin_id_differing_version() {
    let att = attestation_with(vec![
        plugin_result("audit", "0.1", 1),
        plugin_result("audit", "0.2", 1),
    ]);
    assert!(
        att.to_canonical_bytes().is_err(),
        "duplicate plugin_id must be rejected even when plugin_version differs"
    );
}

#[test]
fn attestation_results_reject_duplicate_plugin_id_differing_report_hash() {
    let att = attestation_with(vec![
        plugin_result("audit", "0.1", 1),
        plugin_result("audit", "0.1", 2),
    ]);
    assert!(
        att.to_canonical_bytes().is_err(),
        "duplicate plugin_id must be rejected even when report_hash differs"
    );
}

#[test]
fn blob_kind_from_code_rejects_invalid_and_unknown() {
    use super::BlobKind;
    assert!(BlobKind::from_code(0x0000).is_err());
    assert!(BlobKind::from_code(0x00ff).is_err());
    assert_eq!(BlobKind::from_code(0x0001), Ok(BlobKind::Text));
    assert_eq!(BlobKind::from_code(0x0002), Ok(BlobKind::Binary));
    assert_eq!(BlobKind::from_code(0x0003), Ok(BlobKind::Snapshot));
}

#[test]
fn blob_encode_rejects_declared_size_mismatch() {
    let bad = BlobPayload {
        blob_kind: BlobKind::Text,
        content: b"abc".to_vec(),
        declared_size: 99,
    };
    assert!(
        bad.to_canonical_bytes().is_err(),
        "declared_size must equal content length"
    );
}

#[allow(clippy::expect_used)]
#[test]
fn blob_round_trips_via_new() {
    let blob = BlobPayload::new(BlobKind::Binary, vec![0x01, 0x02, 0x03]);
    let bytes = blob.to_canonical_bytes().expect("encode");
    let decoded = BlobPayload::decode_canonical(&bytes).expect("decode");
    assert_eq!(decoded, blob);
    assert_eq!(decoded.declared_size, 3);
}

#[test]
fn blob_decode_rejects_declared_size_mismatch() {
    // hand-craft: blob_kind=Text(1), content="ab"(2 bytes), declared_size=5
    let mut p = Vec::new();
    p.extend_from_slice(&1u16.to_be_bytes());
    p.push(0x05); // enum_u16
    p.extend_from_slice(&2u64.to_be_bytes());
    p.extend_from_slice(&1u16.to_be_bytes()); // Text
    p.extend_from_slice(&2u16.to_be_bytes());
    p.push(0x11); // bytes
    p.extend_from_slice(&2u64.to_be_bytes());
    p.extend_from_slice(b"ab");
    p.extend_from_slice(&3u16.to_be_bytes());
    p.push(0x04); // u64
    p.extend_from_slice(&8u64.to_be_bytes());
    p.extend_from_slice(&5u64.to_be_bytes()); // declared_size=5 != 2
    assert!(BlobPayload::decode_canonical(&p).is_err());
}

#[test]
fn node_kind_from_code_rejects_invalid_and_unknown() {
    use super::NodeKind;
    assert!(NodeKind::from_code(0x0000).is_err());
    assert!(NodeKind::from_code(0x00ff).is_err());
    assert_eq!(NodeKind::from_code(0x0001), Ok(NodeKind::TextFile));
    assert_eq!(NodeKind::from_code(0x0002), Ok(NodeKind::BinaryFile));
    assert_eq!(NodeKind::from_code(0x0003), Ok(NodeKind::Symlink));
}

#[test]
fn node_kind_derives_from_file_blob_kind() {
    use super::{BlobKind, NodeKind};
    assert_eq!(
        NodeKind::from_file_blob_kind(BlobKind::Text),
        Ok(NodeKind::TextFile)
    );
    assert_eq!(
        NodeKind::from_file_blob_kind(BlobKind::Binary),
        Ok(NodeKind::BinaryFile)
    );
    assert!(
        NodeKind::from_file_blob_kind(BlobKind::Snapshot).is_err(),
        "a file node must not derive from a SNAPSHOT blob"
    );
}

#[test]
fn node_id_round_trips_bytes() {
    use super::NodeId;
    let raw = [0x5a_u8; 32];
    let id = NodeId::from_bytes(raw);
    assert_eq!(id.as_bytes(), &raw);
}

#[test]
fn node_id_try_from_bytes_rejects_all_zero() {
    use super::NodeId;
    assert!(NodeId::try_from_bytes([0_u8; 32]).is_err());
    let ok = NodeId::try_from_bytes([0x01_u8; 32]);
    assert!(ok.is_ok());
}

#[test]
fn patch_payload_rejects_empty_operations() {
    use super::PatchPayload;
    use crate::CanonicalEncode;
    let patch = PatchPayload {
        operations: Vec::new(),
        parent_patch_ids: Vec::new(),
        intent: None,
        preconditions: Vec::new(),
        purpose: PatchPurpose::Normal,
    };
    // §9.1: operations is required with at least one operation.
    assert!(patch.validate().is_err());
    assert!(patch.to_canonical_bytes().is_err());
}

#[test]
fn patch_purpose_absent_decodes_as_normal() {
    let patch = PatchPayload {
        operations: vec![Operation {
            op_seq: 1,
            op_id: None,
            preconditions: Vec::new(),
            kind: OperationKind::EditText(EditText {
                node_id: crate::NodeId::from_bytes([0x22; 32]),
                span_id: [0x10; 32],
                old_span_hash: text_span_hash(b"old"),
                left_anchor_hash: [0x11; 32],
                right_anchor_hash: [0x12; 32],
                replacement_text: b"hello".to_vec(),
                presentation_hint_line: None,
                presentation_hint_column: None,
                old_span_text: b"old".to_vec(),
            }),
        }],
        parent_patch_ids: Vec::new(),
        intent: None,
        preconditions: Vec::new(),
        purpose: PatchPurpose::Normal,
    };
    let bytes = patch.to_canonical_bytes();
    assert!(bytes.is_ok());
    if let Ok(bytes) = bytes {
        assert_eq!(
            PatchPurpose::decode_from_patch_payload(&bytes),
            Ok(PatchPurpose::Normal)
        );
    }
}

#[test]
fn patch_purpose_explicit_normal_is_rejected() {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(&5_u16.to_be_bytes());
    bytes.push(crate::WireType::EnumU16 as u8);
    bytes.extend_from_slice(&2_u64.to_be_bytes());
    bytes.extend_from_slice(&PatchPurpose::Normal.code().to_be_bytes());
    assert!(PatchPurpose::decode_from_patch_payload(&bytes).is_err());
}

/// RFC 117 T1 `stage-1-tag-payload-digest-handoff-v1.md` §6 row 1: field 6 (`patch_set_digest`) is
/// required -- a payload encoding only fields 1-5 (the pre-RFC-117 shape) must fail to decode, not
/// default. Built with `CanonicalWriter` directly rather than via `TagPayload::encode_canonical`,
/// which cannot itself produce a payload missing the field it always writes.
#[allow(clippy::expect_used)]
#[test]
fn tag_payload_requires_patch_set_digest_field() {
    let mut writer = CanonicalWriter::new();
    writer.field_string(1, "v1").expect("field 1 encodes");
    writer
        .field_object_id(2, &ObjectId::from_bytes([0x01; 32]))
        .expect("field 2 encodes");
    writer.field_u64(4, 0).expect("field 4 encodes");
    writer
        .field_string(5, "maintainer-key")
        .expect("field 5 encodes");
    let bytes = writer.finish();

    let message = match TagPayload::decode_canonical(&bytes) {
        Ok(_) => panic!(
            "a Tag payload without field 6 (patch_set_digest) must fail to decode, not default"
        ),
        Err(err) => err.to_string(),
    };
    assert!(
        message.contains("patch_set_digest"),
        "the refusal must name the missing field: {message}"
    );
}

/// RFC 117 T7 `stage-2a-tag-patch-count-handoff-v1.md` §7 item 3: field 7 (`patch_count`) is
/// required -- a payload encoding fields 1-6 (the pre-T7 shape) must fail to decode, not default.
#[allow(clippy::expect_used)]
#[test]
fn tag_payload_requires_patch_count_field() {
    let mut writer = CanonicalWriter::new();
    writer.field_string(1, "v1").expect("field 1 encodes");
    writer
        .field_object_id(2, &ObjectId::from_bytes([0x01; 32]))
        .expect("field 2 encodes");
    writer.field_u64(4, 0).expect("field 4 encodes");
    writer
        .field_string(5, "maintainer-key")
        .expect("field 5 encodes");
    writer.field_bytes(6, &[0x02; 32]).expect("field 6 encodes");
    let bytes = writer.finish();

    let message = match TagPayload::decode_canonical(&bytes) {
        Ok(_) => {
            panic!("a Tag payload without field 7 (patch_count) must fail to decode, not default")
        }
        Err(err) => err.to_string(),
    };
    assert!(
        message.contains("patch_count"),
        "the refusal must name the missing field: {message}"
    );
}