File size: 86,276 Bytes
f74bce1
 
 
 
 
 
 
e70ca45
3127ce8
 
54d801e
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
08b4460
f74bce1
e70ca45
bcd0bca
d9a3ed6
cac098d
d9a3ed6
 
 
 
 
 
 
d417916
 
 
 
 
 
d9a3ed6
 
 
347a4d6
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7098eeb
 
 
d9a3ed6
 
6a909b2
 
36ebc46
 
d9a3ed6
 
2f1532d
 
6b7b99b
 
2608b33
 
50a1c46
 
4e3dd84
 
 
5b93402
 
d9a3ed6
 
 
 
 
 
 
9fa3c4f
 
 
 
 
 
 
 
 
931c763
 
 
 
 
 
 
 
 
 
 
 
 
347a4d6
931c763
 
 
f74bce1
 
 
 
cbb6866
7700633
2608b33
50a1c46
5b93402
72e4ba4
40cb975
bd6cbae
6609140
72e4ba4
f74bce1
 
 
f6b8fce
 
 
 
3127ce8
f6b8fce
f74bce1
 
 
 
3127ce8
 
f74bce1
 
 
 
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
e70ca45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcd0bca
 
e70ca45
 
bcd0bca
 
e70ca45
 
 
 
 
 
 
 
 
 
 
 
3127ce8
e70ca45
 
 
 
 
 
 
bcd0bca
e70ca45
 
 
 
 
 
 
 
f74bce1
 
 
 
d9a3ed6
f74bce1
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cac098d
 
 
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d417916
 
 
 
 
 
 
 
 
 
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
bcd0bca
 
 
 
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
931c763
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f74bce1
 
 
 
 
 
 
 
 
 
d9a3ed6
772a79f
2f1532d
0eb210c
7700633
2608b33
50a1c46
4e3dd84
5b93402
40cb975
6a909b2
bcd0bca
 
38d1263
bd6cbae
36ebc46
6609140
d9a3ed6
 
bede079
7098eeb
f74bce1
 
 
931c763
f74bce1
 
 
 
d9a3ed6
772a79f
2f1532d
0eb210c
7700633
2608b33
50a1c46
4e3dd84
5b93402
40cb975
6a909b2
bcd0bca
 
38d1263
bd6cbae
36ebc46
6609140
d9a3ed6
 
bede079
7098eeb
f74bce1
 
 
931c763
f74bce1
 
 
 
d9a3ed6
772a79f
2f1532d
0eb210c
7700633
2608b33
50a1c46
4e3dd84
5b93402
40cb975
6a909b2
bcd0bca
38d1263
bd6cbae
36ebc46
6609140
d9a3ed6
 
bede079
7098eeb
f74bce1
 
931c763
f74bce1
 
 
08b4460
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d417916
 
 
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00295ca
 
 
 
bede079
 
 
 
 
 
 
 
 
 
 
347a4d6
bede079
7098eeb
 
 
9fa3c4f
 
 
 
 
 
7098eeb
 
 
 
 
 
9fa3c4f
7098eeb
 
9fa3c4f
 
7098eeb
 
9fa3c4f
 
7098eeb
6a909b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36ebc46
 
 
3127ce8
 
 
 
 
36ebc46
 
 
 
 
 
 
 
 
3127ce8
36ebc46
 
 
 
3127ce8
 
 
36ebc46
 
 
 
 
 
38d1263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f1532d
 
 
 
a3aa614
 
2f1532d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3aa614
 
 
 
 
 
2f1532d
 
 
 
 
 
 
 
 
 
 
50a1c46
 
 
 
 
 
 
 
 
2608b33
 
 
 
 
cac098d
 
 
 
2608b33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cac098d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2608b33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cac098d
 
3127ce8
 
 
 
2608b33
50a1c46
 
 
 
 
 
 
 
 
 
4e3dd84
 
 
 
 
 
 
 
50a1c46
3127ce8
 
 
 
 
 
 
 
50a1c46
4e3dd84
 
 
 
 
931c763
 
 
 
 
 
 
 
 
 
 
4e3dd84
5b93402
 
 
 
 
a7a715a
 
 
 
 
 
 
 
 
 
 
 
 
5b93402
 
 
 
 
 
 
 
a7a715a
 
 
 
 
 
 
5b93402
 
 
a7a715a
 
 
 
 
 
 
 
 
 
 
 
 
f74bce1
 
 
 
 
 
 
 
 
 
 
08b4460
f74bce1
08b4460
f74bce1
 
 
 
 
08b4460
 
 
 
 
 
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
772a79f
 
 
 
 
 
 
f6b8fce
 
772a79f
 
 
 
 
 
 
 
2f1532d
 
 
 
 
 
 
 
 
a3aa614
2f1532d
 
 
 
0eb210c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7700633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2608b33
 
 
 
 
 
 
 
cac098d
c775d83
 
cac098d
 
2608b33
 
 
50a1c46
 
 
 
 
 
 
 
 
 
 
 
4e3dd84
 
931c763
4e3dd84
 
 
 
 
 
 
 
 
931c763
 
 
 
 
 
 
 
 
 
 
 
5b93402
 
 
 
 
 
 
 
 
 
 
 
40cb975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a909b2
 
 
 
 
 
 
 
 
 
 
 
 
bcd0bca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38d1263
 
 
 
 
 
 
 
 
 
 
 
bd6cbae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36ebc46
 
 
 
 
 
 
 
 
 
 
 
 
6609140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
d417916
d9a3ed6
 
 
 
 
 
 
d417916
61b791f
 
d9a3ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3127ce8
 
 
 
 
d9a3ed6
 
3127ce8
 
d9a3ed6
 
 
 
 
00295ca
3127ce8
 
 
 
d9a3ed6
 
 
 
 
00295ca
 
d9a3ed6
 
 
bede079
 
 
 
 
 
 
 
 
 
 
7098eeb
 
 
 
 
 
 
 
 
 
 
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08b4460
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a3ed6
 
 
 
 
 
 
 
 
 
772a79f
 
bede079
 
 
 
 
 
7098eeb
 
 
 
 
 
 
2f1532d
 
 
 
 
 
 
 
 
 
 
a3aa614
 
 
 
 
2f1532d
 
 
 
 
0eb210c
 
 
 
7700633
 
 
 
 
2608b33
 
cac098d
 
2608b33
 
 
 
 
 
 
 
c775d83
 
cac098d
 
 
2608b33
50a1c46
 
 
 
 
 
 
 
 
 
 
 
 
4e3dd84
 
 
 
 
 
 
 
 
931c763
 
 
 
 
 
 
 
5b93402
 
 
 
 
 
 
 
 
 
6a909b2
 
 
 
 
 
 
 
 
 
 
36ebc46
 
 
 
 
 
 
bcd0bca
 
 
 
38d1263
 
 
 
 
d9a3ed6
 
 
 
61b791f
d9a3ed6
 
d417916
d9a3ed6
 
 
 
 
 
 
 
 
 
 
bcd0bca
 
 
 
 
f74bce1
 
 
 
 
 
d9a3ed6
772a79f
2f1532d
0eb210c
7700633
2608b33
50a1c46
4e3dd84
5b93402
6a909b2
bcd0bca
 
38d1263
36ebc46
 
 
d9a3ed6
 
bede079
7098eeb
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a3ed6
 
772a79f
 
2f1532d
 
0eb210c
 
7700633
 
2608b33
 
50a1c46
 
4e3dd84
 
931c763
 
5b93402
 
3115d66
 
6a909b2
 
bcd0bca
 
 
 
38d1263
 
3115d66
 
36ebc46
 
3115d66
 
d9a3ed6
 
 
 
bede079
 
7098eeb
 
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54d801e
 
f74bce1
 
 
 
 
54d801e
 
 
 
 
 
 
 
 
 
 
 
f74bce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
#!/usr/bin/env python3
"""Verify the public Hugging Face Space is synced with judge-facing artifacts."""

from __future__ import annotations

import argparse
import json
from http.client import IncompleteRead
import socket
import ssl
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_JSON = ROOT / "docs" / "assets" / "public-space-sync-report.json"
DEFAULT_MD = ROOT / "docs" / "assets" / "public-space-sync-report.md"
SCHEMA = "proofframe.public_space_sync.v1"

SPACE_ID = "ADJCJH/backblaze-proofframe"
SPACE_HOST = "https://adjcjh-backblaze-proofframe.hf.space"
EXPECTED_SPACE_SHA = "auto"
TIMEOUT_SECONDS = 30
FETCH_RETRIES = 3
DRAFT_VIDEO_MIN_BYTES = 100_000
EVENT_SNAPSHOT_MAX_AGE_DAYS = 14
JUDGE_DECISION_BRIEF_MAX_AGE_DAYS = 14
POST_CREDENTIAL_REQUIRED_SEQUENCE = (
    "credential_handoff",
    "b2_live_proof",
    "validate_b2_evidence",
    "final_live_proof",
    "validate_final_evidence",
)
POST_CREDENTIAL_REQUIRED_REPORT_SEQUENCE = (
    "submission_audit",
    "devpost_submission_preview",
    "secret_scan",
    "submission_bundle",
)
SECRET_POLICY_REQUIRED_TERMS = (
    "never stores",
    "backblaze keys",
    "genblaze provider keys",
    "devpost cookies",
    "provider responses",
    "signed urls",
)
SECRET_POLICY_FORBIDDEN_TERMS = (
    "store secrets",
    "stores secrets",
    "store backblaze",
    "store genblaze",
    "store devpost",
    "store signed urls",
    "save secrets",
    "saves secrets",
    "include secrets",
    "includes secrets",
)
TASK_UPDATE_COMMAND_MARKERS = ("scripts/task.py", " task.py ", "--update-tasks")
REQUIRED_BUNDLE_ARTIFACT_IDS = {
    "repo_readme",
    "dockerignore",
    "docker_smoke_json",
    "docker_smoke_script",
    "devpost_packet_json",
    "public_space_sync_json",
    "public_demo_screenshot_json",
    "public_demo_screenshot_script",
    "devpost_preview_json",
    "devpost_preview_script",
    "post_credential_live_proof_json",
    "post_credential_live_proof_script",
    "b2_key_scope_checklist_json",
    "b2_key_scope_checklist_script",
    "genblaze_contract_json",
    "genblaze_contract_script",
    "judge_decision_brief_json",
    "judge_decision_brief_script",
    "judge_evidence_index_json",
    "judge_evidence_index_script",
    "final_closeout_status_json",
    "final_closeout_status_md",
    "final_closeout_status_script",
    "final_video_publish_kit_json",
    "final_video_publish_kit_script",
    "final_submission_control_json",
    "secret_scan_json",
    "submission_audit_json",
    "devpost_submission_checklist_json",
    "demo_video_draft_mp4",
    "task_ledger",
}
DOCKER_SMOKE_REQUIRED_CHECK_IDS = {
    "dockerignore_secret_exclusions",
    "docker_daemon",
    "docker_build",
    "docker_run",
    "docker_health",
    "api_smoke",
    "docker_cleanup",
}
FINAL_CLOSEOUT_REQUIRED_GATE_IDS = {
    "credential_handoff",
    "b2_live_proof",
    "genblaze_live_proof",
    "public_video",
    "devpost_receipt",
    "final_control",
}
FINAL_CLOSEOUT_PREFINAL_MODES = {"waiting_for_credentials", "closeout_blocked"}
FINAL_CLOSEOUT_FINAL_MODE = "final_closeout_ready"
FINAL_CLOSEOUT_SECRET_POLICY_TERMS = {
    "never stores",
    "backblaze keys",
    "genblaze provider keys",
    "devpost cookies",
    "signed urls",
}

