prikk-store 0.24.0

Prikk storage crate scaffold.
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
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
//! Bundle export/import tests.

mod proptest_decode_bundle;

use prikk_object::{
    BlockKind, CanonicalEncode, CreateFile, NodeId, ObjectEnvelope, ObjectId, ObjectType,
    Operation, OperationKind, PatchPayload, PatchPurpose, RefKind, RefStatePayload,
    RefUpdatePayload, TagPayload,
};

use crate::author_key_index::{
    AuthorKeyEntry, force_conflicting_author_key_entry_for_test, lookup_author_key_entries,
    record_author_key_material, verify_author_signature,
};
use crate::author_signing::{AuthorSigner, author_signature};
use crate::bundle::{
    BundleImportOptions, DEFAULT_BUNDLE_MAX_OBJECT_COUNT, decode_bundle, encode_bundle,
    encode_bundle_v1_for_test, export_bundle, import_bundle,
};
use crate::layout::{ContainerSlot, LockableContainer};
use crate::lock::{ActiveLock, acquire_container_locks};
use crate::received::read_received_pointer;
use crate::test_support::{
    rollback_patch_blob_envelope, signed_block, signed_patch_blob_envelope, signed_patch_envelope,
    signed_ref_state_envelope, signed_ref_update_envelope, unique_temp_dir,
};
use crate::{
    Ed25519AuthorSigner, Ed25519MaintainerSigner, FileObjectStore, MaintainerSigner, ObjectReader,
    ObjectWriter, RefPublication, RefStore, RepositoryLayout,
};

/// Seal a two-block `heads/main` (a Root block plus a Normal child referencing one Patch, whose
/// `CreateFile` operation itself references one Blob) into `layout`, returning the tip Block id —
/// enough to exercise a genuinely multi-block, genesis-complete export rather than a single trivial
/// object, and to exercise blob discovery through a Patch's own operations, not just a Block's
/// `snapshot_blob_ref`.
fn seal_two_block_history(
    layout: &RepositoryLayout,
) -> prikk_error::Result<prikk_object::ObjectId> {
    let mut object_store = FileObjectStore::new(layout.clone());
    object_store.write_object(&signed_patch_blob_envelope())?;
    let patch = signed_patch_envelope();
    let patch_id = object_store.write_object(&patch)?;

    let root_block = signed_block(BlockKind::Root, Vec::new(), Vec::new(), None);
    let root_block_id = object_store.write_object(&root_block)?;

    let child_block = signed_block(BlockKind::Normal, vec![root_block_id], vec![patch_id], None);
    let child_block_id = object_store.write_object(&child_block)?;

    let ref_store = RefStore::new(layout.clone());
    let ref_state = signed_ref_state_envelope("heads/main", None, child_block_id, 1);
    let ref_state_id = ref_state.object_id();
    let ref_update =
        signed_ref_update_envelope("heads/main", None, ref_state_id, child_block_id, 1);
    ref_store.publish(&RefPublication {
        ref_name: "heads/main".to_string(),
        expected_previous_ref_state_id: None,
        ref_state,
        ref_update,
    })?;
    Ok(child_block_id)
}

/// `seal_two_block_history`'s own shape, plus a `snapshot_blob_ref` on the Root block -- a distinct
/// blob (`rollback_patch_blob_envelope`'s fixed "rollback fixture\n" content, not the Patch's own
/// "patch fixture\n" one) so the two blobs never collide by content-address. Returns the tip Block id
/// and the snapshot Blob's own id (review condition two,
/// `DC-78-import-closure-validation-review-v1.md` §3: a Block's own `snapshot_blob_ref` is a blob
/// reference too, and needed its own fixture -- `seal_two_block_history`'s blocks never set it).
fn seal_two_block_history_with_snapshot_blob(
    layout: &RepositoryLayout,
) -> prikk_error::Result<(ObjectId, ObjectId)> {
    let mut object_store = FileObjectStore::new(layout.clone());
    object_store.write_object(&signed_patch_blob_envelope())?;
    let patch = signed_patch_envelope();
    let patch_id = object_store.write_object(&patch)?;

    let snapshot_blob = rollback_patch_blob_envelope();
    let snapshot_blob_id = object_store.write_object(&snapshot_blob)?;

    let root_block = signed_block(
        BlockKind::Root,
        Vec::new(),
        Vec::new(),
        Some(snapshot_blob_id),
    );
    let root_block_id = object_store.write_object(&root_block)?;

    let child_block = signed_block(BlockKind::Normal, vec![root_block_id], vec![patch_id], None);
    let child_block_id = object_store.write_object(&child_block)?;

    let ref_store = RefStore::new(layout.clone());
    let ref_state = signed_ref_state_envelope("heads/main", None, child_block_id, 1);
    let ref_state_id = ref_state.object_id();
    let ref_update =
        signed_ref_update_envelope("heads/main", None, ref_state_id, child_block_id, 1);
    ref_store.publish(&RefPublication {
        ref_name: "heads/main".to_string(),
        expected_previous_ref_state_id: None,
        ref_state,
        ref_update,
    })?;
    Ok((child_block_id, snapshot_blob_id))
}

/// DC-53 Stage 2: a fixed-seed AUTHOR signer, distinct across callers via `discriminant` so tests
/// signing more than one Patch under this helper get distinct `key_id`s and object ids.
fn transport_test_signer(discriminant: u8) -> prikk_error::Result<Ed25519AuthorSigner> {
    Ed25519AuthorSigner::from_seed(
        format!("dc53-stage2-transport-{discriminant}"),
        &[discriminant; 32],
    )
}

/// Seal a two-block `heads/main` whose Patch carries a real AUTHOR signature from `signer`, rather
/// than `seal_two_block_history`'s fixed structural fixture -- DC-53 Stage 2's transport tests need
/// a signature `record_author_key_material`/`verify_author_signature` can actually be asked about.
/// If `record_locally` is true, `signer`'s key material is recorded on `layout` before this returns
/// (real authoring's own order, `node_authoring.rs:589`); if false, the Patch is signed but no local
/// material exists for it yet -- vector 7's starting state.
fn seal_two_block_history_with_author(
    layout: &RepositoryLayout,
    signer: &Ed25519AuthorSigner,
    record_locally: bool,
) -> prikk_error::Result<ObjectId> {
    let mut object_store = FileObjectStore::new(layout.clone());
    let blob = signed_patch_blob_envelope();
    object_store.write_object(&blob)?;

    let payload = PatchPayload {
        operations: vec![Operation {
            op_seq: 1,
            op_id: None,
            preconditions: Vec::new(),
            kind: OperationKind::CreateFile(CreateFile {
                path: "transport.txt".to_string(),
                node_id: NodeId::from_bytes([0x54; 32]),
                blob_id: blob.object_id(),
                mode: 0o100_644,
            }),
        }],
        intent: None,
        preconditions: Vec::new(),
        purpose: PatchPurpose::Normal,
    };
    let mut patch = ObjectEnvelope::unsigned(ObjectType::Patch, 1, payload.to_canonical_bytes()?);
    let patch_object_id = patch.object_id();
    let signature = author_signature(signer, patch_object_id)?;
    patch.add_signature(signature)?;
    let patch_id = object_store.write_object(&patch)?;

    if record_locally {
        let active_lock = ActiveLock::acquire(layout)?;
        record_author_key_material(
            layout,
            signer.key_id(),
            signer.public_key_bytes(),
            &active_lock,
        )?;
    }

    let root_block = signed_block(BlockKind::Root, Vec::new(), Vec::new(), None);
    let root_block_id = object_store.write_object(&root_block)?;
    let child_block = signed_block(BlockKind::Normal, vec![root_block_id], vec![patch_id], None);
    let child_block_id = object_store.write_object(&child_block)?;

    let ref_store = RefStore::new(layout.clone());
    let ref_state = signed_ref_state_envelope("heads/main", None, child_block_id, 1);
    let ref_state_id = ref_state.object_id();
    let ref_update =
        signed_ref_update_envelope("heads/main", None, ref_state_id, child_block_id, 1);
    ref_store.publish(&RefPublication {
        ref_name: "heads/main".to_string(),
        expected_previous_ref_state_id: None,
        ref_state,
        ref_update,
    })?;
    Ok(child_block_id)
}