HTML_MARKERS = {
    "judge_recording_slate": "Judge recording slate",
    "sponsor_evidence_model": "Sponsor Evidence Model",
    "judge_brief_panel": "30-Second Judge Brief",
    "criteria_crosswalk_link": "Criteria crosswalk",
    "decision_brief_link": "Decision brief",
    "evidence_index_link": "Evidence index",
    "video_publish_kit_link": "Video publish kit",
    "final_closeout_link": "Final closeout",
    "recording_runbook_panel": "Recording Runbook",
    "devpost_kit_panel": "Devpost Kit",
    "submit_checklist_panel": "Submit Checklist",
    "final_closeout_panel": "Final Closeout",
    "auto_load_judge_demo": "shouldAutoLoadJudgeDemo",
    "final_reports_pending": "Final reports pending",
}
PUBLIC_SAFE_LAUNCH_STATES = {
    ("ready_for_credential_entry", "credential_entry"),
    ("blocked_at_credential_entry", "credential_entry"),
    ("ready_for_genblaze_live_proof", "genblaze_live_proof"),
    ("ready_for_public_video", "public_video"),
}

FetchResult = dict[str, Any]
Fetcher = Callable[[str, int], FetchResult]

socket.setdefaulttimeout(TIMEOUT_SECONDS)


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def checked_at_age_days(checked_at: Any) -> int | None:
    if not isinstance(checked_at, str) or not checked_at:
        return None
    try:
        checked = datetime.fromisoformat(checked_at.replace("Z", "+00:00"))
    except ValueError:
        return None
    now = datetime.now(timezone.utc)
    return max(0, (now - checked.astimezone(timezone.utc)).days)


def fetch_text(url: str, timeout: int = TIMEOUT_SECONDS, retries: int = FETCH_RETRIES) -> FetchResult:
    attempts = max(1, retries)
    transient_result: FetchResult | None = None
    for attempt in range(1, attempts + 1):
        request = Request(url, headers={"User-Agent": "ProofFrame public Space sync verifier"})
        try:
            with urlopen(request, timeout=timeout) as response:
                raw_body = response.read()
                body = raw_body.decode("utf-8", errors="replace")
                return {
                    "ok": True,
                    "status": response.status,
                    "body": body,
                    "bytes": len(raw_body),
                    "content_type": response.headers.get("content-type"),
                    "error": None,
                }
        except HTTPError as error:
            raw_body = error.read()
            body = raw_body.decode("utf-8", errors="replace")
            return {
                "ok": False,
                "status": error.code,
                "body": body,
                "bytes": len(raw_body),
                "content_type": error.headers.get("content-type") if error.headers else None,
                "error": str(error),
            }
        except URLError as error:
            transient_result = {
                "ok": False,
                "status": None,
                "body": "",
                "bytes": 0,
                "content_type": None,
                "error": f"{error.reason} (attempt {attempt}/{attempts})",
            }
        except (TimeoutError, ConnectionResetError, IncompleteRead, socket.timeout, ssl.SSLError) as error:
            transient_result = {
                "ok": False,
                "status": None,
                "body": "",
                "bytes": 0,
                "content_type": None,
                "error": f"{error} (attempt {attempt}/{attempts})",
            }
    return transient_result or {
        "ok": False,
        "status": None,
        "body": "",
        "bytes": 0,
        "content_type": None,
        "error": "fetch failed",
    }


def parse_json(result: FetchResult) -> dict[str, Any] | None:
    try:
        parsed = json.loads(str(result.get("body") or ""))
    except json.JSONDecodeError:
        return None
    return parsed if isinstance(parsed, dict) else None


def dict_field(value: dict[str, Any] | None, key: str) -> dict[str, Any]:
    if not value:
        return {}
    field = value.get(key)
    return field if isinstance(field, dict) else {}


def list_field(value: dict[str, Any] | None, key: str) -> list[Any]:
    if not value:
        return []
    field = value.get(key)
    return field if isinstance(field, list) else []


def fields_match(value: dict[str, Any], expected: dict[str, Any]) -> bool:
    return all(value.get(key) == expected_value for key, expected_value in expected.items())


def dict_list_field(value: dict[str, Any] | None, key: str) -> list[dict[str, Any]]:
    items = list_field(value, key)
    if not all(isinstance(item, dict) for item in items):
        return []
    return items


def command_dicts(plan: dict[str, Any] | None) -> list[dict[str, Any]]:
    commands = dict_list_field(plan, "commands")
    if not commands:
        return []
    for command in commands:
        if not isinstance(command.get("id"), str) or not command.get("id"):
            return []
    return commands


def sequence_in_order(values: list[str], required: tuple[str, ...]) -> bool:
    search_start = 0
    for item in required:
        try:
            found_at = values.index(item, search_start)
        except ValueError:
            return False
        search_start = found_at + 1
    return True


def secret_policy_is_safe(policy: Any) -> bool:
    if not isinstance(policy, str):
        return False
    normalized = policy.lower()
    return all(term in normalized for term in SECRET_POLICY_REQUIRED_TERMS) and not any(
        term in normalized for term in SECRET_POLICY_FORBIDDEN_TERMS
    )


def no_task_update_commands(commands: list[dict[str, Any]]) -> bool:
    for command in commands:
        command_text = str(command.get("command") or "").lower()
        if any(marker in command_text for marker in TASK_UPDATE_COMMAND_MARKERS):
            return False
    return True


def sha256_like(value: Any) -> bool:
    return isinstance(value, str) and len(value) == 64 and all(char in "0123456789abcdef" for char in value.lower())


def artifact_is_present(artifact: dict[str, Any]) -> bool:
    path = artifact.get("path")
    return bool(
        isinstance(artifact.get("id"), str)
        and artifact.get("present") is True
        and isinstance(path, str)
        and path
        and not path.startswith("/")
        and isinstance(artifact.get("bytes"), int)
        and artifact.get("bytes", 0) > 0
        and sha256_like(artifact.get("sha256"))
    )


def report_status(reports: list[dict[str, Any]], report_id: str) -> dict[str, Any]:
    for report in reports:
        if report.get("id") == report_id:
            return report
    return {}


def space_api_url(space_id: str) -> str:
    return f"https://huggingface.co/api/spaces/{space_id}"


def runtime_api_url(space_id: str) -> str:
    return f"https://huggingface.co/api/spaces/{space_id}/runtime"


def raw_file_url(space_id: str, relative_path: str) -> str:
    return f"https://huggingface.co/spaces/{space_id}/raw/main/{relative_path}"


def resolve_file_url(space_id: str, relative_path: str) -> str:
    return f"https://huggingface.co/spaces/{space_id}/resolve/main/{relative_path}"


def public_url(host: str, path: str) -> str:
    return f"{host.rstrip('/')}{path}"


def check_item(check_id: str, label: str, ok: bool, detail: str, evidence: str) -> dict[str, Any]:
    return {
        "id": check_id,
        "label": label,
        "ok": ok,
        "detail": detail,
        "evidence": evidence,
    }


def final_closeout_status_is_public_safe(status: dict[str, Any] | None) -> bool:
    if not status:
        return False
    gates = dict_list_field(status, "gates")
    gate_ids = {str(gate.get("id")) for gate in gates if isinstance(gate.get("id"), str)}
    secret_policy = str(status.get("secret_policy") or "").lower()
    secret_policy_ok = all(term in secret_policy for term in FINAL_CLOSEOUT_SECRET_POLICY_TERMS)
    common_ok = bool(
        status.get("schema") == "proofframe.final_closeout_status.v1"
        and status.get("ok") is True
        and status.get("closeout_health_ok") is True
        and isinstance(status.get("safe_to_submit"), bool)
        and status.get("next_command")
        and FINAL_CLOSEOUT_REQUIRED_GATE_IDS <= gate_ids
        and secret_policy_ok
    )
    if not common_ok:
        return False
    all_gates_ok = all(gate.get("ok") is True for gate in gates)
    has_blocker = any(gate.get("ok") is False for gate in gates)
    if status.get("safe_to_submit") is True:
        return bool(status.get("mode") == FINAL_CLOSEOUT_FINAL_MODE and all_gates_ok)
    return bool(status.get("mode") in FINAL_CLOSEOUT_PREFINAL_MODES and has_blocker)


def build_report(
    *,
    space_id: str = SPACE_ID,
    public_host: str = SPACE_HOST,
    expected_sha: str = EXPECTED_SPACE_SHA,
    fetcher: Fetcher = fetch_text,
) -> dict[str, Any]:
    api_url = space_api_url(space_id)
    runtime_url = runtime_api_url(space_id)
    handoff_url = raw_file_url(space_id, "docs/assets/agent-handoff-report.json")
    event_snapshot_url = raw_file_url(space_id, "docs/assets/devpost-event-snapshot.json")
    launch_plan_url = raw_file_url(space_id, "docs/assets/final-launch-plan.json")
    b2_key_scope_checklist_url = raw_file_url(space_id, "docs/assets/b2-key-scope-checklist.json")
    judge_brief_url = raw_file_url(space_id, "docs/assets/judge-brief.json")
    judge_crosswalk_url = raw_file_url(space_id, "docs/assets/judge-crosswalk.json")
    judge_decision_brief_url = raw_file_url(space_id, "docs/assets/judge-decision-brief.json")
    judge_evidence_index_url = raw_file_url(space_id, "docs/assets/judge-evidence-index.json")
    final_closeout_status_url = raw_file_url(space_id, "docs/assets/final-closeout-status.json")
    video_publish_kit_url = raw_file_url(space_id, "docs/assets/final-video-publish-kit.json")
    recording_assets_url = raw_file_url(space_id, "docs/assets/recording-assets.json")
    public_demo_screenshot_url = raw_file_url(space_id, "docs/assets/public-demo-screenshot-report.json")
    demo_video_draft_url = raw_file_url(space_id, "docs/assets/demo-video-draft.json")
    demo_video_draft_mp4_url = resolve_file_url(space_id, "docs/assets/proofframe-demo-draft.mp4")
    public_video_check_url = raw_file_url(space_id, "docs/assets/public-video-check.json")
    devpost_form_kit_url = raw_file_url(space_id, "docs/assets/devpost-form-kit.json")
    devpost_preview_url = raw_file_url(space_id, "docs/assets/devpost-submission-preview.json")
    submit_checklist_url = raw_file_url(space_id, "docs/assets/devpost-submission-checklist.json")
    post_credential_plan_url = raw_file_url(space_id, "docs/assets/post-credential-live-proof-plan.json")
    submission_bundle_url = raw_file_url(space_id, "docs/assets/submission-bundle-manifest.json")
    genblaze_contract_url = raw_file_url(space_id, "docs/assets/genblaze-contract-report.json")
    docker_smoke_url = raw_file_url(space_id, "docs/assets/docker-smoke-report.json")
    judge_url = public_url(public_host, "/?judge=1")
    health_url = public_url(public_host, "/api/health")
    gate_url = public_url(public_host, "/api/submission/gate")
    final_closeout_endpoint_url = public_url(public_host, "/api/judge/final-closeout")

    space_result = fetcher(api_url, TIMEOUT_SECONDS)
    runtime_result = fetcher(runtime_url, TIMEOUT_SECONDS)
    handoff_result = fetcher(handoff_url, TIMEOUT_SECONDS)
    event_snapshot_result = fetcher(event_snapshot_url, TIMEOUT_SECONDS)
    launch_plan_result = fetcher(launch_plan_url, TIMEOUT_SECONDS)
    b2_key_scope_checklist_result = fetcher(b2_key_scope_checklist_url, TIMEOUT_SECONDS)
    judge_brief_result = fetcher(judge_brief_url, TIMEOUT_SECONDS)
    judge_crosswalk_result = fetcher(judge_crosswalk_url, TIMEOUT_SECONDS)
    judge_decision_brief_result = fetcher(judge_decision_brief_url, TIMEOUT_SECONDS)
    judge_evidence_index_result = fetcher(judge_evidence_index_url, TIMEOUT_SECONDS)
    final_closeout_status_result = fetcher(final_closeout_status_url, TIMEOUT_SECONDS)
    video_publish_kit_result = fetcher(video_publish_kit_url, TIMEOUT_SECONDS)
    recording_assets_result = fetcher(recording_assets_url, TIMEOUT_SECONDS)
    public_demo_screenshot_result = fetcher(public_demo_screenshot_url, TIMEOUT_SECONDS)
    demo_video_draft_result = fetcher(demo_video_draft_url, TIMEOUT_SECONDS)
    demo_video_draft_mp4_result = fetcher(demo_video_draft_mp4_url, TIMEOUT_SECONDS)
    public_video_check_result = fetcher(public_video_check_url, TIMEOUT_SECONDS)
    devpost_form_kit_result = fetcher(devpost_form_kit_url, TIMEOUT_SECONDS)
    devpost_preview_result = fetcher(devpost_preview_url, TIMEOUT_SECONDS)
    submit_checklist_result = fetcher(submit_checklist_url, TIMEOUT_SECONDS)
    post_credential_plan_result = fetcher(post_credential_plan_url, TIMEOUT_SECONDS)
    submission_bundle_result = fetcher(submission_bundle_url, TIMEOUT_SECONDS)
    genblaze_contract_result = fetcher(genblaze_contract_url, TIMEOUT_SECONDS)
    docker_smoke_result = fetcher(docker_smoke_url, TIMEOUT_SECONDS)
    judge_result = fetcher(judge_url, TIMEOUT_SECONDS)
    health_result = fetcher(health_url, TIMEOUT_SECONDS)
    gate_result = fetcher(gate_url, TIMEOUT_SECONDS)
    final_closeout_endpoint_result = fetcher(final_closeout_endpoint_url, TIMEOUT_SECONDS)

    space = parse_json(space_result)
    runtime = parse_json(runtime_result)
    handoff = parse_json(handoff_result)
    event_snapshot = parse_json(event_snapshot_result)
    launch_plan = parse_json(launch_plan_result)
    b2_key_scope_checklist = parse_json(b2_key_scope_checklist_result)
    judge_brief = parse_json(judge_brief_result)
    judge_crosswalk = parse_json(judge_crosswalk_result)
    judge_decision_brief = parse_json(judge_decision_brief_result)
    judge_evidence_index = parse_json(judge_evidence_index_result)
    final_closeout_status = parse_json(final_closeout_status_result)
    video_publish_kit = parse_json(video_publish_kit_result)
    recording_assets = parse_json(recording_assets_result)
    public_demo_screenshot = parse_json(public_demo_screenshot_result)
    demo_video_draft = parse_json(demo_video_draft_result)
    public_video_check = parse_json(public_video_check_result)
    devpost_form_kit = parse_json(devpost_form_kit_result)
    devpost_preview = parse_json(devpost_preview_result)
    submit_checklist = parse_json(submit_checklist_result)
    post_credential_plan = parse_json(post_credential_plan_result)
    submission_bundle = parse_json(submission_bundle_result)
    genblaze_contract = parse_json(genblaze_contract_result)
    docker_smoke = parse_json(docker_smoke_result)
    health = parse_json(health_result)
    gate = parse_json(gate_result)
    final_closeout_endpoint = parse_json(final_closeout_endpoint_result)
    html = str(judge_result.get("body") or "")

    space_sha = space.get("sha") if space else None
    resolved_expected_sha = space_sha if expected_sha in {"", "auto"} else expected_sha
    runtime_sha = runtime.get("sha") if runtime else None
    runtime_stage = runtime.get("stage") if runtime else None
    domain_ready = any(
        domain.get("stage") == "READY" for domain in (runtime.get("domains", []) if runtime else [])
    )
    html_markers = {marker_id: marker in html for marker_id, marker in HTML_MARKERS.items()}
    gate_paths = [
        gate.get("tasks_path") if gate else None,
        gate.get("evidence_gate", {}).get("path") if gate else None,
        gate.get("packet_gate", {}).get("path") if gate else None,
    ]
    gate_paths_relative = bool(
        gate and all(isinstance(path, str) and path and not path.startswith("/") for path in gate_paths)
    )
    report_gate_status = dict_field(gate, "report_gate").get("status") if gate else None
    event_snapshot_event = dict_field(event_snapshot, "event")
    event_snapshot_rules = dict_field(event_snapshot, "rules")
    event_snapshot_validation = dict_field(event_snapshot, "validation")
    event_snapshot_sources = dict_list_field(event_snapshot, "sources")
    event_snapshot_requirements = dict_field(event_snapshot_rules, "requirements")
    event_snapshot_criteria = dict_list_field(event_snapshot_rules, "judging_criteria")
    event_snapshot_age_days = checked_at_age_days(event_snapshot.get("checked_at") if event_snapshot else None)
    event_snapshot_sources_ok = len(event_snapshot_sources) >= 2 and all(
        source.get("ok") is True and source.get("status") == 200 for source in event_snapshot_sources
    )
    event_snapshot_requirements_ok = bool(event_snapshot_requirements) and all(
        present is True for present in event_snapshot_requirements.values()
    )
    event_snapshot_criteria_ok = len(event_snapshot_criteria) >= 4 and all(
        criterion.get("present") is True for criterion in event_snapshot_criteria
    )
    post_credential_commands = command_dicts(post_credential_plan)
    post_credential_command_ids = [str(command["id"]) for command in post_credential_commands]
    post_credential_sequence_ok = (
        post_credential_command_ids[: len(POST_CREDENTIAL_REQUIRED_SEQUENCE)]
        == list(POST_CREDENTIAL_REQUIRED_SEQUENCE)
    )
    post_credential_report_sequence_ok = sequence_in_order(
        post_credential_command_ids,
        POST_CREDENTIAL_REQUIRED_REPORT_SEQUENCE,
    )
    post_credential_no_task_update = no_task_update_commands(post_credential_commands)
    post_credential_secret_policy_ok = secret_policy_is_safe(
        post_credential_plan.get("secret_policy") if post_credential_plan else None
    )
    submission_bundle_artifacts = dict_list_field(submission_bundle, "artifacts")
    submission_bundle_artifact_ids = {
        str(artifact.get("id")) for artifact in submission_bundle_artifacts if isinstance(artifact.get("id"), str)
    }
    submission_bundle_required_artifacts_ok = REQUIRED_BUNDLE_ARTIFACT_IDS <= submission_bundle_artifact_ids
    submission_bundle_artifacts_valid = bool(submission_bundle_artifacts) and all(
        artifact_is_present(artifact) for artifact in submission_bundle_artifacts
    )
    submission_bundle_missing_artifacts = list_field(submission_bundle, "missing_artifacts")
    submission_bundle_devpost_packet = dict_field(submission_bundle, "devpost_packet")
    submission_bundle_gate = dict_field(submission_bundle, "submission_gate")
    submission_bundle_packet_gate = dict_field(submission_bundle_gate, "packet_gate")
    submission_bundle_evidence_gate = dict_field(submission_bundle_gate, "evidence_gate")
    submission_bundle_report_gate = dict_field(submission_bundle_gate, "report_gate")
    submission_bundle_reports = dict_list_field(submission_bundle_report_gate, "reports")
    submission_bundle_secret_scan = report_status(submission_bundle_reports, "secret_scan")
    submission_bundle_submission_audit = report_status(submission_bundle_reports, "submission_audit")
    submission_bundle_next_actions = list_field(submission_bundle_gate, "next_actions")
    submission_bundle_summary = dict_field(submission_bundle_gate, "summary")
    submission_bundle_b2_action_ok = any(
        "Backblaze B2" in str(action) for action in submission_bundle_next_actions
    ) or int(submission_bundle_summary.get("done") or 0) >= 2
    genblaze_contract_failed_checks = list_field(genblaze_contract, "failed_checks")
    genblaze_contract_secret_policy = str(genblaze_contract.get("secret_policy") if genblaze_contract else "")
    genblaze_contract_ok = bool(
        genblaze_contract_result.get("ok")
        and genblaze_contract
        and genblaze_contract.get("schema") == "proofframe.genblaze_contract_check.v1"
        and genblaze_contract.get("ok") is True
        and genblaze_contract.get("mode") == "sdk_contract_ready"
        and genblaze_contract_failed_checks == []
        and "does not read environment variables" in genblaze_contract_secret_policy
        and "Backblaze keys" in genblaze_contract_secret_policy
        and "Genblaze provider keys" in genblaze_contract_secret_policy
    )
    docker_smoke_dockerignore = dict_field(docker_smoke, "dockerignore")
    docker_smoke_health = dict_field(docker_smoke, "health")
    docker_smoke_health_json = dict_field(docker_smoke_health, "json")
    docker_smoke_checks = dict_list_field(docker_smoke, "checks")
    docker_smoke_check_status = {str(check.get("id")): check.get("ok") is True for check in docker_smoke_checks}
    docker_smoke_required_checks_ok = (
        DOCKER_SMOKE_REQUIRED_CHECK_IDS <= set(docker_smoke_check_status)
        and all(docker_smoke_check_status[check_id] for check_id in DOCKER_SMOKE_REQUIRED_CHECK_IDS)
    )
    docker_smoke_ok = bool(
        docker_smoke_result.get("ok")
        and docker_smoke
        and docker_smoke.get("schema") == "proofframe.docker_smoke.v1"
        and docker_smoke.get("ok") is True
        and docker_smoke.get("mode") == "docker_smoke_ready"
        and docker_smoke_required_checks_ok
        and docker_smoke_dockerignore.get("missing_required_patterns") == []
        and docker_smoke_dockerignore.get("missing_allow_patterns") == []
        and docker_smoke_health.get("ok") is True
        and docker_smoke_health_json.get("ready") is True
        and docker_smoke_health_json.get("storage_backend") == "local"
        and docker_smoke_health_json.get("generation_backend") == "mock"
        and docker_smoke_health_json.get("b2_configured") is False
        and docker_smoke_health_json.get("genblaze_configured") is False
    )
    public_demo_screenshot_markers = dict_field(public_demo_screenshot, "markers")
    public_demo_screenshot_visible = dict_field(public_demo_screenshot_markers, "visible")
    public_demo_screenshot_html = dict_field(public_demo_screenshot_markers, "html")
    public_demo_screenshot_image = dict_field(public_demo_screenshot, "screenshot")
    public_demo_screenshot_ok = bool(
        public_demo_screenshot_result.get("ok")
        and public_demo_screenshot
        and public_demo_screenshot.get("schema") == "proofframe.public_demo_screenshot.v1"
        and public_demo_screenshot.get("ok") is True
        and public_demo_screenshot.get("safe_to_commit") is True
        and public_demo_screenshot.get("mode") == "public_judge_screenshot_ready"
        and public_demo_screenshot_markers.get("visible_ok") is True
        and public_demo_screenshot_markers.get("html_ok") is True
        and public_demo_screenshot_visible.get("sponsor_evidence_model", {}).get("present") is True
        and public_demo_screenshot_visible.get("final_reports_pending", {}).get("present") is True
        and public_demo_screenshot_html.get("judge_recording_slate", {}).get("present") is True
        and public_demo_screenshot_html.get("auto_load_judge_demo", {}).get("present") is True
        and public_demo_screenshot_image.get("path") == "docs/assets/proofframe-hf-public-smoke.png"
        and (public_demo_screenshot_image.get("bytes") or 0) >= 100_000
        and (public_demo_screenshot_image.get("width") or 0) >= 1200
        and (public_demo_screenshot_image.get("height") or 0) >= 900
    )
    devpost_preview_readiness = dict_field(devpost_preview, "submission_readiness")
    devpost_preview_field_rollup = dict_field(devpost_preview, "field_rollup")
    devpost_preview_blockers = list_field(devpost_preview_readiness, "final_blockers")
    devpost_preview_blocker_ids = {
        str(blocker.get("id"))
        for blocker in devpost_preview_blockers
        if isinstance(blocker, dict) and isinstance(blocker.get("id"), str)
    }
    devpost_preview_evidence_links = dict_field(devpost_preview, "evidence_links")
    devpost_preview_ok = bool(
        devpost_preview_result.get("ok")
        and devpost_preview
        and devpost_preview.get("schema") == "proofframe.devpost_submission_preview.v1"
        and devpost_preview.get("ok") is True
        and devpost_preview.get("safe_to_share") is True
        and devpost_preview.get("safe_to_submit") is False
        and devpost_preview.get("mode") == "pre_live_preview_ready"
        and devpost_preview_readiness.get("packet_mode") in {"pre_live_safe", "post_live_verified"}
        and devpost_preview_readiness.get("public_space_mode") == "public_space_synced"
        and devpost_preview_readiness.get("public_screenshot_mode") == "public_judge_screenshot_ready"
        and devpost_preview_field_rollup.get("mock_ready") is True
        and devpost_preview_field_rollup.get("final_ready") is False
        and (
            "genblaze_live_proof" in devpost_preview_blocker_ids
            or {"public_video", "public_video_check"} <= devpost_preview_blocker_ids
        )
        and devpost_preview_evidence_links.get("public_demo")
        == "https://adjcjh-backblaze-proofframe.hf.space/?judge=1"
        and devpost_preview_evidence_links.get("public_screenshot")
        == "docs/assets/proofframe-hf-public-smoke.png"
    )
    public_video_check_checks = dict_list_field(public_video_check, "checks")
    public_video_check_by_id = {
        str(item.get("id")): item for item in public_video_check_checks if isinstance(item.get("id"), str)
    }
    public_video_official_host_check = public_video_check_by_id.get("video_url_official_public_host", {})
    public_video_next_actions = list_field(public_video_check, "next_actions")
    public_video_check_ok = bool(
        public_video_check_result.get("ok")
        and public_video_check
        and public_video_check.get("schema") == "proofframe.public_video_check.v1"
        and public_video_check.get("mode") in {"pending_video_url", "public_video_verified"}
        and public_video_check.get("safe_to_submit") is False
        and public_video_check.get("url_analysis", {}).get("official_host") is False
        and public_video_check.get("url_analysis", {}).get("reason") == "missing_or_placeholder"
        and public_video_official_host_check.get("ok") is False
        and "YouTube, Vimeo, and Youku" in str(public_video_official_host_check.get("detail") or "")
        and any("YouTube, Vimeo, or Youku" in str(action) for action in public_video_next_actions)
    )
    b2_key_scope_expected = dict_field(b2_key_scope_checklist, "expected_key")
    b2_key_scope_bucket = dict_field(b2_key_scope_expected, "bucket_scope")
    b2_key_scope_prefix = dict_field(b2_key_scope_expected, "file_name_prefix")
    b2_key_scope_secret_policy = dict_field(b2_key_scope_checklist, "secret_policy")
    b2_key_scope_confirmation = dict_field(b2_key_scope_checklist, "pre_key_creation_confirmation")
    b2_key_scope_confirmation_phrase = str(b2_key_scope_confirmation.get("required_phrase", ""))
    b2_key_scope_required_capabilities = {
        str(item.get("capability"))
        for item in dict_list_field(b2_key_scope_expected, "required_capabilities")
    }
    b2_key_scope_conditional_capabilities = {
        str(item.get("capability")): item
        for item in dict_list_field(b2_key_scope_expected, "conditional_capabilities")
    }
    b2_key_scope_forbidden_capabilities = {
        str(item.get("capability"))
        for item in dict_list_field(b2_key_scope_expected, "forbidden_capabilities")
    }
    b2_key_scope_ok = bool(
        b2_key_scope_checklist_result.get("ok")
        and b2_key_scope_checklist
        and b2_key_scope_checklist.get("schema") == "proofframe.b2_key_scope_checklist.v1"
        and b2_key_scope_checklist.get("ok") is True
        and b2_key_scope_checklist.get("safe_to_commit") is True
        and b2_key_scope_checklist.get("requires_user_confirmation_before_key_creation") is True
        and b2_key_scope_confirmation.get("status") == "required_before_key_creation"
        and b2_key_scope_confirmation.get("safe_to_store") is True
        and "proofframe-demo-a6b4e49" in b2_key_scope_confirmation_phrase
        and "campaigns/" in b2_key_scope_confirmation_phrase
        and "no delete/admin permissions" in b2_key_scope_confirmation_phrase
        and "no secrets in chat/docs/git" in b2_key_scope_confirmation_phrase
        and b2_key_scope_secret_policy.get("forbidden_setup_fields") == []
        and b2_key_scope_bucket.get("mode") == "single_bucket"
        and b2_key_scope_bucket.get("bucket_name") == "proofframe-demo-a6b4e49"
        and b2_key_scope_bucket.get("forbidden") == "all_buckets"
        and b2_key_scope_prefix.get("value") == "campaigns/"
        and {"writeFiles", "listAllBucketNames"} <= b2_key_scope_required_capabilities
        and b2_key_scope_conditional_capabilities.get("readFiles", {}).get("required_now") == "false"
        and b2_key_scope_conditional_capabilities.get("listFiles", {}).get("required_now") == "false"
        and "deleteFiles" in b2_key_scope_forbidden_capabilities
        and "writeBuckets/deleteBuckets" in b2_key_scope_forbidden_capabilities
    )
    judge_evidence_index_links = dict_list_field(judge_evidence_index, "links")
    judge_evidence_index_sections = dict_list_field(judge_evidence_index, "sections")
    judge_evidence_index_blockers = list_field(
        dict_field(judge_evidence_index, "status"),
        "final_blockers",
    )
    judge_evidence_index_link_ids = {
        str(link.get("id")) for link in judge_evidence_index_links if isinstance(link.get("id"), str)
    }
    judge_decision_checks = dict_list_field(judge_decision_brief, "decision_checks")
    judge_decision_check_ids = {
        str(item.get("id")) for item in judge_decision_checks if isinstance(item.get("id"), str)
    }
    judge_decision_source_reports = dict_field(judge_decision_brief, "source_reports")
    judge_decision_public_state = dict_field(judge_decision_brief, "public_state")
    judge_decision_links = dict_field(judge_decision_brief, "links")
    judge_decision_created_at = judge_decision_brief.get("created_at") if judge_decision_brief else None
    judge_decision_age_days = checked_at_age_days(judge_decision_created_at)
    judge_decision_required_sources_ok = all(
        dict_field(judge_decision_source_reports, source_id).get("schema_ok") is True
        for source_id in {
            "judge_brief",
            "judge_crosswalk",
            "judge_evidence_index",
            "award_readiness",
            "final_control",
            "public_space_sync",
            "devpost_preview",
            "video_publish_kit",
            "secret_scan",
            "event_snapshot",
        }
    )
    judge_decision_source_state_ok = all(
        (
            fields_match(
                dict_field(judge_decision_source_reports, "judge_crosswalk"),
                {"ok": True, "mode": "pre_live_crosswalk_ready", "safe_to_submit": False},
            ),
            fields_match(
                dict_field(judge_decision_source_reports, "judge_evidence_index"),
                {
                    "ok": True,
                    "mode": "pre_live_evidence_index_ready",
                    "safe_to_share": True,
                    "safe_to_submit": False,
                },
            ),
            fields_match(
                dict_field(judge_decision_source_reports, "final_control"),
                {"ok": True, "mode": "pre_live_control", "safe_to_submit": False},
            ),
            fields_match(
                dict_field(judge_decision_source_reports, "public_space_sync"),
                {"ok": True, "mode": "public_space_synced"},
            ),
            fields_match(
                dict_field(judge_decision_source_reports, "devpost_preview"),
                {
                    "mode": "pre_live_preview_ready",
                    "safe_to_share": True,
                    "safe_to_submit": False,
                },
            ),
            fields_match(
                dict_field(judge_decision_source_reports, "video_publish_kit"),
                {
                    "ok": True,
                    "mode": "ready_for_final_upload",
                    "safe_to_share": True,
                    "safe_to_submit": False,
                },
            ),
            fields_match(
                dict_field(judge_decision_source_reports, "secret_scan"),
                {"ok": True, "mode": "clear"},
            ),
            fields_match(
                dict_field(judge_decision_source_reports, "event_snapshot"),
                {"mode": "live_official_snapshot"},
            ),
        )
    )
    judge_decision_fresh_ok = bool(
        isinstance(judge_decision_created_at, str)
        and judge_decision_age_days is not None
        and judge_decision_age_days <= JUDGE_DECISION_BRIEF_MAX_AGE_DAYS
        and "judge-evidence-index.md" in str(judge_decision_links.get("evidence_index") or "")
    )
    judge_decision_brief_ok = bool(
        judge_decision_brief_result.get("ok")
        and judge_decision_brief
        and judge_decision_brief.get("schema") == "proofframe.judge_decision_brief.v1"
        and judge_decision_brief.get("ok") is True
        and judge_decision_brief.get("safe_to_share") is True
        and judge_decision_brief.get("safe_to_submit") is False
        and judge_decision_brief.get("mode") == "pre_live_decision_ready"
        and len(judge_decision_checks) >= 6
        and {
            "public_demo_runs",
            "criteria_are_mapped",
            "award_case_is_competitive",
            "claims_are_fail_closed",
            "video_submission_is_gated",
            "no_secret_exposure",
        }
        <= judge_decision_check_ids
        and all(item.get("ok") is True for item in judge_decision_checks)
        and judge_decision_required_sources_ok
        and judge_decision_source_state_ok
        and judge_decision_fresh_ok
        and (
            "does not claim completed Backblaze B2" in str(judge_decision_brief.get("claim_boundary") or "")
            or "may cite completed B2 and Genblaze proof" in str(judge_decision_brief.get("claim_boundary") or "")
        )
    )
    judge_evidence_index_ok = bool(
        judge_evidence_index_result.get("ok")
        and judge_evidence_index
        and judge_evidence_index.get("schema") == "proofframe.judge_evidence_index.v1"
        and judge_evidence_index.get("ok") is True
        and judge_evidence_index.get("safe_to_share") is True
        and judge_evidence_index.get("safe_to_submit") is False
        and judge_evidence_index.get("mode") == "pre_live_evidence_index_ready"
        and len(judge_evidence_index_links) >= 10
        and len(judge_evidence_index_sections) >= 5
        and {
            "public_demo",
            "judge_brief",
            "judge_crosswalk",
            "judge_decision_brief",
            "final_submission_control",
            "final_closeout_status",
        }
        <= judge_evidence_index_link_ids
        and (
            "genblaze_live_proof" in judge_evidence_index_blockers
            or "public_video" in judge_evidence_index_blockers
        )
        and (
            "does not claim completed B2 or Genblaze live proof" in str(judge_evidence_index.get("claim_boundary") or "")
            or "may cite completed B2 and Genblaze proof" in str(judge_evidence_index.get("claim_boundary") or "")
        )
    )
    final_closeout_status_gates = dict_list_field(final_closeout_status, "gates")
    final_closeout_status_gate_ids = {
        str(gate.get("id")) for gate in final_closeout_status_gates if isinstance(gate.get("id"), str)
    }
    final_closeout_status_ok = bool(
        final_closeout_status_result.get("ok") and final_closeout_status_is_public_safe(final_closeout_status)
    )
    final_closeout_endpoint_gates = dict_list_field(final_closeout_endpoint, "gates")
    final_closeout_endpoint_ok = bool(
        final_closeout_endpoint_result.get("ok")
        and final_closeout_status_is_public_safe(final_closeout_endpoint)
        and final_closeout_endpoint.get("schema") == (final_closeout_status or {}).get("schema")
        and final_closeout_endpoint.get("mode") == (final_closeout_status or {}).get("mode")
        and final_closeout_endpoint.get("safe_to_submit") == (final_closeout_status or {}).get("safe_to_submit")
        and {str(gate.get("id")) for gate in final_closeout_endpoint_gates if isinstance(gate.get("id"), str)}
        == final_closeout_status_gate_ids
    )
    video_publish_upload_checks = dict_list_field(video_publish_kit, "upload_checklist")
    video_publish_upload_check_ids = {
        str(item.get("id")) for item in video_publish_upload_checks if isinstance(item.get("id"), str)
    }
    video_publish_sources = dict_field(video_publish_kit, "source_reports")
    video_publish_required_sources_ok = all(
        dict_field(video_publish_sources, source_id).get("schema_ok") is True
        for source_id in {
            "storyboard",
            "draft_video",
            "public_video_check",
            "final_control",
            "evidence_index",
        }
    )
    video_publish_public_video_source = dict_field(video_publish_sources, "public_video_check")
    video_publish_final_control_source = dict_field(video_publish_sources, "final_control")
    video_publish_common_ok = bool(
        video_publish_kit_result.get("ok")
        and video_publish_kit
        and video_publish_kit.get("schema") == "proofframe.final_video_publish_kit.v1"
        and video_publish_kit.get("ok") is True
        and video_publish_kit.get("safe_to_share") is True
        and {"host_family", "public_visibility", "duration", "devpost_field"}
        <= video_publish_upload_check_ids
        and "YouTube" in list_field(video_publish_kit, "allowed_hosts")
        and video_publish_required_sources_ok
    )
    video_publish_prefinal_ok = bool(
        video_publish_common_ok
        and video_publish_kit.get("safe_to_submit") is False
        and video_publish_kit.get("final_video_ready") is False
        and video_publish_kit.get("mode") == "ready_for_final_upload"
        and dict_field(video_publish_kit, "devpost_field").get("ready") is False
        and "safe_to_submit=false" in str(video_publish_kit.get("claim_boundary") or "")
    )
    video_publish_final_ok = bool(
        video_publish_common_ok
        and video_publish_kit.get("safe_to_submit") is True
        and video_publish_kit.get("final_video_ready") is True
        and video_publish_kit.get("mode") == "public_video_ready"
        and dict_field(video_publish_kit, "devpost_field").get("ready") is True
        and video_publish_public_video_source.get("ok") is True
        and video_publish_public_video_source.get("safe_to_submit") is True
        and video_publish_final_control_source.get("schema_ok") is True
        and video_publish_final_control_source.get("ok") is True
        and video_publish_final_control_source.get("safe_to_submit") is True
    )
    video_publish_kit_ok = bool(video_publish_prefinal_ok or video_publish_final_ok)

    checks = [
        check_item(
            "space_metadata",
            "Space metadata points at the expected commit",
            bool(
                space_result.get("ok")
                and space
                and space.get("private") is False
                and space.get("disabled") is False
                and space.get("sdk") == "docker"
                and space_sha == resolved_expected_sha
            ),
            f"Space sha is {space_sha}; expected {resolved_expected_sha}.",
            api_url,
        ),
        check_item(
            "runtime_ready",
            "Space runtime is running the expected commit",
            bool(
                runtime_result.get("ok")
                and runtime_sha == resolved_expected_sha
                and runtime_stage == "RUNNING"
                and domain_ready
            ),
            f"Runtime stage is {runtime_stage}; runtime sha is {runtime_sha}; domain ready is {domain_ready}.",
            runtime_url,
        ),
        check_item(
            "raw_handoff_report",
            "Raw handoff report is public and ready",
            bool(
                handoff_result.get("ok")
                and handoff
                and handoff.get("schema") == "proofframe.agent_handoff.v1"
                and handoff.get("ok") is True
                and handoff.get("mode") == "handoff_ready"
            ),
            f"Handoff schema is {handoff.get('schema') if handoff else None}; mode is {handoff.get('mode') if handoff else None}.",
            handoff_url,
        ),
        check_item(
            "raw_event_snapshot",
            "Raw Devpost event snapshot is public and fresh",
            bool(
                event_snapshot_result.get("ok")
                and event_snapshot
                and event_snapshot.get("schema") == "proofframe.devpost_event_snapshot.v1"
                and event_snapshot.get("mode") == "live_official_snapshot"
                and event_snapshot_validation.get("ok") is True
                and event_snapshot_validation.get("submission_open") is True
                and event_snapshot_sources_ok
                and event_snapshot_requirements_ok
                and event_snapshot_criteria_ok
                and isinstance(event_snapshot_event.get("participant_count_observed"), int)
                and event_snapshot_event.get("participant_count_observed", 0) > 0
                and event_snapshot_event.get("deadline_utc") == "2026-08-03T21:00:00Z"
                and event_snapshot_age_days is not None
                and event_snapshot_age_days <= EVENT_SNAPSHOT_MAX_AGE_DAYS
            ),
            (
                f"Event snapshot schema is {event_snapshot.get('schema') if event_snapshot else None}; "
                f"submission_open={event_snapshot_validation.get('submission_open') if event_snapshot else None}; "
                f"age_days={event_snapshot_age_days}; "
                f"participants={event_snapshot_event.get('participant_count_observed') if event_snapshot else None}."
            ),
            event_snapshot_url,
        ),
        check_item(
            "raw_launch_plan",
            "Raw final launch plan is public and phase-aware",
            bool(
                launch_plan_result.get("ok")
                and launch_plan
                and launch_plan.get("schema") == "proofframe.final_launch_plan.v1"
                and (launch_plan.get("mode"), launch_plan.get("current_phase"))
                in PUBLIC_SAFE_LAUNCH_STATES
            ),
            (
                f"Launch plan schema is {launch_plan.get('schema') if launch_plan else None}; "
                f"mode is {launch_plan.get('mode') if launch_plan else None}; "
                f"current phase is {launch_plan.get('current_phase') if launch_plan else None}."
            ),
            launch_plan_url,
        ),
        check_item(
            "raw_b2_key_scope_checklist",
            "Raw B2 key scope checklist is public and no-secret",
            b2_key_scope_ok,
            (
                f"Checklist schema is {b2_key_scope_checklist.get('schema') if b2_key_scope_checklist else None}; "
                f"safe_to_commit={b2_key_scope_checklist.get('safe_to_commit') if b2_key_scope_checklist else None}; "
                f"bucket={b2_key_scope_bucket.get('bucket_name') if b2_key_scope_checklist else None}; "
                f"prefix={b2_key_scope_prefix.get('value') if b2_key_scope_checklist else None}; "
                f"confirmation={b2_key_scope_confirmation.get('status') if b2_key_scope_checklist else None}; "
                f"required={sorted(b2_key_scope_required_capabilities)}."
            ),
            b2_key_scope_checklist_url,
        ),
        check_item(
            "raw_judge_brief",
            "Raw judge brief is public and claim-safe",
            bool(
                judge_brief_result.get("ok")
                and judge_brief
                and judge_brief.get("schema") == "proofframe.judge_brief.v1"
                and judge_brief.get("status", {}).get("safe_to_submit") is False
            ),
            (
                f"Judge brief schema is {judge_brief.get('schema') if judge_brief else None}; "
                f"safe_to_submit is {judge_brief.get('status', {}).get('safe_to_submit') if judge_brief else None}."
            ),
            judge_brief_url,
        ),
        check_item(
            "raw_judge_crosswalk",
            "Raw judge crosswalk is public and claim-safe",
            bool(
                judge_crosswalk_result.get("ok")
                and judge_crosswalk
                and judge_crosswalk.get("schema") == "proofframe.judge_crosswalk.v1"
                and judge_crosswalk.get("ok") is True
                and judge_crosswalk.get("safe_to_submit") is False
                and judge_crosswalk.get("mode") in {"pre_live_crosswalk_ready", "final_crosswalk_ready"}
            ),
            (
                f"Judge crosswalk schema is {judge_crosswalk.get('schema') if judge_crosswalk else None}; "
                f"mode is {judge_crosswalk.get('mode') if judge_crosswalk else None}; "
                f"safe_to_submit is {judge_crosswalk.get('safe_to_submit') if judge_crosswalk else None}."
            ),
            judge_crosswalk_url,
        ),
        check_item(
            "raw_judge_decision_brief",
            "Raw judge decision brief is public and claim-safe",
            judge_decision_brief_ok,
            (
                f"Decision brief schema is {judge_decision_brief.get('schema') if judge_decision_brief else None}; "
                f"mode is {judge_decision_brief.get('mode') if judge_decision_brief else None}; "
                f"safe_to_submit is {judge_decision_brief.get('safe_to_submit') if judge_decision_brief else None}; "
                f"checks={len(judge_decision_checks)}; "
                f"space_mode={judge_decision_public_state.get('space_mode')}; "
                f"space_sync_checked_at={judge_decision_public_state.get('space_sync_checked_at')}; "
                f"age_days={judge_decision_age_days}; "
                f"fresh={judge_decision_fresh_ok}."
            ),
            judge_decision_brief_url,
        ),
        check_item(
            "raw_judge_evidence_index",
            "Raw judge evidence index is public and claim-safe",
            judge_evidence_index_ok,
            (
                f"Evidence index schema is {judge_evidence_index.get('schema') if judge_evidence_index else None}; "
                f"mode is {judge_evidence_index.get('mode') if judge_evidence_index else None}; "
                f"safe_to_submit is {judge_evidence_index.get('safe_to_submit') if judge_evidence_index else None}; "
                f"links={len(judge_evidence_index_links)}; blockers={len(judge_evidence_index_blockers)}."
            ),
            judge_evidence_index_url,
        ),
        check_item(
            "raw_final_closeout_status",
            "Raw final closeout status is public and closeout-safe",
            final_closeout_status_ok,
            (
                f"Closeout schema is {final_closeout_status.get('schema') if final_closeout_status else None}; "
                f"mode is {final_closeout_status.get('mode') if final_closeout_status else None}; "
                f"safe_to_submit is {final_closeout_status.get('safe_to_submit') if final_closeout_status else None}; "
                f"gates={len(final_closeout_status_gates)}."
            ),
            final_closeout_status_url,
        ),
        check_item(
            "api_final_closeout_status",
            "Final closeout API matches the raw public status",
            final_closeout_endpoint_ok,
            (
                f"API closeout schema is {final_closeout_endpoint.get('schema') if final_closeout_endpoint else None}; "
                f"mode is {final_closeout_endpoint.get('mode') if final_closeout_endpoint else None}; "
                f"safe_to_submit is {final_closeout_endpoint.get('safe_to_submit') if final_closeout_endpoint else None}; "
                f"gates={len(final_closeout_endpoint_gates)}."
            ),
            final_closeout_endpoint_url,
        ),
        check_item(
            "raw_video_publish_kit",
            "Raw final video publish kit is public and final-video gated",
            video_publish_kit_ok,
            (
                f"Video kit schema is {video_publish_kit.get('schema') if video_publish_kit else None}; "
                f"mode is {video_publish_kit.get('mode') if video_publish_kit else None}; "
                f"safe_to_submit is {video_publish_kit.get('safe_to_submit') if video_publish_kit else None}; "
                f"checks={len(video_publish_upload_checks)}."
            ),
            video_publish_kit_url,
        ),
        check_item(
            "raw_recording_assets",
            "Raw recording runbook is public and final-video gated",
            bool(
                recording_assets_result.get("ok")
                and recording_assets
                and recording_assets.get("schema") == "proofframe.recording_assets.v1"
                and recording_assets.get("mock_recording_ready") is True
                and recording_assets.get("final_video_ready") is False
                and isinstance(recording_assets.get("shot_plan"), list)
                and len(recording_assets.get("shot_plan", [])) >= 3
            ),
            (
                f"Recording schema is {recording_assets.get('schema') if recording_assets else None}; "
                f"mode is {recording_assets.get('mode') if recording_assets else None}; "
                f"final_video_ready is {recording_assets.get('final_video_ready') if recording_assets else None}."
            ),
            recording_assets_url,
        ),
        check_item(
            "raw_public_demo_screenshot",
            "Raw public judge screenshot report is public and verified",
            public_demo_screenshot_ok,
            (
                f"Screenshot schema is {public_demo_screenshot.get('schema') if public_demo_screenshot else None}; "
                f"mode is {public_demo_screenshot.get('mode') if public_demo_screenshot else None}; "
                f"visible_ok={public_demo_screenshot_markers.get('visible_ok') if public_demo_screenshot else None}; "
                f"html_ok={public_demo_screenshot_markers.get('html_ok') if public_demo_screenshot else None}; "
                f"bytes={public_demo_screenshot_image.get('bytes') if public_demo_screenshot else None}."
            ),
            public_demo_screenshot_url,
        ),
        check_item(
            "raw_demo_video_draft",
            "Raw mock demo video draft report is public and fail-closed",
            bool(
                demo_video_draft_result.get("ok")
                and demo_video_draft
                and demo_video_draft.get("schema") == "proofframe.demo_video_draft.v1"
                and demo_video_draft.get("ok") is True
                and demo_video_draft.get("safe_to_submit") is False
                and demo_video_draft.get("final_video_ready") is False
                and demo_video_draft.get("video_path") == "docs/assets/proofframe-demo-draft.mp4"
                and (demo_video_draft.get("video_probe", {}).get("bytes") or 0) >= DRAFT_VIDEO_MIN_BYTES
            ),
            (
                f"Draft schema is {demo_video_draft.get('schema') if demo_video_draft else None}; "
                f"mode is {demo_video_draft.get('mode') if demo_video_draft else None}; "
                f"safe_to_submit is {demo_video_draft.get('safe_to_submit') if demo_video_draft else None}."
            ),
            demo_video_draft_url,
        ),
        check_item(
            "public_demo_video_draft_mp4",
            "Mock demo video draft MP4 is publicly readable",
            bool(
                demo_video_draft_mp4_result.get("ok")
                and demo_video_draft_mp4_result.get("status") in {200, 206}
                and (demo_video_draft_mp4_result.get("bytes") or 0) >= DRAFT_VIDEO_MIN_BYTES
                and "video" in str(demo_video_draft_mp4_result.get("content_type") or "").lower()
            ),
            (
                f"status={demo_video_draft_mp4_result.get('status')}; "
                f"bytes={demo_video_draft_mp4_result.get('bytes')}; "
                f"content_type={demo_video_draft_mp4_result.get('content_type')}."
            ),
            demo_video_draft_mp4_url,
        ),
        check_item(
            "raw_public_video_check",
            "Raw public video check is public and official-host gated",
            public_video_check_ok,
            (
                f"Video check schema is {public_video_check.get('schema') if public_video_check else None}; "
                f"mode is {public_video_check.get('mode') if public_video_check else None}; "
                f"safe_to_submit={public_video_check.get('safe_to_submit') if public_video_check else None}; "
                f"official_host_check={public_video_official_host_check.get('ok') if public_video_check else None}."
            ),
            public_video_check_url,
        ),
        check_item(
            "raw_devpost_form_kit",
            "Raw Devpost form kit is public and final-form gated",
            bool(
                devpost_form_kit_result.get("ok")
                and devpost_form_kit
                and devpost_form_kit.get("schema") == "proofframe.devpost_form_kit.v1"
                and devpost_form_kit.get("mock_form_ready") is True
                and devpost_form_kit.get("final_form_ready") is False
                and isinstance(devpost_form_kit.get("fields"), list)
                and len(devpost_form_kit.get("fields", [])) >= 10
            ),
            (
                f"Devpost form schema is {devpost_form_kit.get('schema') if devpost_form_kit else None}; "
                f"mode is {devpost_form_kit.get('mode') if devpost_form_kit else None}; "
                f"final_form_ready is {devpost_form_kit.get('final_form_ready') if devpost_form_kit else None}."
            ),
            devpost_form_kit_url,
        ),
        check_item(
            "raw_devpost_preview",
            "Raw Devpost submission preview is public and claim-safe",
            devpost_preview_ok,
            (
                f"Preview schema is {devpost_preview.get('schema') if devpost_preview else None}; "
                f"mode is {devpost_preview.get('mode') if devpost_preview else None}; "
                f"safe_to_share={devpost_preview.get('safe_to_share') if devpost_preview else None}; "
                f"safe_to_submit={devpost_preview.get('safe_to_submit') if devpost_preview else None}; "
                f"blockers={len(devpost_preview_blockers)}."
            ),
            devpost_preview_url,
        ),
        check_item(
            "raw_submit_checklist",
            "Raw Devpost submit checklist is public and fail-closed",
            bool(
                submit_checklist_result.get("ok")
                and submit_checklist
                and submit_checklist.get("schema") == "proofframe.devpost_submission_checklist.v1"
                and submit_checklist.get("safe_to_submit") is False
                and submit_checklist.get("mode") == "pre_submit_blocked"
                and isinstance(submit_checklist.get("preflight"), list)
                and len(submit_checklist.get("preflight", [])) >= 3
            ),
            (
                f"Submit checklist schema is {submit_checklist.get('schema') if submit_checklist else None}; "
                f"mode is {submit_checklist.get('mode') if submit_checklist else None}; "
                f"safe_to_submit is {submit_checklist.get('safe_to_submit') if submit_checklist else None}."
            ),
            submit_checklist_url,
        ),
        check_item(
            "raw_post_credential_plan",
            "Raw post-credential live proof plan is public and task-safe",
            bool(
                post_credential_plan_result.get("ok")
                and post_credential_plan
                and post_credential_plan.get("schema") == "proofframe.post_credential_live_proof.v1"
                and post_credential_plan.get("ok") is True
                and post_credential_plan.get("mode") == "plan_only"
                and post_credential_plan.get("execute") is False
                and post_credential_plan.get("update_tasks") is False
                and post_credential_sequence_ok
                and post_credential_report_sequence_ok
                and post_credential_no_task_update
                and post_credential_secret_policy_ok
            ),
            (
                f"Post-credential schema is {post_credential_plan.get('schema') if post_credential_plan else None}; "
                f"mode is {post_credential_plan.get('mode') if post_credential_plan else None}; "
                f"required sequence={post_credential_sequence_ok}; "
                f"report sequence={post_credential_report_sequence_ok}; "
                f"secret policy safe={post_credential_secret_policy_ok}; "
                f"devpost preview included={'devpost_submission_preview' in post_credential_command_ids}."
            ),
            post_credential_plan_url,
        ),
        check_item(
            "raw_submission_bundle",
            "Raw submission bundle separates shareability from final submit readiness",
            bool(
                submission_bundle_result.get("ok")
                and submission_bundle
                and submission_bundle.get("schema") == "proofframe.submission_bundle.v1"
                and submission_bundle.get("safe_to_share") is True
                and submission_bundle.get("safe_to_submit") is False
                and submission_bundle_missing_artifacts == []
                and submission_bundle_artifacts_valid
                and submission_bundle_required_artifacts_ok
                and submission_bundle_devpost_packet.get("present") is True
                and submission_bundle_devpost_packet.get("mode") in {"pre_live_safe", "post_live_verified"}
                and (
                    "Do not submit" in str(submission_bundle_devpost_packet.get("claim_warning") or "")
                    or "Use only after T020 and T021" in str(submission_bundle_devpost_packet.get("claim_warning") or "")
                )
                and submission_bundle_gate.get("ok") is False
                and submission_bundle_gate.get("mode") == "pre_live_safe"
                and submission_bundle_packet_gate.get("status") in {"pre_live_packet_pending", "post_live_packet_ready"}
                and submission_bundle_evidence_gate.get("status") in {"missing", "verified"}
                and submission_bundle_report_gate.get("status") == "incomplete"
                and submission_bundle_secret_scan.get("ok") is True
                and submission_bundle_secret_scan.get("status") == "verified"
                and submission_bundle_submission_audit.get("ok") is False
                and submission_bundle_submission_audit.get("status") == "incomplete"
                and submission_bundle_b2_action_ok
                and (
                    any("Genblaze" in str(action) for action in submission_bundle_next_actions)
                    or submission_bundle_evidence_gate.get("status") == "verified"
                )
            ),
            (
                f"Bundle schema is {submission_bundle.get('schema') if submission_bundle else None}; "
                f"safe_to_share={submission_bundle.get('safe_to_share') if submission_bundle else None}; "
                f"safe_to_submit={submission_bundle.get('safe_to_submit') if submission_bundle else None}; "
                f"required artifacts={submission_bundle_required_artifacts_ok}; "
                f"b2 action ok={submission_bundle_b2_action_ok}."
            ),
            submission_bundle_url,
        ),
        check_item(
            "raw_genblaze_contract_report",
            "Raw Genblaze SDK contract report is public and ready",
            genblaze_contract_ok,
            (
                f"Contract schema is {genblaze_contract.get('schema') if genblaze_contract else None}; "
                f"mode is {genblaze_contract.get('mode') if genblaze_contract else None}; "
                f"failed_checks={len(genblaze_contract_failed_checks)}."
            ),
            genblaze_contract_url,
        ),
        check_item(
            "raw_docker_smoke_report",
            "Raw Docker smoke report is public and ready",
            docker_smoke_ok,
            (
                f"Docker smoke schema is {docker_smoke.get('schema') if docker_smoke else None}; "
                f"mode is {docker_smoke.get('mode') if docker_smoke else None}; "
                f"health storage={docker_smoke_health_json.get('storage_backend')}."
            ),
            docker_smoke_url,
        ),
        check_item(
            "public_health",
            "Public demo health is local/mock and ready",
            bool(
                health_result.get("ok")
                and health
                and health.get("ready") is True
                and health.get("storage_backend") == "local"
                and health.get("generation_backend") == "mock"
                and health.get("b2_configured") is False
                and health.get("genblaze_configured") is False
            ),
            (
                f"Health storage={health.get('storage_backend') if health else None}, "
                f"generation={health.get('generation_backend') if health else None}, "
                f"ready={health.get('ready') if health else None}."
            ),
            health_url,
        ),
        check_item(
            "submission_gate",
            "Public submission gate is fail-closed with repo-relative paths",
            bool(
                gate_result.get("ok")
                and gate
                and gate.get("mode") in {"pre_live_safe", "final_ready"}
                and isinstance(gate.get("report_gate"), dict)
                and report_gate_status in {"incomplete", "verified"}
                and gate_paths_relative
            ),
            f"Gate mode is {gate.get('mode') if gate else None}; report gate is {report_gate_status}; relative paths={gate_paths_relative}.",
            gate_url,
        ),
        check_item(
            "judge_html_markers",
            "Judge-mode HTML contains recording and sponsor markers",
            bool(judge_result.get("ok") and all(html_markers.values())),
            f"Markers: {', '.join(f'{key}={value}' for key, value in html_markers.items())}.",
            judge_url,
        ),
    ]

    return {
        "schema": SCHEMA,
        "created_at": utc_now(),
        "ok": all(item["ok"] for item in checks),
        "mode": "public_space_synced" if all(item["ok"] for item in checks) else "public_space_mismatch",
        "space_id": space_id,
        "public_host": public_host,
        "expected_sha": resolved_expected_sha,
        "observed": {
            "space_sha": space_sha,
            "runtime_sha": runtime_sha,
            "runtime_stage": runtime_stage,
            "domain_ready": domain_ready,
            "last_modified": space.get("lastModified") if space else None,
            "health": {
                "ready": health.get("ready") if health else None,
                "storage_backend": health.get("storage_backend") if health else None,
                "generation_backend": health.get("generation_backend") if health else None,
            },
            "submission_gate": {
                "mode": gate.get("mode") if gate else None,
                "summary": gate.get("summary") if gate else None,
                "report_gate_status": report_gate_status,
                "paths_relative": gate_paths_relative,
            },
            "handoff_mode": handoff.get("mode") if handoff else None,
            "event_snapshot": {
                "checked_at": event_snapshot.get("checked_at") if event_snapshot else None,
                "age_days": event_snapshot_age_days,
                "participant_count_observed": (
                    event_snapshot_event.get("participant_count_observed") if event_snapshot else None
                ),
                "submission_open": event_snapshot_validation.get("submission_open") if event_snapshot else None,
                "requirements_ok": event_snapshot_requirements_ok,
                "criteria_ok": event_snapshot_criteria_ok,
            },
            "launch_plan_mode": launch_plan.get("mode") if launch_plan else None,
            "launch_plan_phase": launch_plan.get("current_phase") if launch_plan else None,
            "genblaze_contract": {
                "schema": genblaze_contract.get("schema") if genblaze_contract else None,
                "mode": genblaze_contract.get("mode") if genblaze_contract else None,
                "ok": genblaze_contract.get("ok") if genblaze_contract else None,
                "failed_checks": len(genblaze_contract_failed_checks),
            },
            "docker_smoke": {
                "schema": docker_smoke.get("schema") if docker_smoke else None,
                "mode": docker_smoke.get("mode") if docker_smoke else None,
                "ok": docker_smoke.get("ok") if docker_smoke else None,
                "storage_backend": docker_smoke_health_json.get("storage_backend"),
                "generation_backend": docker_smoke_health_json.get("generation_backend"),
            },
            "b2_key_scope_checklist": {
                "schema": b2_key_scope_checklist.get("schema") if b2_key_scope_checklist else None,
                "ok": b2_key_scope_checklist.get("ok") if b2_key_scope_checklist else None,
                "safe_to_commit": (
                    b2_key_scope_checklist.get("safe_to_commit") if b2_key_scope_checklist else None
                ),
                "requires_user_confirmation_before_key_creation": (
                    b2_key_scope_checklist.get("requires_user_confirmation_before_key_creation")
                    if b2_key_scope_checklist
                    else None
                ),
                "confirmation_status": b2_key_scope_confirmation.get("status"),
                "confirmation_phrase_safe": bool(
                    b2_key_scope_confirmation.get("safe_to_store")
                    and "no secrets in chat/docs/git" in b2_key_scope_confirmation_phrase
                ),
                "bucket_name": b2_key_scope_bucket.get("bucket_name"),
                "prefix": b2_key_scope_prefix.get("value"),
                "required_capabilities": sorted(b2_key_scope_required_capabilities),
                "forbidden_setup_fields": b2_key_scope_secret_policy.get("forbidden_setup_fields"),
            },
            "judge_brief_schema": judge_brief.get("schema") if judge_brief else None,
            "judge_brief_safe_to_submit": (
                judge_brief.get("status", {}).get("safe_to_submit") if judge_brief else None
            ),
            "judge_crosswalk_schema": judge_crosswalk.get("schema") if judge_crosswalk else None,
            "judge_crosswalk_mode": judge_crosswalk.get("mode") if judge_crosswalk else None,
            "judge_crosswalk_safe_to_submit": (
                judge_crosswalk.get("safe_to_submit") if judge_crosswalk else None
            ),
            "judge_decision_brief": {
                "schema": judge_decision_brief.get("schema") if judge_decision_brief else None,
                "created_at": judge_decision_created_at,
                "age_days": judge_decision_age_days,
                "mode": judge_decision_brief.get("mode") if judge_decision_brief else None,
                "safe_to_share": (
                    judge_decision_brief.get("safe_to_share") if judge_decision_brief else None
                ),
                "safe_to_submit": (
                    judge_decision_brief.get("safe_to_submit") if judge_decision_brief else None
                ),
                "check_count": len(judge_decision_checks),
                "space_mode": judge_decision_public_state.get("space_mode"),
                "space_sync_checked_at": judge_decision_public_state.get("space_sync_checked_at"),
                "evidence_index_link": judge_decision_links.get("evidence_index"),
                "source_state_ok": judge_decision_source_state_ok,
                "fresh": judge_decision_fresh_ok,
            },
            "judge_evidence_index": {
                "schema": judge_evidence_index.get("schema") if judge_evidence_index else None,
                "mode": judge_evidence_index.get("mode") if judge_evidence_index else None,
                "safe_to_share": (
                    judge_evidence_index.get("safe_to_share") if judge_evidence_index else None
                ),
                "safe_to_submit": (
                    judge_evidence_index.get("safe_to_submit") if judge_evidence_index else None
                ),
                "link_count": len(judge_evidence_index_links),
                "section_count": len(judge_evidence_index_sections),
                "blocker_count": len(judge_evidence_index_blockers),
            },
            "final_closeout_status": {
                "schema": final_closeout_status.get("schema") if final_closeout_status else None,
                "mode": final_closeout_status.get("mode") if final_closeout_status else None,
                "closeout_health_ok": (
                    final_closeout_status.get("closeout_health_ok") if final_closeout_status else None
                ),
                "safe_to_submit": final_closeout_status.get("safe_to_submit") if final_closeout_status else None,
                "gate_count": len(final_closeout_status_gates),
            },
            "final_closeout_api": {
                "schema": final_closeout_endpoint.get("schema") if final_closeout_endpoint else None,
                "mode": final_closeout_endpoint.get("mode") if final_closeout_endpoint else None,
                "safe_to_submit": (
                    final_closeout_endpoint.get("safe_to_submit") if final_closeout_endpoint else None
                ),
                "gate_count": len(final_closeout_endpoint_gates),
            },
            "video_publish_kit": {
                "schema": video_publish_kit.get("schema") if video_publish_kit else None,
                "mode": video_publish_kit.get("mode") if video_publish_kit else None,
                "safe_to_share": video_publish_kit.get("safe_to_share") if video_publish_kit else None,
                "safe_to_submit": video_publish_kit.get("safe_to_submit") if video_publish_kit else None,
                "final_video_ready": (
                    video_publish_kit.get("final_video_ready") if video_publish_kit else None
                ),
                "upload_check_count": len(video_publish_upload_checks),
            },
            "public_demo_screenshot": {
                "mode": public_demo_screenshot.get("mode") if public_demo_screenshot else None,
                "ok": public_demo_screenshot.get("ok") if public_demo_screenshot else None,
                "visible_ok": public_demo_screenshot_markers.get("visible_ok"),
                "html_ok": public_demo_screenshot_markers.get("html_ok"),
                "bytes": public_demo_screenshot_image.get("bytes"),
                "size": [
                    public_demo_screenshot_image.get("width"),
                    public_demo_screenshot_image.get("height"),
                ],
            },
            "devpost_preview": {
                "mode": devpost_preview.get("mode") if devpost_preview else None,
                "safe_to_share": devpost_preview.get("safe_to_share") if devpost_preview else None,
                "safe_to_submit": devpost_preview.get("safe_to_submit") if devpost_preview else None,
                "field_final_ready": devpost_preview_field_rollup.get("final_ready"),
                "blocker_count": len(devpost_preview_blockers),
            },
            "demo_video_draft_mode": demo_video_draft.get("mode") if demo_video_draft else None,
            "demo_video_draft_safe_to_submit": (
                demo_video_draft.get("safe_to_submit") if demo_video_draft else None
            ),
            "public_video_check": {
                "mode": public_video_check.get("mode") if public_video_check else None,
                "safe_to_submit": public_video_check.get("safe_to_submit") if public_video_check else None,
                "official_host_check_ok": public_video_official_host_check.get("ok"),
            },
            "post_credential_plan_mode": post_credential_plan.get("mode") if post_credential_plan else None,
            "post_credential_plan_validators": {
                "validate_b2_evidence": "validate_b2_evidence" in post_credential_command_ids,
                "validate_final_evidence": "validate_final_evidence" in post_credential_command_ids,
                "devpost_submission_preview": "devpost_submission_preview" in post_credential_command_ids,
            },
            "post_credential_plan_required_sequence": post_credential_sequence_ok,
            "post_credential_plan_report_sequence": post_credential_report_sequence_ok,
            "post_credential_plan_secret_policy_safe": post_credential_secret_policy_ok,
            "submission_bundle": {
                "safe_to_share": submission_bundle.get("safe_to_share") if submission_bundle else None,
                "safe_to_submit": submission_bundle.get("safe_to_submit") if submission_bundle else None,
                "gate_mode": (
                    submission_bundle_gate.get("mode") if submission_bundle else None
                ),
                "required_artifacts_present": submission_bundle_required_artifacts_ok,
                "missing_artifacts": len(submission_bundle_missing_artifacts),
                "artifact_count": len(submission_bundle_artifacts),
            },
            "demo_video_draft_mp4": {
                "status": demo_video_draft_mp4_result.get("status"),
                "bytes": demo_video_draft_mp4_result.get("bytes"),
                "content_type": demo_video_draft_mp4_result.get("content_type"),
            },
            "html_markers": html_markers,
        },
        "urls": {
            "space_api": api_url,
            "runtime_api": runtime_url,
            "raw_handoff_report": handoff_url,
            "raw_event_snapshot": event_snapshot_url,
            "raw_launch_plan": launch_plan_url,
            "raw_b2_key_scope_checklist": b2_key_scope_checklist_url,
            "raw_judge_brief": judge_brief_url,
            "raw_judge_crosswalk": judge_crosswalk_url,
            "raw_judge_decision_brief": judge_decision_brief_url,
            "raw_judge_evidence_index": judge_evidence_index_url,
            "raw_final_closeout_status": final_closeout_status_url,
            "raw_video_publish_kit": video_publish_kit_url,
            "raw_public_demo_screenshot": public_demo_screenshot_url,
            "raw_demo_video_draft": demo_video_draft_url,
            "demo_video_draft_mp4": demo_video_draft_mp4_url,
            "raw_public_video_check": public_video_check_url,
            "raw_devpost_form_kit": devpost_form_kit_url,
            "raw_devpost_preview": devpost_preview_url,
            "raw_submit_checklist": submit_checklist_url,
            "raw_post_credential_plan": post_credential_plan_url,
            "raw_submission_bundle": submission_bundle_url,
            "raw_genblaze_contract_report": genblaze_contract_url,
            "raw_docker_smoke_report": docker_smoke_url,
            "judge": judge_url,
            "health": health_url,
            "submission_gate": gate_url,
        },
        "checks": checks,
        "next_actions": next_actions(checks),
    }