/// Find the imported Patch in `target`'s object store by scanning for the one carrying
/// `transport.txt` -- `seal_two_block_history_with_author`'s own fixture path, distinct from
/// `seal_two_block_history`'s `a.txt`.
fn find_imported_transport_patch(target: &RepositoryLayout) -> prikk_error::Result<ObjectEnvelope> {
    // The Patch's object id is derived from its canonical payload, which the sender and receiver
    // both compute identically -- recompute it here rather than threading it through `import_bundle`'s
    // own report, which deliberately reports only counts (DC-53 Stage 2, D6/D7's own "no new
    // verification path" -- this helper is test-only introspection, not part of the transport
    // contract).
    let target_store = FileObjectStore::new(target.clone());
    let ref_state_id = read_received_pointer(target, "remotes/heads/main")?
        .ok_or_else(|| {
            prikk_error::PrikkError::Integrity("received ref state missing".to_string())
        })?
        .ref_state_id;
    let ref_state_envelope = target_store
        .read_typed(ref_state_id, ObjectType::RefState)?
        .ok_or_else(|| {
            prikk_error::PrikkError::Integrity("received RefState missing".to_string())
        })?;
    let ref_state_payload = prikk_object::RefStatePayload::decode_canonical(
        &ref_state_envelope.canonical_payload,
        ref_state_envelope.schema_version,
    )?;
    let block_envelope = target_store
        .read_typed(ref_state_payload.target_object_id, ObjectType::Block)?
        .ok_or_else(|| prikk_error::PrikkError::Integrity("received Block missing".to_string()))?;
    let block_payload =
        prikk_object::BlockPayload::decode_canonical(&block_envelope.canonical_payload)?;
    for patch_id in &block_payload.patch_ids {
        if let Some(envelope) = target_store.read_typed(*patch_id, ObjectType::Patch)? {
            return Ok(envelope);
        }
    }
    Err(prikk_error::PrikkError::Integrity(
        "no Patch found in received Block".to_string(),
    ))
}

#[test]
fn export_of_missing_ref_fails() {
    let root = unique_temp_dir("bundle-export-missing-ref");
    let layout = RepositoryLayout::init(root.clone());
    assert!(layout.is_ok());
    if let Ok(layout) = layout {
        assert!(export_bundle(&layout, "heads/main").is_err());
    }
    let _ = std::fs::remove_dir_all(root);
}

#[test]
fn import_of_malformed_bytes_fails_closed() {
    let root = unique_temp_dir("bundle-import-malformed");
    let layout = RepositoryLayout::init(root.clone());
    assert!(layout.is_ok());
    if let Ok(layout) = layout {
        let options = BundleImportOptions::default_limits();
        assert!(import_bundle(&layout, b"not a bundle", &options).is_err());
        assert!(import_bundle(&layout, b"PBNDL001", &options).is_err());
        assert!(import_bundle(&layout, &[], &options).is_err());
    }
    let _ = std::fs::remove_dir_all(root);
}