def next_actions(checks: list[dict[str, Any]]) -> list[str]:
    failed = {item["id"] for item in checks if not item["ok"]}
    actions: list[str] = []
    if "space_metadata" in failed or "runtime_ready" in failed:
        actions.append("Upload the current public demo bundle to the Hugging Face Space and wait for RUNNING.")
    if "raw_handoff_report" in failed:
        actions.append("Regenerate and upload docs/assets/agent-handoff-report.json to the Space.")
    if "raw_event_snapshot" in failed:
        actions.append("Regenerate and upload docs/assets/devpost-event-snapshot.json to the Space.")
    if "raw_launch_plan" in failed:
        actions.append("Regenerate and upload docs/assets/final-launch-plan.json to the Space.")
    if "raw_b2_key_scope_checklist" in failed:
        actions.append("Regenerate and upload docs/assets/b2-key-scope-checklist.json to the Space.")
    if "raw_judge_brief" in failed:
        actions.append("Regenerate and upload docs/assets/judge-brief.json to the Space.")
    if "raw_judge_crosswalk" in failed:
        actions.append("Regenerate and upload docs/assets/judge-crosswalk.json to the Space.")
    if "raw_judge_decision_brief" in failed:
        actions.append("Regenerate and upload docs/assets/judge-decision-brief.json to the Space.")
    if "raw_judge_evidence_index" in failed:
        actions.append("Regenerate and upload docs/assets/judge-evidence-index.json to the Space.")
    if "raw_final_closeout_status" in failed:
        actions.append("Regenerate and upload docs/assets/final-closeout-status.json to the Space.")
    if "api_final_closeout_status" in failed:
        actions.append("Redeploy the Space so /api/judge/final-closeout matches the raw closeout status.")
    if "raw_video_publish_kit" in failed:
        actions.append("Regenerate and upload docs/assets/final-video-publish-kit.json to the Space.")
    if "raw_recording_assets" in failed:
        actions.append("Regenerate and upload docs/assets/recording-assets.json to the Space.")
    if "raw_public_demo_screenshot" in failed:
        actions.append("Regenerate and upload docs/assets/public-demo-screenshot-report.json to the Space.")
    if "raw_demo_video_draft" in failed:
        actions.append("Regenerate and upload docs/assets/demo-video-draft.json to the Space.")
    if "public_demo_video_draft_mp4" in failed:
        actions.append("Regenerate and upload docs/assets/proofframe-demo-draft.mp4 to the Space.")
    if "raw_public_video_check" in failed:
        actions.append("Regenerate and upload docs/assets/public-video-check.json to the Space.")
    if "raw_devpost_form_kit" in failed:
        actions.append("Regenerate and upload docs/assets/devpost-form-kit.json to the Space.")
    if "raw_devpost_preview" in failed:
        actions.append("Regenerate and upload docs/assets/devpost-submission-preview.json to the Space.")
    if "raw_submit_checklist" in failed:
        actions.append("Regenerate and upload docs/assets/devpost-submission-checklist.json to the Space.")
    if "raw_post_credential_plan" in failed:
        actions.append("Regenerate and upload docs/assets/post-credential-live-proof-plan.json to the Space.")
    if "raw_submission_bundle" in failed:
        actions.append("Regenerate and upload docs/assets/submission-bundle-manifest.json to the Space.")
    if "raw_genblaze_contract_report" in failed:
        actions.append("Regenerate and upload docs/assets/genblaze-contract-report.json to the Space.")
    if "raw_docker_smoke_report" in failed:
        actions.append("Regenerate and upload docs/assets/docker-smoke-report.json to the Space.")
    if "public_health" in failed or "submission_gate" in failed or "judge_html_markers" in failed:
        actions.append("Rebuild the public Space and rerun public API/HTML smoke checks.")
    if not actions:
        actions.append("Public Space sync evidence is ready for the pre-live Devpost demo.")
    return actions