#[test]
fn export_then_import_carries_the_full_genesis_complete_closure() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("bundle-export-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let child_block_id = seal_two_block_history(&source)?;

    let (report, bytes) = export_bundle(&source, "heads/main")?;
    assert_eq!(report.ref_name, "heads/main");
    assert_eq!(report.tip_block_id, child_block_id);
    // RefState + 2 Blocks + 1 Patch + 1 Blob (the Patch's CreateFile references it) = 5 objects;
    // no Attestation in this fixture.
    assert_eq!(report.object_count, 5);

    let target_root = unique_temp_dir("bundle-import-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let import_report = import_bundle(&target, &bytes, &BundleImportOptions::default_limits())?;
    assert_eq!(import_report.ref_name, "remotes/heads/main");
    assert_eq!(import_report.object_count, 5);
    assert_eq!(import_report.written_object_count, 5);

    let pointer = read_received_pointer(&target, "remotes/heads/main")?;
    assert!(pointer.is_some());
    if let Some(pointer) = pointer {
        assert_eq!(pointer.ref_state_id, import_report.ref_state_id);
    }

    let target_objects = FileObjectStore::new(target.clone());
    assert!(
        target_objects
            .read_typed(child_block_id, ObjectType::Block)?
            .is_some()
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// RFC 102 Stage 6 Step 2, design-v1.md §15.8: `import_bundle` acquires the `ReceivedIndex`
/// container lock -- the gap the received-index concurrency investigation surfaced in the first
/// place (`FINDINGS.md`), closed here. Proven the same way as the ref/trust equivalents: hold the
/// lock externally, observe the refusal, release, observe success. Object writes must not have
/// happened either -- the lock is acquired after them, so a refused import still leaves the target
/// repository's received-index untouched, but confirming the objects themselves aren't silently
/// re-imported on retry is the property this test also checks.
#[test]
fn import_refuses_while_received_index_lock_is_externally_held() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("bundle-lock-conflict-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;

    let target_root = unique_temp_dir("bundle-lock-conflict-target");
    let target = RepositoryLayout::init(target_root.clone())?;

    let held = acquire_container_locks(&target, &[LockableContainer::ReceivedIndex])?;
    assert!(import_bundle(&target, &bytes, &BundleImportOptions::default_limits()).is_err());
    assert!(read_received_pointer(&target, "remotes/heads/main")?.is_none());
    drop(held);

    let report = import_bundle(&target, &bytes, &BundleImportOptions::default_limits())?;
    assert_eq!(report.ref_name, "remotes/heads/main");
    assert!(read_received_pointer(&target, "remotes/heads/main")?.is_some());

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

#[test]
fn import_never_writes_a_local_ref_pointer() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("bundle-negctrl-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;

    let target_root = unique_temp_dir("bundle-negctrl-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let ref_store = RefStore::new(target.clone());
    let before = ref_store.list_ref_pointers()?;
    assert!(before.is_empty());

    import_bundle(&target, &bytes, &BundleImportOptions::default_limits())?;

    let after = RefStore::new(target.clone()).list_ref_pointers()?;
    assert_eq!(
        before, after,
        "bundle import must never advance or create a local heads/*-or-tags/* ref pointer"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

#[test]
fn reimporting_the_same_bundle_is_idempotent() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("bundle-reimport-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;

    let target_root = unique_temp_dir("bundle-reimport-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let options = BundleImportOptions::default_limits();
    let first = import_bundle(&target, &bytes, &options)?;
    assert_eq!(first.written_object_count, 5);

    let second = import_bundle(&target, &bytes, &options)?;
    assert_eq!(second.written_object_count, 0);
    assert_eq!(second.ref_state_id, first.ref_state_id);

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// DC-86 criterion 3, the negative control: a bundle whose declared object count is exactly at the
/// limit is accepted, and the identical bundle against a limit one below its actual count is refused.
/// A bound nobody has seen fire is a bound nobody knows exists.
#[test]
fn import_object_count_limit_fires_exactly_at_the_boundary() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("bundle-limit-count-boundary-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (report, bytes) = export_bundle(&source, "heads/main")?;
    assert_eq!(report.object_count, 5);

    let under_root = unique_temp_dir("bundle-limit-count-boundary-under");
    let under_target = RepositoryLayout::init(under_root.clone())?;
    let refused = import_bundle(
        &under_target,
        &bytes,
        &BundleImportOptions::default_limits().with_max_object_count(4),
    );
    assert!(
        refused.is_err(),
        "a limit one below the actual count (5) must refuse"
    );

    let at_root = unique_temp_dir("bundle-limit-count-boundary-at");
    let at_target = RepositoryLayout::init(at_root.clone())?;
    let accepted = import_bundle(
        &at_target,
        &bytes,
        &BundleImportOptions::default_limits().with_max_object_count(5),
    );
    assert!(
        accepted.is_ok(),
        "a limit exactly at the actual count (5) must accept"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(under_root);
    let _ = std::fs::remove_dir_all(at_root);
    Ok(())
}

/// The same negative control for the total-bytes bound: one byte short of the encoded bundle's own
/// length refuses; the exact length accepts.
#[test]
fn import_total_bytes_limit_fires_exactly_at_the_boundary() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("bundle-limit-bytes-boundary-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;

    let under_root = unique_temp_dir("bundle-limit-bytes-boundary-under");
    let under_target = RepositoryLayout::init(under_root.clone())?;
    let refused = import_bundle(
        &under_target,
        &bytes,
        &BundleImportOptions::default_limits().with_max_total_bytes(bytes.len() - 1),
    );
    assert!(
        refused.is_err(),
        "a byte limit one below the bundle's own length must refuse"
    );

    let at_root = unique_temp_dir("bundle-limit-bytes-boundary-at");
    let at_target = RepositoryLayout::init(at_root.clone())?;
    let accepted = import_bundle(
        &at_target,
        &bytes,
        &BundleImportOptions::default_limits().with_max_total_bytes(bytes.len()),
    );
    assert!(
        accepted.is_ok(),
        "a byte limit exactly at the bundle's own length must accept"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(under_root);
    let _ = std::fs::remove_dir_all(at_root);
    Ok(())
}

/// DC-86 criterion 2, measured rather than asserted: a refused over-limit import leaves the target's
/// object store with exactly the same object count as before the attempt — "it returned an error"
/// does not by itself prove nothing was written.
#[test]
fn import_refused_over_the_object_count_limit_writes_nothing() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("bundle-limit-writes-nothing-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;

    let target_root = unique_temp_dir("bundle-limit-writes-nothing-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let before = crate::verify_repository(&target)?.checked_objects;

    let refused = import_bundle(
        &target,
        &bytes,
        &BundleImportOptions::default_limits().with_max_object_count(4),
    );
    assert!(refused.is_err());

    let after = crate::verify_repository(&target)?.checked_objects;
    assert_eq!(
        before, after,
        "a refused import must leave the object store's checked-object count unchanged"
    );
    assert_eq!(before, Some(0));

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// DC-53 Stage 2, §7 vector 7: a bundle whose author-key section omits a key for a Patch it
/// contains -- material is optional per-author -- must still import, and the Patch must read
/// Unverifiable, not Sound and not a failure.
#[test]
fn dc53_stage2_vector7_omitted_material_imports_as_unverifiable() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc53-vector7-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let signer = transport_test_signer(0xa1)?;
    seal_two_block_history_with_author(&source, &signer, false)?;

    let (report, bytes) = export_bundle(&source, "heads/main")?;
    assert_eq!(
        report.author_key_count, 0,
        "no local material exists for this key_id, so the section must omit it"
    );

    let target_root = unique_temp_dir("dc53-vector7-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let import_report = import_bundle(&target, &bytes, &BundleImportOptions::default_limits())?;
    assert_eq!(import_report.recorded_author_key_count, 0);

    let imported_patch = find_imported_transport_patch(&target)?;
    let outcome = verify_author_signature(&target, &imported_patch)?;
    assert_eq!(
        outcome,
        Some((signer.key_id().to_string(), false)),
        "expected Unverifiable, got {outcome:?}"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// Positive control alongside vector 7: material that *is* recorded locally transports and the
/// imported Patch reads Sound, not merely "not a failure" -- `Unverifiable` would also pass that
/// weaker bar.
#[test]
fn dc53_stage2_transported_material_imports_as_sound() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc53-vector-sound-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let signer = transport_test_signer(0xa2)?;
    seal_two_block_history_with_author(&source, &signer, true)?;

    let (report, bytes) = export_bundle(&source, "heads/main")?;
    assert_eq!(report.author_key_count, 1);

    let target_root = unique_temp_dir("dc53-vector-sound-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let import_report = import_bundle(&target, &bytes, &BundleImportOptions::default_limits())?;
    assert_eq!(import_report.recorded_author_key_count, 1);

    let imported_patch = find_imported_transport_patch(&target)?;
    let outcome = verify_author_signature(&target, &imported_patch)?;
    assert_eq!(outcome, Some((signer.key_id().to_string(), true)));

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// DC-53 Stage 2, §7 vector 8: a bundle whose author-key section carries a key that does not
/// verify the Patch's signature -- the transport-layer forgery case. Import records the material
/// anyway (D7: import records, `verify` decides, no cryptographic check at the transport layer,
/// matching how objects are written without re-verifying them); `verify_author_signature` on the
/// imported Patch is what fails, reached through the transport path rather than local authoring
/// but the same underlying check as D3's third row.
#[test]
fn dc53_stage2_vector8_a_transported_key_that_does_not_verify_reads_failed()
-> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc53-vector8-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let signer = transport_test_signer(0xa3)?;
    seal_two_block_history_with_author(&source, &signer, true)?;

    let (_, bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, mut author_keys) =
        decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert_eq!(author_keys.len(), 1);
    if let Some(entry) = author_keys.first_mut() {
        // Swap in an unrelated public key for the same key_id -- the forgery this vector targets.
        entry.public_key = [0xbb; 32];
    }
    let tampered = encode_bundle(&ref_name, &objects, &author_keys)?;

    let target_root = unique_temp_dir("dc53-vector8-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let import_report = import_bundle(&target, &tampered, &BundleImportOptions::default_limits())?;
    assert_eq!(
        import_report.recorded_author_key_count, 1,
        "import records material without checking it, D7"
    );

    let imported_patch = find_imported_transport_patch(&target)?;
    let outcome = verify_author_signature(&target, &imported_patch);
    assert!(
        outcome.is_err(),
        "the transported key must not verify the Patch's real signature -- got {outcome:?}"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// DC-53 Stage 2, D7/C2: a bundle whose own author-key section carries two different public keys
/// for one `key_id` must be refused before any write -- a hostile or merely stale bundle must not
/// be able to leave a receiver with an unresolvable, permanently unverifiable `key_id`.
#[test]
fn import_rejects_a_bundle_whose_author_key_section_disagrees_with_itself()
-> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc53-bundle-internal-conflict-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let signer = transport_test_signer(0xa4)?;
    seal_two_block_history_with_author(&source, &signer, true)?;

    let (_, bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, mut author_keys) =
        decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert_eq!(author_keys.len(), 1);
    let key_id = author_keys
        .first()
        .map(|entry| entry.key_id.clone())
        .ok_or_else(|| {
            prikk_error::PrikkError::Integrity("expected one decoded author-key entry".to_string())
        })?;
    author_keys.push(AuthorKeyEntry {
        key_id: key_id.clone(),
        public_key: [0xcc; 32],
    });
    let hostile = encode_bundle(&ref_name, &objects, &author_keys)?;

    let target_root = unique_temp_dir("dc53-bundle-internal-conflict-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let before = crate::verify_repository(&target)?.checked_objects;
    let result = import_bundle(&target, &hostile, &BundleImportOptions::default_limits());
    assert!(
        result.is_err(),
        "a bundle whose own author-key section disagrees with itself must be refused"
    );
    let after = crate::verify_repository(&target)?.checked_objects;
    assert_eq!(
        before, after,
        "refused before any write -- the object store must be untouched"
    );
    assert_eq!(before, Some(0));
    // DC-53 Stage 2 implementation review v1, C1: the object store is not the container this
    // check protects -- the hazard is a partial write to the author-key container itself, which
    // has no prune/repair path. Asserted directly, not inferred from the object store happening
    // to move together with it (a coincidence of today's ordering, not a guarantee).
    assert_eq!(
        lookup_author_key_entries(&target, &key_id)?,
        Vec::new(),
        "a refused hostile bundle must leave no author-key entry behind, not even the attacker's \
         first-listed one"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// DC-53 Stage 2, D7: reusing Step 1's `record_author_key_material` at import means a transported
/// key conflicting with material this receiver *already* has locally is refused too -- distinct
/// from the bundle-internal case above, and the receiver's own existing material must survive
/// untouched.
#[test]
fn import_rejects_a_transported_key_conflicting_with_local_material() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc53-import-local-conflict-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let signer = transport_test_signer(0xa5)?;
    seal_two_block_history_with_author(&source, &signer, true)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;

    let target_root = unique_temp_dir("dc53-import-local-conflict-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let active_lock = ActiveLock::acquire(&target)?;
    record_author_key_material(&target, signer.key_id(), [0xdd; 32], &active_lock)?;
    drop(active_lock);

    let result = import_bundle(&target, &bytes, &BundleImportOptions::default_limits());
    assert!(
        result.is_err(),
        "a transported key conflicting with existing local material must be refused"
    );
    assert!(
        read_received_pointer(&target, "remotes/heads/main")?.is_none(),
        "a refused import must not create the received pointer"
    );
    let entries = lookup_author_key_entries(&target, signer.key_id())?;
    assert_eq!(
        entries,
        vec![AuthorKeyEntry {
            key_id: signer.key_id().to_string(),
            public_key: [0xdd; 32],
        }],
        "the transported conflicting key must never be recorded -- {entries:?}"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// DC-53 Stage 2 follow-up (`multi-key-import-partial-write-v1.md`): with `m > 1` transported keys,
/// a conflict at a later entry must not leave an earlier, non-conflicting entry durably recorded --
/// the container that leak would land in has no prune, no compaction and no repair. Built by
/// exporting one signer's real bundle, then splicing in a second, synthetic transported key whose
/// `key_id` the target already holds under a *different* public key -- the first entry has nothing
/// wrong with it; the second is the one that must refuse the whole import.
#[test]
fn import_rejects_a_later_conflicting_key_without_recording_an_earlier_one()
-> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc53-multi-key-import-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let signer_a = transport_test_signer(0xb1)?;
    seal_two_block_history_with_author(&source, &signer_a, true)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, mut author_keys) =
        decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert_eq!(
        author_keys.len(),
        1,
        "expected exactly one transported key from a single-author export"
    );

    let signer_b = transport_test_signer(0xb2)?;
    author_keys.push(AuthorKeyEntry {
        key_id: signer_b.key_id().to_string(),
        public_key: signer_b.public_key_bytes(),
    });
    let hostile = encode_bundle(&ref_name, &objects, &author_keys)?;

    let target_root = unique_temp_dir("dc53-multi-key-import-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let active_lock = ActiveLock::acquire(&target)?;
    record_author_key_material(&target, signer_b.key_id(), [0xdd; 32], &active_lock)?;
    drop(active_lock);

    let result = import_bundle(&target, &hostile, &BundleImportOptions::default_limits());
    assert!(
        result.is_err(),
        "a later transported key conflicting with local material must refuse the whole import"
    );
    assert!(
        read_received_pointer(&target, "remotes/heads/main")?.is_none(),
        "a refused import must not create the received pointer"
    );
    assert_eq!(
        lookup_author_key_entries(&target, signer_a.key_id())?,
        Vec::new(),
        "the earlier entry, which conflicted with nothing, must not have been recorded either -- \
         the whole import is refused before any entry is written"
    );
    assert_eq!(
        lookup_author_key_entries(&target, signer_b.key_id())?,
        vec![AuthorKeyEntry {
            key_id: signer_b.key_id().to_string(),
            public_key: [0xdd; 32],
        }],
        "the target's own pre-existing material for the conflicting key_id must survive untouched"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// `multi-key-import-partial-write-v1.md` §5.3: re-importing an unchanged bundle must stay
/// idempotent under the new pre-validation pass too -- a repeat import must hit
/// `check_author_key_conflict`'s `AlreadyRecorded` outcome, not a manufactured conflict, and must
/// not grow the container.
#[test]
fn reimporting_the_same_bundle_records_no_new_author_key_entries() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc53-multi-key-reimport-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let signer = transport_test_signer(0xb3)?;
    seal_two_block_history_with_author(&source, &signer, true)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;

    let target_root = unique_temp_dir("dc53-multi-key-reimport-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let options = BundleImportOptions::default_limits();
    import_bundle(&target, &bytes, &options)?;
    let after_first = lookup_author_key_entries(&target, signer.key_id())?;
    assert_eq!(after_first.len(), 1);

    import_bundle(&target, &bytes, &options)?;
    let after_second = lookup_author_key_entries(&target, signer.key_id())?;
    assert_eq!(
        after_second, after_first,
        "re-importing an unchanged bundle must not grow the author-key container"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// DC-53 Stage 2, §1's ratified edge case: exporting a `key_id` whose *local* material already
/// disagrees with itself (only reachable via a legacy pre-Stage-2 state, planted directly here)
/// must fail the export rather than silently pick one of the two conflicting keys -- presenting the
/// receiver with an arbitrarily-chosen key would look like a provenance claim this sender's own
/// repository does not actually make.
#[test]
fn export_fails_when_local_material_already_conflicts_for_an_exported_key_id()
-> prikk_error::Result<()> {
    let root = unique_temp_dir("dc53-export-local-conflict");
    let layout = RepositoryLayout::init(root.clone())?;
    let signer = transport_test_signer(0xa6)?;
    seal_two_block_history_with_author(&layout, &signer, true)?;
    force_conflicting_author_key_entry_for_test(&layout, signer.key_id(), [0xee; 32])?;

    let result = export_bundle(&layout, "heads/main");
    assert!(
        result.is_err(),
        "export must refuse rather than silently pick one of two conflicting local keys"
    );

    let _ = std::fs::remove_dir_all(root);
    Ok(())
}

/// DC-53 Stage 2, C1 (plan review): the author-key section's own declared count needs the same
/// DC-86 bound the object count already has -- a second declared count in a format a hostile
/// sender fully controls, with no bound, would reopen the hole DC-86 closed.
#[test]
fn author_key_count_limit_fires_exactly_at_the_boundary() -> prikk_error::Result<()> {
    let ref_name = "heads/main".to_string();
    let objects: Vec<ObjectEnvelope> = Vec::new();
    let author_keys = vec![
        AuthorKeyEntry {
            key_id: "a".to_string(),
            public_key: [1; 32],
        },
        AuthorKeyEntry {
            key_id: "b".to_string(),
            public_key: [2; 32],
        },
    ];
    let bytes = encode_bundle(&ref_name, &objects, &author_keys)?;

    let refused = decode_bundle(&bytes, 1);
    assert!(
        refused.is_err(),
        "a limit one below the actual author-key count (2) must refuse"
    );

    let accepted = decode_bundle(&bytes, 2);
    assert!(
        accepted.is_ok(),
        "a limit exactly at the actual author-key count (2) must accept"
    );

    Ok(())
}

/// DC-53 Stage 2 follow-up (bundle-v1-import-regression-v1.md): the actual migration path
/// `layout.rs`'s retired-format messages promise, walked end to end. A `PBNDL001` bundle -- encoded
/// the way a Stage-1-or-earlier build really produced one, not hand-edited bytes -- must import, its
/// Patch must read `Unverifiable` (never `Sound`: this bundle carries no author-key section at all,
/// regardless of what material the sender happened to have locally), and `verify_repository` must
/// pass and say so.
#[test]
fn a_pbndl001_bundle_imports_and_its_patch_reads_unverifiable() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc53-pbndl001-import-source");
    let source = RepositoryLayout::init(source_root.clone())?;

    // A genuinely, fully sealed history -- real commit, real seal, real adopted maintainer -- not
    // the lightweight `signed_block` structural fixture other tests in this file use, which never
    // computes a real state-merkle-root and so would fail `verify_repository`'s block-state stage
    // for reasons unrelated to this test. `verify passes and says so` (handoff §4) means a genuine
    // pass, not one read past unrelated fixture noise.
    let author = transport_test_signer(0xa8)?;
    let maintainer = Ed25519MaintainerSigner::from_seed("dc53-pbndl001-maintainer", &[0xa9; 32])?;
    crate::trust::add_trusted_maintainer(
        &source,
        maintainer.key_id(),
        &prikk_hash::to_hex(&maintainer.public_key_bytes()),
    )?;
    std::fs::write(source.root().join("v1-import.txt"), b"v1 import\n")?;
    crate::worktree_patch::commit_worktree_changes_signed(
        &source,
        "heads/main",
        "dc53 pbndl001 fixture",
        crate::worktree_patch::WorktreePatchCommitOptions::default(),
        &author,
    )?;
    // Records `author`'s key material locally on `source` as a side effect (the same production
    // path `node_authoring.rs` uses) -- the sender genuinely has material to carry, so the v1
    // path's own omission below is a real assertion, not an accident of the fixture having
    // nothing to drop.
    crate::rfc111_seal_simulation::simulate_one_seal(&source, "heads/main", &maintainer)?;

    let (_, v2_bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, author_keys) =
        decode_bundle(&v2_bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert_eq!(
        author_keys.len(),
        1,
        "sanity: the sender really did have material to carry"
    );
    let v1_bytes = encode_bundle_v1_for_test(&ref_name, &objects)?;

    let target_root = unique_temp_dir("dc53-pbndl001-import-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let import_report = import_bundle(&target, &v1_bytes, &BundleImportOptions::default_limits())?;
    assert_eq!(
        import_report.recorded_author_key_count, 0,
        "a PBNDL001 bundle carries no author-key section to record"
    );

    let imported_patch = find_imported_transport_patch(&target)?;
    let outcome = verify_author_signature(&target, &imported_patch)?;
    assert_eq!(
        outcome,
        Some((author.key_id().to_string(), false)),
        "expected Unverifiable, got {outcome:?}"
    );

    let report = crate::verify_repository(&target)?;
    assert!(
        !report.has_item_failure(),
        "verify must pass against a v1-imported repository: {report:?}"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

fn author_key_container_bytes(layout: &RepositoryLayout) -> prikk_error::Result<Vec<u8>> {
    let relative = layout.repository_relative(&layout.author_key_container_path())?;
    Ok(
        crate::fsutil::read_file_if_exists(layout.repository_mutation_root(), &relative)?
            .unwrap_or_default(),
    )
}

/// Byte-for-byte snapshot of the received-ref index's full on-disk state: both container slots plus
/// the generation log that decides which slot is live (RFC 102 Stage 6 Step 1's compaction shape).
/// An ordinary import only ever appends to the live slot, but comparing all three files, not just
/// one, is what makes "unchanged" a real claim rather than one that only holds for today's write
/// pattern.
fn received_index_bytes(
    layout: &RepositoryLayout,
) -> prikk_error::Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
    let read = |path: std::path::PathBuf| -> prikk_error::Result<Vec<u8>> {
        let relative = layout.repository_relative(&path)?;
        Ok(
            crate::fsutil::read_file_if_exists(layout.repository_mutation_root(), &relative)?
                .unwrap_or_default(),
        )
    };
    Ok((
        read(layout.received_index_slot_path(ContainerSlot::A))?,
        read(layout.received_index_slot_path(ContainerSlot::B))?,
        read(layout.received_index_generation_log_path())?,
    ))
}

// DC-78 `import-closure-validation-handoff-v1.md` §5: `import_bundle` validates the bundle's own
// closure -- ref target, patch-referenced blobs, block-named patches, block-named parents -- before
// any write, matching `accept_exchange_artifact`'s own precedent. Each row below has its own test;
// the corresponding negative control (removing the one check that row proves) was run by hand in an
// isolated, discarded worktree per this project's own standing review discipline, not encoded here.

/// §5 row 1: a bundle whose exported ref's target does not resolve -- carried by the bundle nor
/// already local -- is refused. Built exactly as report item 3 asks: a genuine tag-ref bundle, minus
/// the Tag envelope the DC-78 tag-export fix (`d605c10`) added -- the literal shape a pre-fix
/// `export_bundle` build used to emit for a tag ref. Confirms a pre-DC-78-shaped tag bundle can
/// actually be constructed in a test, not merely asserted to exist.
#[test]
fn row1_a_bundle_whose_ref_target_is_absent_is_refused() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc78-closure-row1-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let tip_block_id = seal_two_block_history(&source)?;
    let maintainer =
        Ed25519MaintainerSigner::from_seed("dc78-closure-row1-maintainer", &[0xc1; 32])?;
    let mut object_store = FileObjectStore::new(source.clone());
    publish_tag(
        &source,
        &mut object_store,
        "tags/v1",
        tip_block_id,
        &maintainer,
    )?;

    let (_, bytes) = export_bundle(&source, "tags/v1")?;
    let (ref_name, objects, author_keys) = decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert!(
        objects
            .iter()
            .any(|envelope| envelope.object_type == ObjectType::Tag),
        "fixture sanity: a genuine tag bundle must carry the Tag envelope"
    );
    let pre_fix_shaped_objects: Vec<ObjectEnvelope> = objects
        .into_iter()
        .filter(|envelope| envelope.object_type != ObjectType::Tag)
        .collect();
    let pre_fix_shaped_bytes = encode_bundle(&ref_name, &pre_fix_shaped_objects, &author_keys)?;

    let target_root = unique_temp_dir("dc78-closure-row1-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let result = import_bundle(
        &target,
        &pre_fix_shaped_bytes,
        &BundleImportOptions::default_limits(),
    );
    let err = match result {
        Ok(report) => panic!(
            "a bundle whose RefState targets a Tag object it never carried must be refused: \
             {report:?}"
        ),
        Err(err) => err,
    };
    assert!(
        err.to_string().contains("targets missing tag"),
        "unexpected error: {err}"
    );
    assert!(read_received_pointer(&target, "remotes/tags/v1")?.is_none());

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// §5 row 2: a bundle missing a blob a carried patch's operations reference is refused.
#[test]
fn row2_a_bundle_missing_a_referenced_blob_is_refused() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc78-closure-row2-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, author_keys) = decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert!(
        objects
            .iter()
            .any(|envelope| envelope.object_type == ObjectType::Blob),
        "fixture sanity"
    );
    let broken_objects: Vec<ObjectEnvelope> = objects
        .into_iter()
        .filter(|envelope| envelope.object_type != ObjectType::Blob)
        .collect();
    let broken_bytes = encode_bundle(&ref_name, &broken_objects, &author_keys)?;

    let target_root = unique_temp_dir("dc78-closure-row2-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let result = import_bundle(
        &target,
        &broken_bytes,
        &BundleImportOptions::default_limits(),
    );
    let err = match result {
        Ok(report) => {
            panic!("a bundle missing a patch-referenced blob must be refused: {report:?}")
        }
        Err(err) => err,
    };
    assert!(
        err.to_string().contains("references blob"),
        "unexpected error: {err}"
    );
    assert!(read_received_pointer(&target, "remotes/heads/main")?.is_none());

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// Review condition two (`DC-78-import-closure-validation-review-v1.md` §3): a Block's own
/// `snapshot_blob_ref` is a blob reference too, on the same terms as a Patch's own operations
/// (row 2's own property, restated for the other blob-naming site). A well-formed bundle carrying
/// the snapshot blob still imports and the blob lands; a bundle missing it is refused.
#[test]
fn row2b_a_bundle_missing_a_blocks_snapshot_blob_is_refused() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc78-closure-row2b-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let (_, snapshot_blob_id) = seal_two_block_history_with_snapshot_blob(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, author_keys) = decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert!(
        objects
            .iter()
            .any(|envelope| envelope.object_id() == snapshot_blob_id),
        "fixture sanity: the exported bundle must carry the block's own snapshot blob"
    );

    // Positive half: the well-formed bundle, snapshot blob included, still imports and the blob
    // actually lands.
    let good_target_root = unique_temp_dir("dc78-closure-row2b-good-target");
    let good_target = RepositoryLayout::init(good_target_root.clone())?;
    import_bundle(&good_target, &bytes, &BundleImportOptions::default_limits())?;
    let good_target_objects = FileObjectStore::new(good_target.clone());
    assert!(
        good_target_objects
            .read_typed(snapshot_blob_id, ObjectType::Blob)?
            .is_some(),
        "the snapshot blob must actually land in the receiving repository's store"
    );

    // Negative half: the same bundle, minus only the snapshot blob, is refused.
    let broken_objects: Vec<ObjectEnvelope> = objects
        .into_iter()
        .filter(|envelope| envelope.object_id() != snapshot_blob_id)
        .collect();
    let broken_bytes = encode_bundle(&ref_name, &broken_objects, &author_keys)?;

    let target_root = unique_temp_dir("dc78-closure-row2b-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let result = import_bundle(
        &target,
        &broken_bytes,
        &BundleImportOptions::default_limits(),
    );
    let err = match result {
        Ok(report) => {
            panic!("a bundle missing a block's own snapshot blob must be refused: {report:?}")
        }
        Err(err) => err,
    };
    assert!(
        err.to_string().contains("names snapshot blob"),
        "unexpected error: {err}"
    );
    assert!(read_received_pointer(&target, "remotes/heads/main")?.is_none());

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(good_target_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// §5 row 3: a bundle missing a block's own named patch is refused.
#[test]
fn row3_a_bundle_missing_a_blocks_patch_is_refused() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc78-closure-row3-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, author_keys) = decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert!(
        objects
            .iter()
            .any(|envelope| envelope.object_type == ObjectType::Patch),
        "fixture sanity"
    );
    let broken_objects: Vec<ObjectEnvelope> = objects
        .into_iter()
        .filter(|envelope| envelope.object_type != ObjectType::Patch)
        .collect();
    let broken_bytes = encode_bundle(&ref_name, &broken_objects, &author_keys)?;

    let target_root = unique_temp_dir("dc78-closure-row3-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let result = import_bundle(
        &target,
        &broken_bytes,
        &BundleImportOptions::default_limits(),
    );
    let err = match result {
        Ok(report) => {
            panic!("a bundle missing a block's own named patch must be refused: {report:?}")
        }
        Err(err) => err,
    };
    assert!(
        err.to_string().contains("names patch"),
        "unexpected error: {err}"
    );
    assert!(read_received_pointer(&target, "remotes/heads/main")?.is_none());

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// §5 row 4: a bundle missing a block's own named parent is refused.
#[test]
fn row4_a_bundle_missing_a_blocks_parent_is_refused() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc78-closure-row4-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let child_block_id = seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, author_keys) = decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    let is_root_block = |envelope: &ObjectEnvelope| {
        envelope.object_type == ObjectType::Block && envelope.object_id() != child_block_id
    };
    assert!(
        objects.iter().any(is_root_block),
        "fixture sanity: the root block must be present before removal"
    );
    let broken_objects: Vec<ObjectEnvelope> = objects
        .into_iter()
        .filter(|envelope| !is_root_block(envelope))
        .collect();
    let broken_bytes = encode_bundle(&ref_name, &broken_objects, &author_keys)?;

    let target_root = unique_temp_dir("dc78-closure-row4-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let result = import_bundle(
        &target,
        &broken_bytes,
        &BundleImportOptions::default_limits(),
    );
    let err = match result {
        Ok(report) => {
            panic!("a bundle missing a block's own named parent must be refused: {report:?}")
        }
        Err(err) => err,
    };
    assert!(
        err.to_string().contains("names parent"),
        "unexpected error: {err}"
    );
    assert!(read_received_pointer(&target, "remotes/heads/main")?.is_none());

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// §5 row 5: objects already held locally satisfy "present" -- the ordinary incremental case, not an
/// edge case (handoff §2/§5's own warning: this is the row most likely to be got wrong). Two
/// independent partial-bundle scenarios, one per surviving call site (review condition one,
/// `DC-78-import-closure-validation-review-v1.md` §2: the first version of this test only pinned the
/// patch and parent sites, not the blob site -- the blob happened to always ride along inside the
/// bundle whenever the Patch that references it did, so the blob check's own local-fallback half was
/// never actually exercised).
///
/// Scenario A hand-truncates a genuine bundle down to only its RefState and tip Block, after
/// pre-seeding the receiver with the Root block, Patch, and Blob directly -- pins the block's own
/// patch-presence and parent-presence checks (item 3, item 4).
///
/// Scenario B carries everything *except* the Blob -- RefState, both Blocks, and the Patch that
/// references it -- after pre-seeding only the Blob directly. This is what actually exercises the
/// blob-presence check's local-fallback half (item 2): that check only ever scans blobs referenced by
/// a Patch's operations, and it only scans a Patch that is itself decoded from the bundle's own
/// bytes -- so the blob site can only be pinned by a fixture where the Patch travels with the bundle
/// but its own Blob does not.
#[test]
fn row5_objects_already_held_locally_satisfy_present() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc78-closure-row5-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    let child_block_id = seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;

    // Scenario A: item 3 (block's own patch) and item 4 (block's own parent).
    let (ref_name, objects, author_keys) = decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    let target_root = unique_temp_dir("dc78-closure-row5-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let mut target_objects = FileObjectStore::new(target.clone());
    let mut carried_objects: Vec<ObjectEnvelope> = Vec::new();
    for envelope in objects {
        let already_local = match envelope.object_type {
            ObjectType::Block => envelope.object_id() != child_block_id,
            ObjectType::Patch | ObjectType::Blob => true,
            _ => false,
        };
        if already_local {
            target_objects.write_object(&envelope)?;
        } else {
            carried_objects.push(envelope);
        }
    }
    assert_eq!(
        carried_objects.len(),
        2,
        "fixture sanity: only the RefState and tip Block should remain in the partial bundle"
    );
    let partial_bytes = encode_bundle(&ref_name, &carried_objects, &author_keys)?;

    let report = import_bundle(
        &target,
        &partial_bytes,
        &BundleImportOptions::default_limits(),
    )?;
    assert_eq!(report.object_count, 2);
    assert_eq!(
        report.written_object_count, 2,
        "the pre-seeded objects must not be double-counted as newly written"
    );
    assert!(read_received_pointer(&target, "remotes/heads/main")?.is_some());
    assert!(
        target_objects
            .read_typed(child_block_id, ObjectType::Block)?
            .is_some()
    );

    // Scenario B: item 2 (blob referenced by a carried patch's own operations).
    let (ref_name_b, objects_b, author_keys_b) =
        decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    let target_b_root = unique_temp_dir("dc78-closure-row5-target-b");
    let target_b = RepositoryLayout::init(target_b_root.clone())?;
    let mut target_b_objects = FileObjectStore::new(target_b.clone());
    let mut carried_objects_b: Vec<ObjectEnvelope> = Vec::new();
    for envelope in objects_b {
        if envelope.object_type == ObjectType::Blob {
            target_b_objects.write_object(&envelope)?;
        } else {
            carried_objects_b.push(envelope);
        }
    }
    assert_eq!(
        carried_objects_b.len(),
        4,
        "fixture sanity: everything except the Blob should remain in this partial bundle"
    );
    assert!(
        carried_objects_b
            .iter()
            .any(|envelope| envelope.object_type == ObjectType::Patch),
        "fixture sanity: the Patch that references the omitted Blob must itself be carried, or \
         the blob check's own loop never runs"
    );
    let partial_bytes_b = encode_bundle(&ref_name_b, &carried_objects_b, &author_keys_b)?;

    let report_b = import_bundle(
        &target_b,
        &partial_bytes_b,
        &BundleImportOptions::default_limits(),
    )?;
    assert_eq!(report_b.object_count, 4);
    assert_eq!(
        report_b.written_object_count, 4,
        "the pre-seeded Blob must not be double-counted as newly written"
    );
    assert!(read_received_pointer(&target_b, "remotes/heads/main")?.is_some());

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    let _ = std::fs::remove_dir_all(target_b_root);
    Ok(())
}

/// §5 row 6: a refused import writes no received pointer and records no key material. Compared
/// byte-for-byte against both the received-ref index (all three on-disk files) and the author-key
/// container, each pre-seeded with a genuine, unrelated entry first -- an empty-to-empty comparison
/// would only prove nothing was ever written to an empty container, not that a refusal leaves
/// existing state untouched (the Stage 3 review's own row 1 model, mirrored here for
/// `import_bundle`'s second receiving path). The pre-seed is a genuine successful import for the
/// *same* ref name, so this also proves a hostile re-import cannot clobber a good existing pointer.
#[test]
fn row6_a_refused_import_writes_no_pointer_and_records_no_key_material() -> prikk_error::Result<()>
{
    let good_source_root = unique_temp_dir("dc78-closure-row6-good-source");
    let good_source = RepositoryLayout::init(good_source_root.clone())?;
    seal_two_block_history(&good_source)?;
    let (_, good_bytes) = export_bundle(&good_source, "heads/main")?;

    let target_root = unique_temp_dir("dc78-closure-row6-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    let good_report = import_bundle(&target, &good_bytes, &BundleImportOptions::default_limits())?;

    let unrelated_signer = transport_test_signer(0xc6)?;
    let unrelated_lock = ActiveLock::acquire(&target)?;
    record_author_key_material(
        &target,
        unrelated_signer.key_id(),
        unrelated_signer.public_key_bytes(),
        &unrelated_lock,
    )?;
    drop(unrelated_lock);

    let received_before = received_index_bytes(&target)?;
    let author_keys_before = author_key_container_bytes(&target)?;
    assert!(
        !received_before.0.is_empty() || !received_before.1.is_empty(),
        "fixture sanity"
    );
    assert!(!author_keys_before.is_empty(), "fixture sanity");

    // A different, hostile bundle for the SAME ref name -- row 3's shape (missing a block's own
    // named patch) -- carrying its own transportable author-key material, so "records no key
    // material" is a real assertion, not a vacuous one. Row 2's shape (a missing blob) will not do
    // here: `seal_two_block_history_with_author` and the good pre-seed above both build their Blob
    // from the same fixed fixture bytes, so it is content-addressed to the same id and the target
    // already holds it from the good import -- "already present locally" would correctly let it
    // through, proving the wrong thing for this test. The Patch and child Block differ between the
    // two fixtures (distinct paths/node ids), so removing the Patch is genuinely absent everywhere.
    let attack_signer = transport_test_signer(0xc7)?;
    let attack_source_root = unique_temp_dir("dc78-closure-row6-attack-source");
    let attack_source = RepositoryLayout::init(attack_source_root.clone())?;
    seal_two_block_history_with_author(&attack_source, &attack_signer, true)?;
    let (_, attack_bytes) = export_bundle(&attack_source, "heads/main")?;
    let (ref_name, objects, author_keys) =
        decode_bundle(&attack_bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    assert_eq!(
        author_keys.len(),
        1,
        "fixture sanity: the attack bundle must carry material"
    );
    let broken_objects: Vec<ObjectEnvelope> = objects
        .into_iter()
        .filter(|envelope| envelope.object_type != ObjectType::Patch)
        .collect();
    let broken_bytes = encode_bundle(&ref_name, &broken_objects, &author_keys)?;

    let result = import_bundle(
        &target,
        &broken_bytes,
        &BundleImportOptions::default_limits(),
    );
    assert!(result.is_err(), "the hostile re-import must be refused");

    let received_after = received_index_bytes(&target)?;
    let author_keys_after = author_key_container_bytes(&target)?;
    assert_eq!(
        received_before, received_after,
        "byte-for-byte: the received-ref index must be untouched by a refused import"
    );
    assert_eq!(
        author_keys_before, author_keys_after,
        "byte-for-byte: the author-key container must be untouched by a refused import"
    );

    let pointer = read_received_pointer(&target, "remotes/heads/main")?;
    assert_eq!(
        pointer.map(|pointer| pointer.ref_state_id),
        Some(good_report.ref_state_id),
        "the genuine earlier import's pointer must survive a refused re-import unchanged"
    );
    assert!(
        lookup_author_key_entries(&target, attack_signer.key_id())?.is_empty(),
        "the attack bundle's own key material must not be recorded"
    );

    let _ = std::fs::remove_dir_all(good_source_root);
    let _ = std::fs::remove_dir_all(attack_source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// §5 row 7 (regression guard): a well-formed bundle still imports, `PBNDL002` and `PBNDL001` alike.
#[test]
fn row7_a_well_formed_bundle_still_imports_both_formats() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc78-closure-row7-source");
    let source = RepositoryLayout::init(source_root.clone())?;
    seal_two_block_history(&source)?;
    let (_, bytes) = export_bundle(&source, "heads/main")?;
    let (ref_name, objects, _author_keys) = decode_bundle(&bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    let v1_bytes = encode_bundle_v1_for_test(&ref_name, &objects)?;

    let v2_target_root = unique_temp_dir("dc78-closure-row7-v2-target");
    let v2_target = RepositoryLayout::init(v2_target_root.clone())?;
    import_bundle(&v2_target, &bytes, &BundleImportOptions::default_limits())?;
    assert!(read_received_pointer(&v2_target, "remotes/heads/main")?.is_some());

    let v1_target_root = unique_temp_dir("dc78-closure-row7-v1-target");
    let v1_target = RepositoryLayout::init(v1_target_root.clone())?;
    import_bundle(
        &v1_target,
        &v1_bytes,
        &BundleImportOptions::default_limits(),
    )?;
    assert!(read_received_pointer(&v1_target, "remotes/heads/main")?.is_some());

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(v2_target_root);
    let _ = std::fs::remove_dir_all(v1_target_root);
    Ok(())
}

// DC-78 bundle-export tag-ref gap follow-up (`bundle-export-tag-ref-gap-v1.md`): a tag ref must
// resolve its second hop (ref -> Tag object -> Block) and the Tag envelope itself must travel,
// not just the Block closure it points to -- omitting it hands the receiver a signed RefState
// naming an object they do not have, and their own `verify` fails on exactly that (ruling §1).

/// Publish `tag_name` (a `tags/*` ref) pointing, via a Tag object, at `target_block_id`, every
/// object genuinely MAINTAINER-signed by `maintainer` -- matching `tag.rs`'s own doc, tags are
/// "maintainer-signed, on the same terms as `seal`/`branch create`", not the dummy structural
/// signature `test_support::signed_ref_state_envelope` uses (which cannot pass a real trust check).
fn publish_tag(
    layout: &RepositoryLayout,
    object_store: &mut FileObjectStore,
    tag_name: &str,
    target_block_id: ObjectId,
    maintainer: &Ed25519MaintainerSigner,
) -> prikk_error::Result<ObjectId> {
    let (patch_set_digest, patch_count) =
        crate::compute_patch_set_digest_and_count_from_block(object_store, target_block_id)?;
    let tag_payload = TagPayload {
        name: tag_name.to_string(),
        target_block_id,
        message: None,
        created_at: 0,
        author_key_id: maintainer.key_id().to_string(),
        patch_set_digest,
        patch_count,
    };
    let mut tag_envelope =
        ObjectEnvelope::unsigned(ObjectType::Tag, 1, tag_payload.to_canonical_bytes()?);
    let tag_object_id = tag_envelope.object_id();
    tag_envelope.add_signature(crate::maintainer_signature(
        maintainer,
        ObjectType::Tag,
        tag_object_id,
    )?)?;
    let tag_id = object_store.write_object(&tag_envelope)?;

    let ref_state_payload = RefStatePayload {
        ref_name: tag_name.to_string(),
        kind: RefKind::Tag,
        target_object_id: tag_id,
        update_seq: 1,
        previous_ref_state_id: None,
        required_attestation_ids: Vec::new(),
        closed: false,
    };
    let mut ref_state_envelope = ObjectEnvelope::unsigned(
        ObjectType::RefState,
        1,
        ref_state_payload.to_canonical_bytes()?,
    );
    let ref_state_id = ref_state_envelope.object_id();
    ref_state_envelope.add_signature(crate::maintainer_signature(
        maintainer,
        ObjectType::RefState,
        ref_state_id,
    )?)?;

    let ref_update_payload = RefUpdatePayload {
        ref_name: tag_name.to_string(),
        old_ref_state_id: None,
        new_ref_state_id: ref_state_id,
        new_target_object_id: tag_id,
        update_seq: 1,
        created_at: 0,
        author_key_id: maintainer.key_id().to_string(),
    };
    let mut ref_update_envelope = ObjectEnvelope::unsigned(
        ObjectType::RefUpdate,
        1,
        ref_update_payload.to_canonical_bytes()?,
    );
    let ref_update_id = ref_update_envelope.object_id();
    ref_update_envelope.add_signature(crate::maintainer_signature(
        maintainer,
        ObjectType::RefUpdate,
        ref_update_id,
    )?)?;

    let ref_store = RefStore::new(layout.clone());
    ref_store.publish_with_object_store(
        object_store,
        &RefPublication {
            ref_name: tag_name.to_string(),
            expected_previous_ref_state_id: None,
            ref_state: ref_state_envelope,
            ref_update: ref_update_envelope,
        },
    )?;
    Ok(tag_id)
}

/// Ruling §3's required addition, stronger than asserting the Tag object is merely present:
/// exporting a tag ref succeeds, and the receiver's own `verify_repository` passes against the
/// imported result -- the property that fails today (before the fix) because the receiver holds a
/// signed RefState naming a Tag object it never received.
///
/// Uses a genuinely, fully sealed history -- real commit, real seal, real adopted maintainer, the
/// same discipline `a_pbndl001_bundle_imports_and_its_patch_reads_unverifiable` documents above --
/// not the lightweight `signed_block` structural fixture, which never computes a real
/// state-merkle-root and would fail `verify_repository`'s block-state stage for reasons unrelated
/// to this test.
#[test]
fn export_of_a_tag_ref_succeeds_and_the_imported_bundle_verifies() -> prikk_error::Result<()> {
    let source_root = unique_temp_dir("dc78-tag-export-source");
    let source = RepositoryLayout::init(source_root.clone())?;

    let author = transport_test_signer(0xb4)?;
    let maintainer = Ed25519MaintainerSigner::from_seed("dc78-tag-maintainer", &[0xb5; 32])?;
    crate::trust::add_trusted_maintainer(
        &source,
        maintainer.key_id(),
        &prikk_hash::to_hex(&maintainer.public_key_bytes()),
    )?;
    std::fs::write(source.root().join("dc78-tag.txt"), b"dc78 tag fixture\n")?;
    crate::worktree_patch::commit_worktree_changes_signed(
        &source,
        "heads/main",
        "dc78 tag fixture",
        crate::worktree_patch::WorktreePatchCommitOptions::default(),
        &author,
    )?;
    let sealed_ref_state_id =
        crate::rfc111_seal_simulation::simulate_one_seal(&source, "heads/main", &maintainer)?;
    let source_object_store = FileObjectStore::new(source.clone());
    let sealed_ref_state_envelope = source_object_store
        .read_typed(sealed_ref_state_id, ObjectType::RefState)?
        .ok_or_else(|| prikk_error::PrikkError::Integrity("missing sealed RefState".to_string()))?;
    let sealed_ref_state_payload = RefStatePayload::decode_canonical(
        &sealed_ref_state_envelope.canonical_payload,
        sealed_ref_state_envelope.schema_version,
    )?;
    let tip_block_id = sealed_ref_state_payload.target_object_id;

    let mut object_store = FileObjectStore::new(source.clone());
    let tag_id = publish_tag(
        &source,
        &mut object_store,
        "tags/v1",
        tip_block_id,
        &maintainer,
    )?;

    let (_, bytes) = export_bundle(&source, "tags/v1")?;

    let target_root = unique_temp_dir("dc78-tag-export-target");
    let target = RepositoryLayout::init(target_root.clone())?;
    import_bundle(&target, &bytes, &BundleImportOptions::default_limits())?;

    let report = crate::verify_repository(&target)?;
    assert!(
        !report.has_item_failure(),
        "verify must pass against a repository that imported a tag bundle: {report:?}"
    );

    // Review condition (`DC-78-bundle-tag-gap-implementation-review-v1.md` §4): the export-side
    // closure-count test does not prove the Tag object actually *arrived* -- if import ever grew
    // object-type filtering, the exported count would stay +1 while the Tag stopped landing here,
    // and nothing above would notice. Assert arrival directly, on the receiving side, by id.
    let target_object_store = FileObjectStore::new(target.clone());
    assert!(
        target_object_store
            .read_typed(tag_id, ObjectType::Tag)?
            .is_some(),
        "the Tag object must be present in the receiving repository's store after import"
    );

    let _ = std::fs::remove_dir_all(source_root);
    let _ = std::fs::remove_dir_all(target_root);
    Ok(())
}

/// Ruling §1's structural claim, made executable: a tag ref and a `heads/*` ref pointing at the
/// same block export the identical Block/Patch/Blob closure -- the property that says the second
/// hop landed in the right place, not merely that it landed somewhere.
#[test]
fn tag_ref_and_heads_ref_at_the_same_block_export_the_same_object_closure()
-> prikk_error::Result<()> {
    let root = unique_temp_dir("dc78-tag-vs-heads-closure");
    let layout = RepositoryLayout::init(root.clone())?;
    let tip_block_id = seal_two_block_history(&layout)?;
    let maintainer =
        Ed25519MaintainerSigner::from_seed("dc78-tag-vs-heads-maintainer", &[0xb6; 32])?;
    let mut object_store = FileObjectStore::new(layout.clone());
    publish_tag(
        &layout,
        &mut object_store,
        "tags/v1",
        tip_block_id,
        &maintainer,
    )?;

    let (_, heads_bytes) = export_bundle(&layout, "heads/main")?;
    let (_, tag_bytes) = export_bundle(&layout, "tags/v1")?;

    let (_, heads_objects, _) = decode_bundle(&heads_bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;
    let (_, tag_objects, _) = decode_bundle(&tag_bytes, DEFAULT_BUNDLE_MAX_OBJECT_COUNT)?;

    let closure_only = |objects: &[ObjectEnvelope]| {
        objects
            .iter()
            .filter(|envelope| {
                matches!(
                    envelope.object_type,
                    ObjectType::Block | ObjectType::Patch | ObjectType::Blob
                )
            })
            .map(|envelope| (envelope.object_type, envelope.object_id()))
            .collect::<std::collections::BTreeSet<_>>()
    };
    assert_eq!(
        closure_only(&heads_objects),
        closure_only(&tag_objects),
        "a tag ref and a heads ref at the same block must export the identical Block/Patch/Blob \
         closure"
    );
    // The tag bundle carries one more object than the heads bundle: the Tag envelope itself.
    assert_eq!(tag_objects.len(), heads_objects.len() + 1);

    let _ = std::fs::remove_dir_all(root);
    Ok(())
}