def render_markdown(report: dict[str, Any]) -> str:
    lines = [
        "# ProofFrame Public Space Sync Report",
        "",
        f"Mode: `{report['mode']}`",
        f"OK: `{str(report['ok']).lower()}`",
        f"Created: `{report['created_at']}`",
        f"Space: `{report['space_id']}`",
        f"Public host: {report['public_host']}",
        f"Expected sha: `{report['expected_sha']}`",
        f"Runtime sha: `{report['observed']['runtime_sha']}`",
        f"Runtime stage: `{report['observed']['runtime_stage']}`",
        "",
        "## Checks",
        "",
        "| Status | Check | Detail | Evidence |",
        "| --- | --- | --- | --- |",
    ]
    for item in report["checks"]:
        status = "OK" if item["ok"] else "FAIL"
        lines.append(f"| {status} | {item['label']} | {item['detail']} | {item['evidence']} |")
    lines.extend(["", "## Next Actions", ""])
    lines.extend(f"- {action}" for action in report["next_actions"])
    lines.append("")
    return "\n".join(lines)


def write_outputs(report: dict[str, Any], json_path: Path, markdown_path: Path) -> None:
    json_path.parent.mkdir(parents=True, exist_ok=True)
    markdown_path.parent.mkdir(parents=True, exist_ok=True)
    json_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    markdown_path.write_text(render_markdown(report), encoding="utf-8")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Verify the public ProofFrame Hugging Face Space sync.")
    parser.add_argument("--json-out", type=Path, default=DEFAULT_JSON)
    parser.add_argument("--markdown-out", type=Path, default=DEFAULT_MD)
    parser.add_argument("--space-id", default=SPACE_ID)
    parser.add_argument("--public-host", default=SPACE_HOST)
    parser.add_argument("--expected-sha", default=EXPECTED_SPACE_SHA)
    parser.add_argument("--wait-attempts", type=int, default=1)
    parser.add_argument("--wait-seconds", type=float, default=30.0)
    return parser


def main() -> None:
    args = build_parser().parse_args()
    attempts = max(1, args.wait_attempts)
    report: dict[str, Any] | None = None
    for attempt in range(attempts):
        report = build_report(
            space_id=args.space_id,
            public_host=args.public_host,
            expected_sha=args.expected_sha,
        )
        if report["ok"] or attempt == attempts - 1:
            break
        time.sleep(max(0.0, args.wait_seconds))
    assert report is not None
    write_outputs(report, args.json_out, args.markdown_out)
    print(
        json.dumps(
            {
                "ok": report["ok"],
                "mode": report["mode"],
                "json": str(args.json_out),
                "markdown": str(args.markdown_out),
                "runtime_sha": report["observed"]["runtime_sha"],
                "failed_checks": [item["id"] for item in report["checks"] if not item["ok"]],
            },
            indent=2,
        )
    )
    if not report["ok"]:
        raise SystemExit(1)


if __name__ == "__main__":
    main()