File size: 287,866 Bytes
d82db76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
#!/usr/bin/env python3
"""Audit a completed OCR eval output directory for review readiness."""

from __future__ import annotations

import argparse
import csv
import hashlib
import html
import importlib.util
import json
import random
import shlex
import sys
import unicodedata
from datetime import datetime
from pathlib import Path
from typing import Any

import regex
from rapidfuzz.distance import Levenshtein

from ocrtech.metrics import bbox_iou
from ocrtech.references import load_reference
from ocrtech.schemas import BBox, Document, TextLine


TOOLS_DIR = Path(__file__).resolve().parent
SUPPORTED_NORMALIZATION_PROFILE = "NFC_preserve_whitespace"
UNCERTAINTY_BOOTSTRAP_SAMPLES = 200
UNCERTAINTY_BOOTSTRAP_SEED = 1729
MIN_CLAIM_SCORING_UNITS = 30
RECOGNIZER_ARTIFACTS = (
    "eval-run.json",
    "metrics.json",
    "metrics.md",
    "predictions.tsv",
    "unmatched.tsv",
    "worst-lines.csv",
    "sample-review.csv",
    "sample-review.html",
    "confusions.json",
    "command.txt",
    "claim-safety.md",
)
PAGE_ARTIFACTS = (
    "page-eval-run.json",
    "metrics.json",
    "metrics.md",
    "page-metrics.csv",
    "reference-artifacts.tsv",
    "text-pairs.tsv",
    "missing.tsv",
    "worst-pages.csv",
    "confusions.json",
    "sample-review.csv",
    "sample-review.html",
    "line-alignment.csv",
    "command.txt",
    "claim-safety.md",
)
RECIPE_ROOT_ARTIFACTS = (
    "recipe-run.json",
    "recipe.json",
    "recipe-validation.json",
    "audit.json",
    "claim-safety.md",
    "materialize/output-command-run.json",
    "materialize/output-command-run.md",
    "materialize/command-template.txt",
)
RECOGNIZER_REQUIRED_RUN_FIELDS = (
    "created_at",
    "model_name",
    "checkpoint",
    "config",
    "dictionary",
    "artifact_identity",
    "label_file",
    "label_file_sha256",
    "prediction_file",
    "prediction_file_sha256",
    "data_dir",
    "script_inventory_file",
    "script_inventory_file_sha256",
    "eval_pack_version",
    "pack_content_sha256",
    "frozen_eval_pack",
    "unseen_for_selection",
    "selected_checkpoint_on_test",
    "normalization_profile",
    "eval_mode",
    "languages",
    "scripts",
    "domains",
    "gt_statuses",
    "splits",
    "script_inventory",
    "claim_safe",
    "warnings",
    "machine",
    "command",
)
PAGE_REQUIRED_RUN_FIELDS = (
    "created_at",
    "system_name",
    "model_name",
    "checkpoint",
    "config",
    "dictionary",
    "artifact_identity",
    "eval_manifest",
    "eval_manifest_sha256",
    "train_manifests",
    "documents_dir",
    "ocr_output_kind",
    "require_output_audit",
    "output_audit_filename",
    "output_audit_passed_field",
    "page_output_audit",
    "script_inventory_file",
    "script_inventory_file_sha256",
    "eval_pack_version",
    "pack_content_sha256",
    "frozen_eval_pack",
    "unseen_for_selection",
    "selected_checkpoint_on_test",
    "line_iou_threshold",
    "language_default",
    "script_default",
    "domain_default",
    "gt_status_default",
    "normalization_profile",
    "languages",
    "scripts",
    "domains",
    "gt_statuses",
    "splits",
    "eval_mode",
    "script_inventory",
    "claim_safe",
    "warnings",
    "machine",
    "command",
)
RECIPE_REQUIRED_FIELDS = (
    "created_at",
    "recipe_id",
    "recipe_file",
    "recipe_file_sha256",
    "root",
    "outputs",
    "train_manifests",
    "recipe_validation",
    "materialization",
    "audit",
    "score",
    "machine",
    "command",
)
CLAIM_SAFE_DOMAINS = {"real_print", "real_handwritten"}
CLAIM_SAFE_GT_STATUSES = {"human_verified", "machine_converted_spot_checked"}
CLAIM_EVAL_SPLITS = {"eval", "test", "heldout", "held_out", "validation"}
SOURCE_DOCUMENT_KEYS = ("source_document", "source_doc", "source_pdf", "source_image", "source_xml", "document", "doc_id")
PAGE_KEYS = ("page", "page_index", "page_number", "source_page", "page_id")
BBOX_KEYS = ("bbox", "bounding_box", "coords", "polygon")
CLAIM_ELIGIBLE_KEYS = ("claim_eligible", "claim_evidence_eligible", "paper_claim_eligible")
HUMAN_REVIEW_EVIDENCE_KEYS = (
    "reviewed_by",
    "reviewer",
    "native_reviewer",
    "gt_reviewer",
    "review_artifact",
    "gt_review_artifact",
    "review_batch",
    "double_reviewed_by",
    "inter_annotator_agreement",
    "correction_rate",
)
PROVENANCE_SIGNAL_KEYS = (
    "label_provenance",
    "gt_source",
    "source_gt_status",
    "source_label_status",
    "reference_status",
    "assisted_source",
    "source_type",
    "data_origin",
    "evidence_type",
    "dataset_type",
    "slices",
)


def _read_json(path: Path) -> Any:
    if not path.exists():
        raise FileNotFoundError(f"JSON artifact does not exist: {path}")
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise ValueError(f"invalid JSON artifact: {path}: {exc}") from exc


def _load_tool(name: str) -> Any:
    path = TOOLS_DIR / f"{name}.py"
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"could not load tool module: {path}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module


def _score_dir(run_dir: Path) -> Path:
    if (run_dir / "eval-run.json").exists() or (run_dir / "page-eval-run.json").exists():
        return run_dir
    if (run_dir / "score").is_dir():
        return run_dir / "score"
    raise FileNotFoundError(f"could not find eval-run.json, page-eval-run.json, or score/ in {run_dir}")


def _mode(score_dir: Path) -> str:
    if (score_dir / "eval-run.json").exists():
        return "recognizer_oracle_crop"
    if (score_dir / "page-eval-run.json").exists():
        return "page_level_ocr"
    raise FileNotFoundError(f"score directory has no eval run JSON: {score_dir}")


def _is_number(value: Any) -> bool:
    return isinstance(value, int | float) and not isinstance(value, bool)


def _close(left: float, right: float, epsilon: float = 1e-12) -> bool:
    return abs(left - right) <= epsilon


def _percentile(values: list[float], q: float) -> float:
    if not values:
        return 0.0
    ordered = sorted(values)
    if len(ordered) == 1:
        return ordered[0]
    position = (len(ordered) - 1) * q
    lower = int(position)
    upper = min(lower + 1, len(ordered) - 1)
    weight = position - lower
    return ordered[lower] * (1.0 - weight) + ordered[upper] * weight


def _confidence_interval(values: list[float]) -> dict[str, float]:
    return {
        "low": _percentile(values, 0.025),
        "high": _percentile(values, 0.975),
    }


def _expected_uncertainty(
    units: list[dict[str, int]],
    *,
    method: str,
    metrics: tuple[str, ...],
) -> dict[str, Any]:
    n = len(units)
    samples: dict[str, list[float]] = {metric: [] for metric in metrics}
    if n:
        rng = random.Random(UNCERTAINTY_BOOTSTRAP_SEED)
        for _ in range(UNCERTAINTY_BOOTSTRAP_SAMPLES):
            totals = {
                "codepoint_edits": 0,
                "codepoint_ref_len": 0,
                "grapheme_edits": 0,
                "grapheme_ref_len": 0,
                "exact": 0,
            }
            for _ in range(n):
                unit = units[rng.randrange(n)]
                for key in totals:
                    totals[key] += unit.get(key, 0)
            if "cer_codepoint_micro" in samples:
                samples["cer_codepoint_micro"].append(totals["codepoint_edits"] / max(totals["codepoint_ref_len"], 1))
            if "cer_grapheme_micro" in samples:
                samples["cer_grapheme_micro"].append(totals["grapheme_edits"] / max(totals["grapheme_ref_len"], 1))
            if "exact_line_accuracy" in samples:
                samples["exact_line_accuracy"].append(totals["exact"] / max(n, 1))
            if "text_cer_codepoint_micro" in samples:
                samples["text_cer_codepoint_micro"].append(totals["codepoint_edits"] / max(totals["codepoint_ref_len"], 1))
            if "text_cer_grapheme_micro" in samples:
                samples["text_cer_grapheme_micro"].append(totals["grapheme_edits"] / max(totals["grapheme_ref_len"], 1))
            if "text_exact_accuracy" in samples:
                samples["text_exact_accuracy"].append(totals["exact"] / max(totals.get("text_reference", n), 1))
    return {
        "method": method,
        "confidence_level": 0.95,
        "bootstrap_samples": UNCERTAINTY_BOOTSTRAP_SAMPLES,
        "seed": UNCERTAINTY_BOOTSTRAP_SEED,
        "scoring_units": n,
        "effective_sample_size": n,
        "min_claim_scoring_units": MIN_CLAIM_SCORING_UNITS,
        "claim_sample_size_ok": n >= MIN_CLAIM_SCORING_UNITS,
        "metrics": {metric: _confidence_interval(samples[metric]) for metric in metrics},
    }


def _check_uncertainty(recorded: Any, expected: dict[str, Any], label: str) -> list[str]:
    issues: list[str] = []
    if not isinstance(recorded, dict):
        return [f"{label} uncertainty is missing or not an object"]
    for key in (
        "method",
        "confidence_level",
        "bootstrap_samples",
        "seed",
        "scoring_units",
        "effective_sample_size",
        "min_claim_scoring_units",
        "claim_sample_size_ok",
    ):
        if recorded.get(key) != expected[key]:
            issues.append(f"{label} uncertainty {key} mismatch: recorded={recorded.get(key)} recomputed={expected[key]}")
    recorded_metrics = recorded.get("metrics")
    expected_metrics = expected["metrics"]
    if not isinstance(recorded_metrics, dict):
        return issues + [f"{label} uncertainty metrics missing or not an object"]
    missing = sorted(set(expected_metrics) - set(recorded_metrics))
    extra = sorted(set(recorded_metrics) - set(expected_metrics))
    if missing:
        issues.append(f"{label} uncertainty metrics missing fields: {missing}")
    if extra:
        issues.append(f"{label} uncertainty metrics contain extra fields: {extra}")
    for metric, expected_interval in expected_metrics.items():
        recorded_interval = recorded_metrics.get(metric)
        if not isinstance(recorded_interval, dict):
            issues.append(f"{label} uncertainty {metric} interval missing or not an object")
            continue
        for bound in ("low", "high"):
            value = recorded_interval.get(bound)
            expected_value = expected_interval[bound]
            if not _is_number(value) or not _close(float(value), expected_value):
                issues.append(f"{label} uncertainty {metric}.{bound} mismatch: recorded={value} recomputed={expected_value}")
    return issues


def _artifact_rows(path: Path) -> int:
    if not path.exists():
        return 0
    with path.open("r", encoding="utf-8", newline="") as handle:
        return max(sum(1 for _ in handle) - 1, 0)


def _csv_rows(path: Path) -> list[dict[str, str]]:
    if not path.exists():
        return []
    with path.open("r", encoding="utf-8", newline="") as handle:
        return list(csv.DictReader(handle))


def _tsv_rows(path: Path) -> list[dict[str, str]]:
    if not path.exists():
        return []
    with path.open("r", encoding="utf-8", newline="") as handle:
        return list(csv.DictReader(handle, delimiter="\t"))


def _short_rows(rows: list[Any], limit: int = 10) -> list[Any | str]:
    visible: list[Any | str] = list(rows[:limit])
    if len(rows) > limit:
        visible.append(f"... {len(rows) - limit} more")
    return visible


def _duplicate_values(rows: list[dict[str, str]], field: str) -> list[str]:
    seen: set[str] = set()
    duplicates: set[str] = set()
    for row in rows:
        value = row.get(field) or ""
        if not value:
            continue
        if value in seen:
            duplicates.add(value)
        seen.add(value)
    return sorted(duplicates)


def _duplicate_keys(rows: list[dict[str, str]], fields: tuple[str, ...]) -> list[tuple[str, ...]]:
    seen: set[tuple[str, ...]] = set()
    duplicates: set[tuple[str, ...]] = set()
    for row in rows:
        key = tuple(row.get(field) or "" for field in fields)
        if not any(key):
            continue
        if key in seen:
            duplicates.add(key)
        seen.add(key)
    return sorted(duplicates)


def _check_unique_field(label: str, rows: list[dict[str, str]], field: str) -> list[str]:
    duplicates = _duplicate_values(rows, field)
    if duplicates:
        return [f"{label} duplicate {field} values: {duplicates[:10]}"]
    return []


def _check_unique_key(label: str, rows: list[dict[str, str]], fields: tuple[str, ...]) -> list[str]:
    duplicates = _duplicate_keys(rows, fields)
    if duplicates:
        return [f"{label} duplicate {','.join(fields)} values: {duplicates[:10]}"]
    return []


def _sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _check_hash_field(eval_run: dict[str, Any], path_field: str, hash_field: str, label: str) -> list[str]:
    issues: list[str] = []
    path_value = eval_run.get(path_field)
    expected = eval_run.get(hash_field)
    if path_value in (None, "") and expected in (None, ""):
        return issues
    if not isinstance(path_value, str) or not path_value:
        issues.append(f"{label} hash is recorded but path is missing: {hash_field}")
        return issues
    if not isinstance(expected, str) or not expected:
        issues.append(f"{label} path is recorded but hash is missing: {hash_field}")
        return issues
    path = Path(path_value)
    if not path.exists():
        issues.append(f"{label} path does not exist for hash verification: {path_value}")
        return issues
    actual = _sha256_file(path)
    if actual != expected:
        issues.append(f"{label} sha256 mismatch for {path_field}: recorded={expected} actual={actual}")
    return issues


def _read_summary_for_audit(eval_run: dict[str, Any], label: str, purpose: str) -> tuple[dict[str, Any], list[str]]:
    summary_file = eval_run.get("summary_file")
    if summary_file in (None, ""):
        return {}, []
    if not isinstance(summary_file, str):
        return {}, [f"{label} summary_file is not a string"]
    path = Path(summary_file)
    if not path.exists():
        return {}, [f"{label} summary file does not exist for {purpose}: {summary_file}"]
    try:
        payload = _read_json(path)
    except (OSError, ValueError) as exc:
        return {}, [f"{label} summary file could not be parsed for {purpose}: {exc}"]
    if not isinstance(payload, dict):
        return {}, [f"{label} summary file is not a JSON object for {purpose}: {summary_file}"]
    return payload, []


def _check_summary_metadata_consistency(eval_run: dict[str, Any], label: str) -> list[str]:
    summary, issues = _read_summary_for_audit(eval_run, label, "metadata audit")
    if issues or not summary:
        return issues

    list_fields = (
        ("language", "languages"),
        ("script", "scripts"),
        ("domain", "domains"),
        ("gt_status", "gt_statuses"),
        ("split", "splits"),
    )
    for summary_field, run_field in list_fields:
        summary_value = summary.get(summary_field)
        if summary_value in (None, ""):
            continue
        run_values = eval_run.get(run_field)
        if not isinstance(run_values, list):
            continue
        run_value_strings = {str(value) for value in run_values}
        if str(summary_value) not in run_value_strings:
            issues.append(f"{label} summary {summary_field} mismatch: summary={summary_value!r} run={run_values!r}")

    summary_version = summary.get("eval_pack_version")
    run_version = eval_run.get("eval_pack_version")
    if summary_version not in (None, "") and run_version not in (None, "") and str(summary_version) != str(run_version):
        issues.append(f"{label} summary eval_pack_version mismatch: summary={summary_version!r} run={run_version!r}")

    for field in ("frozen_eval_pack", "unseen_for_selection", "claim_eligible_default"):
        if field not in summary:
            continue
        summary_value = summary.get(field)
        run_value = eval_run.get(field)
        if not isinstance(summary_value, bool):
            issues.append(f"{label} summary {field} is not boolean: {summary_value!r}")
            continue
        if isinstance(run_value, bool) and summary_value != run_value:
            issues.append(f"{label} summary {field} mismatch: summary={summary_value!r} run={run_value!r}")

    summary_eval_pack = summary.get("eval_pack")
    if isinstance(summary_eval_pack, dict):
        summary_task = summary_eval_pack.get("task")
        run_task = eval_run.get("eval_mode")
        if summary_task not in (None, "") and run_task not in (None, "") and str(summary_task) != str(run_task):
            issues.append(f"{label} summary task mismatch: summary={summary_task!r} run={run_task!r}")
    return issues


def _check_train_manifest_hashes(eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    manifests = eval_run.get("train_manifests")
    if manifests in (None, []):
        return issues
    if not isinstance(manifests, list):
        return ["train_manifests is not a list"]
    for index, manifest in enumerate(manifests):
        if not isinstance(manifest, dict):
            issues.append(f"train_manifests[{index}] is not an object")
            continue
        path_value = manifest.get("path")
        expected = manifest.get("sha256")
        if not isinstance(path_value, str) or not path_value:
            issues.append(f"train_manifests[{index}] missing path")
            continue
        if not isinstance(expected, str) or not expected:
            issues.append(f"train_manifests[{index}] missing sha256")
            continue
        path = Path(path_value)
        if not path.exists():
            issues.append(f"train_manifests[{index}] path does not exist: {path_value}")
            continue
        actual = _sha256_file(path)
        if actual != expected:
            issues.append(f"train_manifests[{index}] sha256 mismatch: recorded={expected} actual={actual}")
    return issues


def _audit_hash_text(value: str) -> str:
    return hashlib.sha256(_nfc(value).encode("utf-8")).hexdigest()


def _audit_sample_hash(image_sha256: str, text_sha256: str) -> str:
    return hashlib.sha256(f"{image_sha256}\0{text_sha256}".encode("utf-8")).hexdigest()


def _train_manifest_paths(eval_run: dict[str, Any]) -> tuple[list[Path], list[str]]:
    manifests = eval_run.get("train_manifests")
    if manifests in (None, []):
        return [], []
    if not isinstance(manifests, list):
        return [], ["train_manifests is not a list for leakage recomputation"]
    paths: list[Path] = []
    issues: list[str] = []
    for index, manifest in enumerate(manifests):
        if not isinstance(manifest, dict):
            issues.append(f"train_manifests[{index}] is not an object for leakage recomputation")
            continue
        path_value = manifest.get("path")
        if not isinstance(path_value, str) or not path_value:
            issues.append(f"train_manifests[{index}] missing path for leakage recomputation")
            continue
        paths.append(Path(path_value))
    return paths, issues


def _audit_manifest_leakage_rows(path: Path, *, manifest_dir: Path | None = None, compute_missing_image_sha: bool) -> tuple[list[dict[str, str]], list[str]]:
    rows: list[dict[str, str]] = []
    issues: list[str] = []
    if not path.exists():
        return rows, [f"leakage manifest does not exist: {path}"]
    base_dir = manifest_dir or path.parent
    with path.open("r", encoding="utf-8") as handle:
        for line_no, line in enumerate(handle, 1):
            line = line.strip()
            if not line:
                continue
            try:
                payload = json.loads(line)
            except json.JSONDecodeError as exc:
                issues.append(f"leakage manifest {path}:{line_no} invalid JSON: {exc}")
                continue
            if not isinstance(payload, dict):
                issues.append(f"leakage manifest {path}:{line_no} row is not an object")
                continue
            metadata = dict(payload.get("metadata") or {})
            sample_id = str(payload.get("sample_id") or payload.get("id") or metadata.get("sample_id") or "")
            image_path = str(payload.get("image_path") or payload.get("image") or metadata.get("image_path") or "")
            image_sha256 = str(payload.get("sha256") or payload.get("image_sha256") or metadata.get("sha256") or "")
            if compute_missing_image_sha and not image_sha256 and image_path:
                resolved = _resolve_audit_manifest_path(image_path, base_dir)
                if resolved.exists():
                    image_sha256 = _sha256_file(resolved)
            text_value = payload.get("text") if payload.get("text") is not None else metadata.get("text")
            text = str(text_value or "")
            text_sha256 = str(payload.get("text_sha256") or metadata.get("text_sha256") or (_audit_hash_text(text) if text else ""))
            sample_sha256 = str(payload.get("sample_sha256") or metadata.get("sample_sha256") or "")
            if not sample_sha256 and image_sha256 and text_sha256:
                sample_sha256 = _audit_sample_hash(image_sha256, text_sha256)
            source_sample_id = str(payload.get("source_sample_id") or metadata.get("source_sample_id") or sample_id)
            rows.append(
                {
                    "sample_id": sample_id,
                    "source_sample_id": source_sample_id,
                    "image_path": image_path,
                    "image_sha256": image_sha256,
                    "text_sha256": text_sha256,
                    "sample_sha256": sample_sha256,
                }
            )
    return rows, issues


def _leakage_overlap(left: list[dict[str, str]], right: list[dict[str, str]], field: str) -> list[str]:
    left_values = {row.get(field) or "" for row in left if row.get(field)}
    right_values = {row.get(field) or "" for row in right if row.get(field)}
    return sorted(left_values & right_values)


def _leakage_overlaps(train_rows: list[dict[str, str]], eval_rows: list[dict[str, str]]) -> dict[str, list[str]]:
    return {
        "sample_id": _leakage_overlap(train_rows, eval_rows, "sample_id"),
        "source_sample_id": _leakage_overlap(train_rows, eval_rows, "source_sample_id"),
        "image_sha256": _leakage_overlap(train_rows, eval_rows, "image_sha256"),
        "sample_sha256": _leakage_overlap(train_rows, eval_rows, "sample_sha256"),
        "image_path": _leakage_overlap(train_rows, eval_rows, "image_path"),
        "text_sha256": _leakage_overlap(train_rows, eval_rows, "text_sha256"),
    }


def _compare_leakage_report(label: str, recorded: Any, expected: dict[str, Any]) -> list[str]:
    if not isinstance(recorded, dict):
        return [f"{label} leakage report is missing or not an object"]
    issues: list[str] = []
    for key in ("train_manifests", "checked", "train_rows", "eval_rows"):
        if recorded.get(key) != expected[key]:
            issues.append(f"{label} leakage {key} mismatch: recorded={recorded.get(key)} recomputed={expected[key]}")
    recorded_overlaps = recorded.get("overlaps")
    if not isinstance(recorded_overlaps, dict):
        issues.append(f"{label} leakage overlaps missing or not an object")
        return issues
    for key, expected_values in expected["overlaps"].items():
        recorded_values = recorded_overlaps.get(key)
        if recorded_values != expected_values:
            issues.append(f"{label} leakage overlaps.{key} mismatch: recorded={recorded_values} recomputed={expected_values}")
    return issues


def _spotcheck_calibration_summary(path: Path) -> tuple[dict[str, Any] | None, list[str]]:
    if not path.exists():
        return None, [f"spotcheck calibration file does not exist for summary audit: {path}"]
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        return None, [f"spotcheck calibration file is invalid JSON for summary audit: {path}: {exc}"]
    if not isinstance(payload, dict):
        return None, [f"spotcheck calibration file must contain an object for summary audit: {path}"]
    return (
        {
            "claim_evidence_eligible": payload.get("claim_evidence_eligible"),
            "recommended_pack_gt_status": payload.get("recommended_pack_gt_status"),
            "language": payload.get("language"),
            "script": payload.get("script"),
            "domain": payload.get("domain"),
            "source_gt_status": payload.get("source_gt_status"),
            "counts": payload.get("counts", {}),
            "machine_label_metrics": payload.get("machine_label_metrics", {}),
            "eligibility_reasons": payload.get("eligibility_reasons", []),
        },
        [],
    )


def _check_spotcheck_calibration_summary(eval_run: dict[str, Any], metrics: dict[str, Any], label: str) -> list[str]:
    path_value = eval_run.get("spotcheck_calibration_file")
    if path_value in (None, ""):
        if eval_run.get("spotcheck_calibration") not in (None, {}):
            return [f"{label} spotcheck_calibration is recorded without spotcheck_calibration_file"]
        if metrics.get("spotcheck_calibration") not in (None, {}):
            return [f"{label} metrics spotcheck_calibration is recorded without spotcheck_calibration_file"]
        return []
    if not isinstance(path_value, str):
        return [f"{label} spotcheck_calibration_file is not a string"]
    expected, issues = _spotcheck_calibration_summary(Path(path_value))
    if issues:
        return issues
    assert expected is not None
    recorded_run = eval_run.get("spotcheck_calibration")
    recorded_metrics = metrics.get("spotcheck_calibration")
    if recorded_run != expected:
        issues.append(f"{label} eval-run spotcheck_calibration does not match calibration file: recorded={recorded_run} recomputed={expected}")
    if recorded_metrics != expected:
        issues.append(f"{label} metrics spotcheck_calibration does not match calibration file: recorded={recorded_metrics} recomputed={expected}")
    return issues


def _check_artifact_identity(eval_run: dict[str, Any], required: tuple[str, ...], label: str) -> list[str]:
    issues: list[str] = []
    artifacts = eval_run.get("artifact_identity")
    if not isinstance(artifacts, dict):
        return [f"{label} artifact_identity is missing or not an object"]
    for name in required:
        identity = artifacts.get(name)
        if not isinstance(identity, dict):
            issues.append(f"{label} artifact_identity.{name} is missing or not an object")
            continue
        if not identity.get("verified"):
            issues.append(f"{label} artifact_identity.{name} is not hash-verifiable: {identity.get('reason') or 'unverified'}")
            continue
        recorded_value = eval_run.get(name)
        identity_value = identity.get("value")
        if not isinstance(recorded_value, str) or not recorded_value:
            issues.append(f"{label} {name} field is missing for artifact_identity consistency")
        elif identity_value != recorded_value:
            issues.append(f"{label} artifact_identity.{name}.value does not match eval-run {name}: recorded={identity_value} eval_run={recorded_value}")
        path_value = identity.get("path") or identity.get("value")
        expected = identity.get("sha256")
        if not isinstance(path_value, str) or not path_value:
            issues.append(f"{label} artifact_identity.{name} missing path")
            continue
        if not isinstance(expected, str) or not expected:
            issues.append(f"{label} artifact_identity.{name} missing sha256")
            continue
        path = Path(path_value)
        if not path.exists():
            issues.append(f"{label} artifact_identity.{name} path does not exist: {path_value}")
            continue
        actual = _sha256_file(path)
        if actual != expected:
            issues.append(f"{label} artifact_identity.{name} sha256 mismatch: recorded={expected} actual={actual}")
    return issues


def _check_required_artifacts(score_dir: Path, names: tuple[str, ...]) -> list[str]:
    issues: list[str] = []
    for name in names:
        path = score_dir / name
        if not path.exists():
            issues.append(f"missing required artifact: {name}")
        elif path.is_file() and path.stat().st_size == 0:
            issues.append(f"empty required artifact: {name}")
    return issues


def _fmt_report_metric(value: Any) -> str:
    if _is_number(value):
        return f"{float(value):.6f}"
    return str(value)


def _expect_report_line(text: str, issues: list[str], line: str) -> None:
    if line not in text.splitlines():
        issues.append(f"claim-safety.md missing or stale line: {line}")


def _check_claim_safety_report_consistency(score_dir: Path, eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    path = score_dir / "claim-safety.md"
    if not path.exists():
        return issues
    text = path.read_text(encoding="utf-8")
    machine = eval_run.get("machine") if isinstance(eval_run.get("machine"), dict) else {}
    expected_lines = [
        f"- eval mode: {eval_run.get('eval_mode')}",
        f"- claim safe: {eval_run.get('claim_safe')}",
        f"- created at: {eval_run.get('created_at')}",
        f"- machine platform: {machine.get('platform')}",
        f"- machine python: {machine.get('python')}",
        f"- command: {eval_run.get('command')}",
        f"- eval pack version: {eval_run.get('eval_pack_version') or '(missing)'}",
        f"- frozen eval pack: {eval_run.get('frozen_eval_pack')}",
        f"- unseen for selection: {eval_run.get('unseen_for_selection')}",
        f"- selected checkpoint on test: {eval_run.get('selected_checkpoint_on_test')}",
        f"- languages: {eval_run.get('languages')}",
        f"- scripts: {eval_run.get('scripts')}",
        f"- domains: {eval_run.get('domains')}",
        f"- GT statuses: {eval_run.get('gt_statuses')}",
        f"- splits: {eval_run.get('splits')}",
        f"- metadata contradictions: {metrics.get('metadata_contradictions', [])}",
    ]
    mode = eval_run.get("eval_mode")
    if mode == "recognizer_oracle_crop":
        uncertainty = metrics.get("uncertainty") if isinstance(metrics.get("uncertainty"), dict) else {}
        intervals = uncertainty.get("metrics") if isinstance(uncertainty.get("metrics"), dict) else {}
        graph_interval = intervals.get("cer_grapheme_micro") if isinstance(intervals.get("cer_grapheme_micro"), dict) else {}
        inventory = metrics.get("script_inventory") if isinstance(metrics.get("script_inventory"), dict) else {}
        normalization = metrics.get("normalization_summary") if isinstance(metrics.get("normalization_summary"), dict) else {}
        dictionary_coverage = metrics.get("dictionary_coverage") if isinstance(metrics.get("dictionary_coverage"), dict) else {}
        expected_lines.extend(
            [
                f"- model: {eval_run.get('model_name')}",
                f"- checkpoint: {eval_run.get('checkpoint') or '(not recorded)'}",
                f"- config: {eval_run.get('config') or '(not recorded)'}",
                f"- dictionary: {eval_run.get('dictionary') or '(not recorded)'}",
                f"- artifact identity: {json.dumps(eval_run.get('artifact_identity', {}), ensure_ascii=False, sort_keys=True)}",
                f"- label file: {eval_run.get('label_file')}",
                f"- prediction file: {eval_run.get('prediction_file')}",
                f"- scored lines: {metrics.get('n_lines')}",
                f"- unmatched labels: {metrics.get('unmatched_labels')}",
                f"- unmatched predictions: {metrics.get('unmatched_predictions')}",
                f"- script inventory file: {inventory.get('inventory_file')}",
                f"- observed codepoints/graphemes: {inventory.get('observed_codepoint_count')}/{inventory.get('observed_grapheme_count')}",
                f"- missing required codepoints: {inventory.get('missing_required_codepoints')}",
                f"- missing required graphemes: {inventory.get('missing_required_graphemes')}",
                f"- normalization profile: {normalization.get('profile')}",
                f"- normalization changed GT/prediction/any: {normalization.get('gt_changed')}/{normalization.get('prediction_changed')}/{normalization.get('any_changed')} of {normalization.get('total')}",
                f"- dictionary coverage checked: {dictionary_coverage.get('checked')}",
                f"- dictionary GT codepoints/dictionary codepoints: {dictionary_coverage.get('gt_codepoint_count')}/{dictionary_coverage.get('dictionary_codepoint_count')}",
                f"- dictionary missing GT codepoints: {dictionary_coverage.get('missing_gt_codepoints')}",
                f"- codepoint CER micro: {_fmt_report_metric(metrics.get('cer_codepoint_micro'))}",
                f"- grapheme CER micro: {_fmt_report_metric(metrics.get('cer_grapheme_micro'))}",
                f"- exact-line accuracy: {_fmt_report_metric(metrics.get('exact_line_accuracy'))}",
                f"- prediction match rate: {_fmt_report_metric(metrics.get('prediction_match_rate'))}",
                f"- codepoint edits/ref: {metrics.get('codepoint_edits')}/{metrics.get('codepoint_ref_len')}",
                f"- grapheme edits/ref: {metrics.get('grapheme_edits')}/{metrics.get('grapheme_ref_len')}",
                f"- zero-length GT lines: {metrics.get('zero_length_gt_lines')}",
                f"- uncertainty method: {uncertainty.get('method')}",
                f"- uncertainty scoring units: {uncertainty.get('effective_sample_size')}/{uncertainty.get('min_claim_scoring_units')}",
                f"- grapheme CER 95% CI: {_fmt_report_metric(graph_interval.get('low'))}..{_fmt_report_metric(graph_interval.get('high'))}",
                "- command.txt",
                "- predictions.tsv",
                "- unmatched.tsv",
                "- worst-lines.csv",
                "- sample-review.csv",
                "- sample-review.html",
                "- confusions.json",
            ]
        )
        slices = metrics.get("slices") if isinstance(metrics.get("slices"), list) else []
        for row in slices:
            if not isinstance(row, dict):
                continue
            expected_lines.append(
                f"- {row.get('language')} / {row.get('script')} / {row.get('domain')} / {row.get('gt_status')} / {row.get('split')}: "
                f"n={row.get('n_lines')} graph_CER={_fmt_report_metric(row.get('cer_grapheme_micro'))} "
                f"cp_CER={_fmt_report_metric(row.get('cer_codepoint_micro'))} exact={_fmt_report_metric(row.get('exact_line_accuracy'))}"
            )
    elif mode == "page_level_ocr":
        metric_means = metrics.get("metric_means") if isinstance(metrics.get("metric_means"), dict) else {}
        uncertainty = metrics.get("uncertainty") if isinstance(metrics.get("uncertainty"), dict) else {}
        intervals = uncertainty.get("metrics") if isinstance(uncertainty.get("metrics"), dict) else {}
        graph_interval = intervals.get("text_cer_grapheme_micro") if isinstance(intervals.get("text_cer_grapheme_micro"), dict) else {}
        inventory = metrics.get("script_inventory") if isinstance(metrics.get("script_inventory"), dict) else {}
        normalization = metrics.get("normalization_summary") if isinstance(metrics.get("normalization_summary"), dict) else {}
        dictionary_coverage = metrics.get("dictionary_coverage") if isinstance(metrics.get("dictionary_coverage"), dict) else {}
        expected_lines.extend(
            [
                f"- system: {eval_run.get('system_name')}",
                f"- model: {eval_run.get('model_name')}",
                f"- checkpoint: {eval_run.get('checkpoint') or '(not recorded)'}",
                f"- config: {eval_run.get('config') or '(not recorded)'}",
                f"- dictionary: {eval_run.get('dictionary') or '(not recorded)'}",
                f"- artifact identity: {json.dumps(eval_run.get('artifact_identity', {}), ensure_ascii=False, sort_keys=True)}",
                f"- normalization profile: {eval_run.get('normalization_profile')}",
                f"- eval manifest: {eval_run.get('eval_manifest')}",
                f"- documents dir: {eval_run.get('documents_dir')}",
                f"- manifest samples: {metrics.get('manifest_samples')}",
                f"- scored pages: {metrics.get('scored_pages')}",
                f"- missing documents: {metrics.get('missing_documents')}",
                f"- missing references: {metrics.get('missing_references')}",
                f"- script inventory file: {inventory.get('inventory_file')}",
                f"- observed codepoints/graphemes: {inventory.get('observed_codepoint_count')}/{inventory.get('observed_grapheme_count')}",
                f"- missing required codepoints: {inventory.get('missing_required_codepoints')}",
                f"- missing required graphemes: {inventory.get('missing_required_graphemes')}",
                f"- normalization profile: {normalization.get('profile')}",
                f"- normalization changed reference/prediction/any: {normalization.get('reference_changed')}/{normalization.get('prediction_changed')}/{normalization.get('any_changed')} of {normalization.get('total')}",
                f"- dictionary coverage checked: {dictionary_coverage.get('checked')}",
                f"- dictionary reference codepoints/dictionary codepoints: {dictionary_coverage.get('gt_codepoint_count')}/{dictionary_coverage.get('dictionary_codepoint_count')}",
                f"- dictionary missing reference codepoints: {dictionary_coverage.get('missing_gt_codepoints')}",
                f"- leakage checked: {metrics.get('leakage', {}).get('checked') if isinstance(metrics.get('leakage'), dict) else None}",
                f"- text codepoint CER micro: {_fmt_report_metric(metrics.get('text_cer_codepoint_micro'))}",
                f"- text grapheme CER micro: {_fmt_report_metric(metrics.get('text_cer_grapheme_micro'))}",
                f"- text exact accuracy: {_fmt_report_metric(metrics.get('text_exact_accuracy'))}",
                f"- line detection F1 mean: {_fmt_report_metric(metric_means.get('line_detection_f1'))}",
                f"- line mean IoU: {_fmt_report_metric(metric_means.get('line_mean_iou'))}",
                f"- reading-order pair accuracy: {_fmt_report_metric(metric_means.get('reading_order_pair_accuracy'))}",
                f"- text codepoint edits/ref: {metrics.get('text_codepoint_edits')}/{metrics.get('text_codepoint_ref_len')}",
                f"- text grapheme edits/ref: {metrics.get('text_grapheme_edits')}/{metrics.get('text_grapheme_ref_len')}",
                f"- text exact pages/ref pages: {metrics.get('text_exact_pages')}/{metrics.get('text_reference_pages')}",
                f"- zero-length text references: {metrics.get('zero_length_text_references')}",
                f"- uncertainty method: {uncertainty.get('method')}",
                f"- uncertainty scoring units: {uncertainty.get('effective_sample_size')}/{uncertainty.get('min_claim_scoring_units')}",
                f"- text grapheme CER 95% CI: {_fmt_report_metric(graph_interval.get('low'))}..{_fmt_report_metric(graph_interval.get('high'))}",
                "- command.txt",
                "- page-metrics.csv",
                "- reference-artifacts.tsv",
                "- text-pairs.tsv",
                "- missing.tsv",
                "- worst-pages.csv",
                "- sample-review.csv",
                "- sample-review.html",
                "- confusions.json",
                "- line-alignment.csv",
            ]
        )
        slices = metrics.get("slices") if isinstance(metrics.get("slices"), list) else []
        for row in slices:
            if not isinstance(row, dict):
                continue
            row_means = row.get("metric_means") if isinstance(row.get("metric_means"), dict) else {}
            expected_lines.append(
                f"- {row.get('language')} / {row.get('script')} / {row.get('domain')} / {row.get('gt_status')} / {row.get('split')}: "
                f"pages={row.get('scored_pages')} text_graph_CER={_fmt_report_metric(row.get('text_cer_grapheme_micro'))} "
                f"text_cp_CER={_fmt_report_metric(row.get('text_cer_codepoint_micro'))} "
                f"exact={_fmt_report_metric(row.get('text_exact_accuracy'))} line_F1={_fmt_report_metric(row_means.get('line_detection_f1', 0.0))}"
            )
    for line in expected_lines:
        _expect_report_line(text, issues, line)
    warnings = eval_run.get("warnings") if isinstance(eval_run.get("warnings"), list) else []
    if warnings:
        for warning in warnings:
            _expect_report_line(text, issues, f"- {warning}")
    else:
        _expect_report_line(text, issues, "- none")
    return issues


def _expect_metrics_line(text: str, issues: list[str], line: str) -> None:
    if line not in text.splitlines():
        issues.append(f"metrics.md missing or stale line: {line}")


def _check_metrics_md_consistency(score_dir: Path, eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    path = score_dir / "metrics.md"
    if not path.exists():
        return issues
    text = path.read_text(encoding="utf-8")
    expected_lines: list[str] = []
    mode = eval_run.get("eval_mode")
    if mode == "recognizer_oracle_crop":
        uncertainty = metrics.get("uncertainty") if isinstance(metrics.get("uncertainty"), dict) else {}
        intervals = uncertainty.get("metrics") if isinstance(uncertainty.get("metrics"), dict) else {}
        graph_interval = intervals.get("cer_grapheme_micro") if isinstance(intervals.get("cer_grapheme_micro"), dict) else {}
        inventory = metrics.get("script_inventory") if isinstance(metrics.get("script_inventory"), dict) else {}
        normalization = metrics.get("normalization_summary") if isinstance(metrics.get("normalization_summary"), dict) else {}
        dictionary_coverage = metrics.get("dictionary_coverage") if isinstance(metrics.get("dictionary_coverage"), dict) else {}
        expected_lines.extend(
            [
                "# Recognizer Eval Metrics",
                f"- lines: {metrics.get('n_lines')}",
                f"- label lines: {metrics.get('label_lines')}",
                f"- prediction match rate: {_fmt_report_metric(metrics.get('prediction_match_rate'))}",
                f"- unmatched labels: {metrics.get('unmatched_labels')}",
                f"- unmatched predictions: {metrics.get('unmatched_predictions')}",
                f"- codepoint CER: {_fmt_report_metric(metrics.get('cer_codepoint_micro'))}",
                f"- grapheme CER: {_fmt_report_metric(metrics.get('cer_grapheme_micro'))}",
                f"- exact-line accuracy: {_fmt_report_metric(metrics.get('exact_line_accuracy'))}",
                f"- codepoint edits/ref: {metrics.get('codepoint_edits')}/{metrics.get('codepoint_ref_len')}",
                f"- grapheme edits/ref: {metrics.get('grapheme_edits')}/{metrics.get('grapheme_ref_len')}",
                f"- zero-length GT lines: {metrics.get('zero_length_gt_lines')}",
                f"- normalization profile: {normalization.get('profile')}",
                f"- normalization changed GT/prediction/any: {normalization.get('gt_changed')}/{normalization.get('prediction_changed')}/{normalization.get('any_changed')} of {normalization.get('total')}",
                f"- dictionary coverage checked: {dictionary_coverage.get('checked')}",
                f"- dictionary GT codepoints/dictionary codepoints: {dictionary_coverage.get('gt_codepoint_count')}/{dictionary_coverage.get('dictionary_codepoint_count')}",
                f"- dictionary missing GT codepoints: {dictionary_coverage.get('missing_gt_codepoints')}",
                f"- uncertainty method: {uncertainty.get('method')}",
                f"- uncertainty scoring units: {uncertainty.get('effective_sample_size')}/{uncertainty.get('min_claim_scoring_units')}",
                f"- grapheme CER 95% CI: {_fmt_report_metric(graph_interval.get('low'))}..{_fmt_report_metric(graph_interval.get('high'))}",
                f"- script inventory file: {inventory.get('inventory_file')}",
                f"- observed codepoints/graphemes: {inventory.get('observed_codepoint_count')}/{inventory.get('observed_grapheme_count')}",
                f"- missing required codepoints: {inventory.get('missing_required_codepoints')}",
                f"- missing required graphemes: {inventory.get('missing_required_graphemes')}",
            ]
        )
        slices = metrics.get("slices") if isinstance(metrics.get("slices"), list) else []
        for row in slices:
            if not isinstance(row, dict):
                continue
            expected_lines.append(
                f"- {row.get('language')} / {row.get('script')} / {row.get('domain')} / {row.get('gt_status')} / {row.get('split')}: "
                f"n={row.get('n_lines')} graph_CER={_fmt_report_metric(row.get('cer_grapheme_micro'))} "
                f"cp_CER={_fmt_report_metric(row.get('cer_codepoint_micro'))} exact={_fmt_report_metric(row.get('exact_line_accuracy'))}"
            )
    elif mode == "page_level_ocr":
        metric_means = metrics.get("metric_means") if isinstance(metrics.get("metric_means"), dict) else {}
        uncertainty = metrics.get("uncertainty") if isinstance(metrics.get("uncertainty"), dict) else {}
        intervals = uncertainty.get("metrics") if isinstance(uncertainty.get("metrics"), dict) else {}
        graph_interval = intervals.get("text_cer_grapheme_micro") if isinstance(intervals.get("text_cer_grapheme_micro"), dict) else {}
        inventory = metrics.get("script_inventory") if isinstance(metrics.get("script_inventory"), dict) else {}
        normalization = metrics.get("normalization_summary") if isinstance(metrics.get("normalization_summary"), dict) else {}
        dictionary_coverage = metrics.get("dictionary_coverage") if isinstance(metrics.get("dictionary_coverage"), dict) else {}
        expected_lines.extend(
            [
                "# Page OCR Eval Metrics",
                f"- manifest samples: {metrics.get('manifest_samples')}",
                f"- scored pages: {metrics.get('scored_pages')}",
                f"- missing documents: {metrics.get('missing_documents')}",
                f"- missing references: {metrics.get('missing_references')}",
                f"- text codepoint CER micro: {_fmt_report_metric(metrics.get('text_cer_codepoint_micro'))}",
                f"- text grapheme CER micro: {_fmt_report_metric(metrics.get('text_cer_grapheme_micro'))}",
                f"- text exact accuracy: {_fmt_report_metric(metrics.get('text_exact_accuracy'))}",
                f"- text codepoint edits/ref: {metrics.get('text_codepoint_edits')}/{metrics.get('text_codepoint_ref_len')}",
                f"- text grapheme edits/ref: {metrics.get('text_grapheme_edits')}/{metrics.get('text_grapheme_ref_len')}",
                f"- text exact pages/ref pages: {metrics.get('text_exact_pages')}/{metrics.get('text_reference_pages')}",
                f"- zero-length text references: {metrics.get('zero_length_text_references')}",
                f"- normalization profile: {normalization.get('profile')}",
                f"- normalization changed reference/prediction/any: {normalization.get('reference_changed')}/{normalization.get('prediction_changed')}/{normalization.get('any_changed')} of {normalization.get('total')}",
                f"- dictionary coverage checked: {dictionary_coverage.get('checked')}",
                f"- dictionary reference codepoints/dictionary codepoints: {dictionary_coverage.get('gt_codepoint_count')}/{dictionary_coverage.get('dictionary_codepoint_count')}",
                f"- dictionary missing reference codepoints: {dictionary_coverage.get('missing_gt_codepoints')}",
                f"- line detection F1 mean: {_fmt_report_metric(metric_means.get('line_detection_f1', 0.0))}",
                f"- line mean IoU: {_fmt_report_metric(metric_means.get('line_mean_iou', 0.0))}",
                f"- uncertainty method: {uncertainty.get('method')}",
                f"- uncertainty scoring units: {uncertainty.get('effective_sample_size')}/{uncertainty.get('min_claim_scoring_units')}",
                f"- text grapheme CER 95% CI: {_fmt_report_metric(graph_interval.get('low'))}..{_fmt_report_metric(graph_interval.get('high'))}",
                f"- script inventory file: {inventory.get('inventory_file')}",
                f"- observed codepoints/graphemes: {inventory.get('observed_codepoint_count')}/{inventory.get('observed_grapheme_count')}",
                f"- missing required codepoints: {inventory.get('missing_required_codepoints')}",
                f"- missing required graphemes: {inventory.get('missing_required_graphemes')}",
            ]
        )
        for key, value in metric_means.items():
            expected_lines.append(f"- {key}: {_fmt_report_metric(value)}")
        slices = metrics.get("slices") if isinstance(metrics.get("slices"), list) else []
        for row in slices:
            if not isinstance(row, dict):
                continue
            row_means = row.get("metric_means") if isinstance(row.get("metric_means"), dict) else {}
            expected_lines.append(
                f"- {row.get('language')} / {row.get('script')} / {row.get('domain')} / {row.get('gt_status')} / {row.get('split')}: "
                f"pages={row.get('scored_pages')} text_graph_CER={_fmt_report_metric(row.get('text_cer_grapheme_micro'))} "
                f"text_cp_CER={_fmt_report_metric(row.get('text_cer_codepoint_micro'))} "
                f"line_F1={_fmt_report_metric(row_means.get('line_detection_f1', 0.0))}"
            )
        coverage = metrics.get("reference_coverage") if isinstance(metrics.get("reference_coverage"), dict) else {}
        for key, value in coverage.items():
            expected_lines.append(f"- {key}: {value}")
    for line in expected_lines:
        _expect_metrics_line(text, issues, line)
    warnings = eval_run.get("warnings") if isinstance(eval_run.get("warnings"), list) else []
    if warnings:
        for warning in warnings:
            _expect_metrics_line(text, issues, f"- {warning}")
    else:
        _expect_metrics_line(text, issues, "- none")
    return issues


def _expect_root_report_line(text: str, issues: list[str], line: str) -> None:
    if line not in text.splitlines():
        issues.append(f"root claim-safety.md missing or stale line: {line}")


def _check_root_claim_safety_report_consistency(
    run_dir: Path,
    recipe_run: dict[str, Any],
    eval_run: dict[str, Any],
    metrics: dict[str, Any],
) -> list[str]:
    issues: list[str] = []
    path = run_dir / "claim-safety.md"
    if not path.exists():
        return issues
    text = path.read_text(encoding="utf-8")
    recipe: dict[str, Any] = {}
    if (run_dir / "recipe.json").exists():
        try:
            raw_recipe = _read_json(run_dir / "recipe.json")
        except (FileNotFoundError, ValueError) as exc:
            issues.append(str(exc))
            raw_recipe = {}
        if isinstance(raw_recipe, dict):
            recipe = raw_recipe
    else:
        issues.append("recipe.json must contain a JSON object")
    recipe_audit = recipe_run.get("audit") if isinstance(recipe_run.get("audit"), dict) else {}
    machine = eval_run.get("machine") if isinstance(eval_run.get("machine"), dict) else {}
    leakage = metrics.get("leakage") if isinstance(metrics.get("leakage"), dict) else {}
    uncertainty = metrics.get("uncertainty") if isinstance(metrics.get("uncertainty"), dict) else {}
    intervals = uncertainty.get("metrics") if isinstance(uncertainty.get("metrics"), dict) else {}
    script_inventory = metrics.get("script_inventory") if isinstance(metrics.get("script_inventory"), dict) else {}
    expected_lines = [
        f"- recipe: {recipe_run.get('recipe_id')}",
        f"- task: {recipe.get('task')}",
        f"- audit passed: {recipe_audit.get('audit_passed')}",
        f"- claim safe: {eval_run.get('claim_safe')}",
        f"- eval mode: {eval_run.get('eval_mode')}",
        f"- score created at: {eval_run.get('created_at')}",
        f"- score machine platform: {machine.get('platform')}",
        f"- score machine python: {machine.get('python')}",
        f"- score command: {eval_run.get('command')}",
    ]
    mode = eval_run.get("eval_mode")
    if mode == "page_level_ocr":
        expected_lines.extend(
            [
                f"- system: {eval_run.get('system_name')}",
                f"- model: {eval_run.get('model_name')}",
                f"- checkpoint: {eval_run.get('checkpoint') or '(not recorded)'}",
                f"- config: {eval_run.get('config') or '(not recorded)'}",
                f"- dictionary: {eval_run.get('dictionary') or '(not recorded)'}",
                f"- artifact identity: {json.dumps(eval_run.get('artifact_identity', {}), ensure_ascii=False, sort_keys=True)}",
                f"- normalization profile: {eval_run.get('normalization_profile')}",
                f"- eval manifest: {eval_run.get('eval_manifest')}",
                f"- documents dir: {eval_run.get('documents_dir')}",
                f"- manifest samples: {metrics.get('manifest_samples')}",
                f"- scored pages: {metrics.get('scored_pages')}",
                f"- missing documents: {metrics.get('missing_documents')}",
                f"- missing references: {metrics.get('missing_references')}",
            ]
        )
    else:
        expected_lines.extend(
            [
                f"- model: {eval_run.get('model_name')}",
                f"- checkpoint: {eval_run.get('checkpoint') or '(not recorded)'}",
                f"- config: {eval_run.get('config') or '(not recorded)'}",
                f"- dictionary: {eval_run.get('dictionary') or '(not recorded)'}",
                f"- artifact identity: {json.dumps(eval_run.get('artifact_identity', {}), ensure_ascii=False, sort_keys=True)}",
                f"- normalization profile: {eval_run.get('normalization_profile')}",
                f"- label file: {eval_run.get('label_file')}",
                f"- prediction file: {eval_run.get('prediction_file')}",
                f"- scored lines: {metrics.get('n_lines')}",
                f"- unmatched labels: {metrics.get('unmatched_labels')}",
                f"- unmatched predictions: {metrics.get('unmatched_predictions')}",
            ]
        )
    expected_lines.extend(
        [
        f"- eval pack version: {eval_run.get('eval_pack_version') or '(missing)'}",
        f"- frozen eval pack: {eval_run.get('frozen_eval_pack')}",
        f"- unseen for selection: {eval_run.get('unseen_for_selection')}",
        f"- selected checkpoint on test: {eval_run.get('selected_checkpoint_on_test')}",
        f"- languages: {eval_run.get('languages')}",
        f"- scripts: {eval_run.get('scripts')}",
        f"- domains: {eval_run.get('domains')}",
        f"- GT statuses: {eval_run.get('gt_statuses')}",
        f"- splits: {eval_run.get('splits')}",
        f"- script inventory file: {script_inventory.get('inventory_file')}",
        f"- observed codepoints/graphemes: {script_inventory.get('observed_codepoint_count')}/{script_inventory.get('observed_grapheme_count')}",
        f"- missing required codepoints: {script_inventory.get('missing_required_codepoints')}",
        f"- missing required graphemes: {script_inventory.get('missing_required_graphemes')}",
        f"- metadata contradictions: {metrics.get('metadata_contradictions', [])}",
        ]
    )
    if mode == "page_level_ocr":
        metric_means = metrics.get("metric_means") if isinstance(metrics.get("metric_means"), dict) else {}
        normalization = metrics.get("normalization_summary") if isinstance(metrics.get("normalization_summary"), dict) else {}
        dictionary_coverage = metrics.get("dictionary_coverage") if isinstance(metrics.get("dictionary_coverage"), dict) else {}
        expected_lines.extend(
            [
                f"- metadata coverage: {metrics.get('metadata_coverage')}",
                f"- reference coverage: {metrics.get('reference_coverage')}",
                f"- normalization changed reference/prediction/any: {normalization.get('reference_changed')}/{normalization.get('prediction_changed')}/{normalization.get('any_changed')} of {normalization.get('total')}",
                f"- dictionary coverage checked: {dictionary_coverage.get('checked')}",
                f"- dictionary reference codepoints/dictionary codepoints: {dictionary_coverage.get('gt_codepoint_count')}/{dictionary_coverage.get('dictionary_codepoint_count')}",
                f"- dictionary missing reference codepoints: {dictionary_coverage.get('missing_gt_codepoints')}",
                f"- leakage checked: {leakage.get('checked')}",
                f"- text codepoint CER micro: {_fmt_report_metric(metrics.get('text_cer_codepoint_micro'))}",
                f"- text grapheme CER micro: {_fmt_report_metric(metrics.get('text_cer_grapheme_micro'))}",
                f"- text exact accuracy: {_fmt_report_metric(metrics.get('text_exact_accuracy'))}",
                f"- line detection F1 mean: {_fmt_report_metric(metric_means.get('line_detection_f1'))}",
                f"- line mean IoU: {_fmt_report_metric(metric_means.get('line_mean_iou'))}",
                f"- reading-order pair accuracy: {_fmt_report_metric(metric_means.get('reading_order_pair_accuracy'))}",
                f"- text codepoint edits/ref: {metrics.get('text_codepoint_edits')}/{metrics.get('text_codepoint_ref_len')}",
                f"- text grapheme edits/ref: {metrics.get('text_grapheme_edits')}/{metrics.get('text_grapheme_ref_len')}",
                f"- text exact pages/ref pages: {metrics.get('text_exact_pages')}/{metrics.get('text_reference_pages')}",
                f"- zero-length text references: {metrics.get('zero_length_text_references')}",
                f"- uncertainty method: {uncertainty.get('method')}",
                f"- uncertainty scoring units: {uncertainty.get('effective_sample_size')}/{uncertainty.get('min_claim_scoring_units')}",
                f"- text grapheme CER 95% CI: {_fmt_report_metric((intervals.get('text_cer_grapheme_micro') or {}).get('low'))}..{_fmt_report_metric((intervals.get('text_cer_grapheme_micro') or {}).get('high'))}",
            ]
        )
        slices = metrics.get("slices") if isinstance(metrics.get("slices"), list) else []
        for row in slices:
            if not isinstance(row, dict):
                continue
            row_means = row.get("metric_means") if isinstance(row.get("metric_means"), dict) else {}
            expected_lines.append(
                f"- {row.get('language')} / {row.get('script')} / {row.get('domain')} / {row.get('gt_status')} / {row.get('split')}: "
                f"pages={row.get('scored_pages')} text_graph_CER={_fmt_report_metric(row.get('text_cer_grapheme_micro'))} "
                f"text_cp_CER={_fmt_report_metric(row.get('text_cer_codepoint_micro'))} "
                f"exact={_fmt_report_metric(row.get('text_exact_accuracy'))} line_F1={_fmt_report_metric(row_means.get('line_detection_f1', 0.0))}"
            )
        expected_lines.extend(
            [
                "- audit JSON: audit.json",
                "- eval run JSON: score/page-eval-run.json",
                "- metrics JSON: score/metrics.json",
                "- metrics Markdown: score/metrics.md",
                "- command text: score/command.txt",
                "- page metrics CSV: score/page-metrics.csv",
                "- reference artifacts TSV: score/reference-artifacts.tsv",
                "- text pairs TSV: score/text-pairs.tsv",
                "- missing TSV: score/missing.tsv",
                "- worst pages: score/worst-pages.csv",
                "- line alignment CSV: score/line-alignment.csv",
                "- review CSV: score/sample-review.csv",
                "- review HTML: score/sample-review.html",
                "- confusions JSON: score/confusions.json",
            ]
        )
    else:
        normalization = metrics.get("normalization_summary") if isinstance(metrics.get("normalization_summary"), dict) else {}
        dictionary_coverage = metrics.get("dictionary_coverage") if isinstance(metrics.get("dictionary_coverage"), dict) else {}
        expected_lines.extend(
            [
                f"- provenance coverage: {metrics.get('provenance_coverage')}",
                f"- normalizer counts: {metrics.get('normalizer_counts', {})}",
                f"- normalization changed GT/prediction/any: {normalization.get('gt_changed')}/{normalization.get('prediction_changed')}/{normalization.get('any_changed')} of {normalization.get('total')}",
                f"- dictionary coverage checked: {dictionary_coverage.get('checked')}",
                f"- dictionary GT codepoints/dictionary codepoints: {dictionary_coverage.get('gt_codepoint_count')}/{dictionary_coverage.get('dictionary_codepoint_count')}",
                f"- dictionary missing GT codepoints: {dictionary_coverage.get('missing_gt_codepoints')}",
                f"- leakage checked: {leakage.get('checked')}",
                f"- codepoint CER micro: {_fmt_report_metric(metrics.get('cer_codepoint_micro'))}",
                f"- grapheme CER micro: {_fmt_report_metric(metrics.get('cer_grapheme_micro'))}",
                f"- exact-line accuracy: {_fmt_report_metric(metrics.get('exact_line_accuracy'))}",
                f"- codepoint edits/ref: {metrics.get('codepoint_edits')}/{metrics.get('codepoint_ref_len')}",
                f"- grapheme edits/ref: {metrics.get('grapheme_edits')}/{metrics.get('grapheme_ref_len')}",
                f"- zero-length GT lines: {metrics.get('zero_length_gt_lines')}",
                f"- uncertainty method: {uncertainty.get('method')}",
                f"- uncertainty scoring units: {uncertainty.get('effective_sample_size')}/{uncertainty.get('min_claim_scoring_units')}",
                f"- grapheme CER 95% CI: {_fmt_report_metric((intervals.get('cer_grapheme_micro') or {}).get('low'))}..{_fmt_report_metric((intervals.get('cer_grapheme_micro') or {}).get('high'))}",
            ]
        )
        slices = metrics.get("slices") if isinstance(metrics.get("slices"), list) else []
        for row in slices:
            if not isinstance(row, dict):
                continue
            expected_lines.append(
                f"- {row.get('language')} / {row.get('script')} / {row.get('domain')} / {row.get('gt_status')} / {row.get('split')}: "
                f"n={row.get('n_lines')} graph_CER={_fmt_report_metric(row.get('cer_grapheme_micro'))} "
                f"cp_CER={_fmt_report_metric(row.get('cer_codepoint_micro'))} exact={_fmt_report_metric(row.get('exact_line_accuracy'))}"
            )
        expected_lines.extend(
            [
                "- audit JSON: audit.json",
                "- eval run JSON: score/eval-run.json",
                "- metrics JSON: score/metrics.json",
                "- metrics Markdown: score/metrics.md",
                "- command text: score/command.txt",
                "- predictions TSV: score/predictions.tsv",
                "- unmatched TSV: score/unmatched.tsv",
                "- worst lines: score/worst-lines.csv",
                "- review CSV: score/sample-review.csv",
                "- review HTML: score/sample-review.html",
                "- confusions JSON: score/confusions.json",
            ]
        )
    for line in expected_lines:
        _expect_root_report_line(text, issues, line)
    warnings = eval_run.get("warnings") if isinstance(eval_run.get("warnings"), list) else []
    if warnings:
        for warning in warnings:
            _expect_root_report_line(text, issues, f"- {warning}")
    else:
        _expect_root_report_line(text, issues, "- none")
    return issues


def _check_timestamp(payload: dict[str, Any], field: str, label: str) -> list[str]:
    value = payload.get(field)
    if not isinstance(value, str) or not value:
        return [f"{label} {field} timestamp is missing"]
    try:
        datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError:
        return [f"{label} {field} timestamp is invalid: {value}"]
    return []


def _check_required_fields(payload: dict[str, Any], fields: tuple[str, ...], label: str) -> list[str]:
    issues: list[str] = []
    for field in fields:
        if field not in payload:
            issues.append(f"{label} missing required field: {field}")
        elif payload[field] in (None, "") and field not in {"checkpoint", "config", "dictionary"}:
            issues.append(f"{label} has empty required field: {field}")
    return issues


def _check_normalization_profile(eval_run: dict[str, Any]) -> list[str]:
    profile = eval_run.get("normalization_profile")
    if profile != SUPPORTED_NORMALIZATION_PROFILE:
        return [
            "eval run normalization_profile does not match supported metric recomputation profile: "
            f"recorded={profile!r} expected={SUPPORTED_NORMALIZATION_PROFILE!r}"
        ]
    return []


def _check_normalization_summary(recorded: Any, expected: dict[str, Any], label: str) -> list[str]:
    if not isinstance(recorded, dict):
        return [f"{label} normalization_summary missing or not an object"]
    issues: list[str] = []
    for key, expected_value in expected.items():
        if recorded.get(key) != expected_value:
            issues.append(f"{label} normalization_summary {key} mismatch: recorded={recorded.get(key)} recomputed={expected_value}")
    return issues


def _expected_recognizer_normalization_summary(score_dir: Path) -> dict[str, Any]:
    rows = _tsv_rows(score_dir / "predictions.tsv")
    gt_changed = sum(1 for row in rows if (row.get("gt_text") or "") != _nfc(row.get("gt_text") or ""))
    prediction_changed = sum(1 for row in rows if (row.get("prediction") or "") != _nfc(row.get("prediction") or ""))
    return {
        "profile": SUPPORTED_NORMALIZATION_PROFILE,
        "unit": "line",
        "total": len(rows),
        "gt_changed": gt_changed,
        "prediction_changed": prediction_changed,
        "any_changed": sum(
            1
            for row in rows
            if (row.get("gt_text") or "") != _nfc(row.get("gt_text") or "")
            or (row.get("prediction") or "") != _nfc(row.get("prediction") or "")
        ),
    }


def _expected_page_normalization_summary(score_dir: Path) -> dict[str, Any]:
    rows = _tsv_rows(score_dir / "text-pairs.tsv")
    prediction_changed = sum(1 for row in rows if (row.get("prediction_text") or "") != _nfc(row.get("prediction_text") or ""))
    reference_changed = sum(1 for row in rows if (row.get("reference_text") or "") != _nfc(row.get("reference_text") or ""))
    return {
        "profile": SUPPORTED_NORMALIZATION_PROFILE,
        "unit": "page",
        "total": len(rows),
        "prediction_changed": prediction_changed,
        "reference_changed": reference_changed,
        "any_changed": sum(
            1
            for row in rows
            if (row.get("prediction_text") or "") != _nfc(row.get("prediction_text") or "")
            or (row.get("reference_text") or "") != _nfc(row.get("reference_text") or "")
        ),
    }


def _check_machine_metadata(payload: dict[str, Any], label: str) -> list[str]:
    machine = payload.get("machine")
    if not isinstance(machine, dict):
        return [f"{label} machine metadata is missing or not an object"]
    issues: list[str] = []
    for field in ("platform", "python"):
        value = machine.get(field)
        if not isinstance(value, str) or not value:
            issues.append(f"{label} machine.{field} is missing")
    return issues


def _check_common(score_dir: Path, eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    if eval_run.get("claim_safe") is True and eval_run.get("warnings"):
        issues.append("claim_safe is true but warnings are present")
    if eval_run.get("claim_safe") is False and not eval_run.get("warnings"):
        issues.append("claim_safe is false but warnings are empty")
    issues.extend(_check_machine_metadata(eval_run, "eval run"))
    if not isinstance(eval_run.get("command"), str) or not eval_run["command"]:
        issues.append("eval run command is missing")
    else:
        command_file = score_dir / "command.txt"
        if command_file.exists() and command_file.read_text(encoding="utf-8").strip() != eval_run["command"].strip():
            issues.append("command.txt does not match eval run command")
    issues.extend(_check_normalization_profile(eval_run))
    issues.extend(_check_timestamp(eval_run, "created_at", "eval run"))
    metrics_md = score_dir / "metrics.md"
    if metrics_md.exists() and not metrics_md.read_text(encoding="utf-8").strip():
        issues.append("metrics.md is blank")
    elif metrics_md.exists():
        issues.extend(_check_metrics_md_consistency(score_dir, eval_run, metrics))
    claim_report = score_dir / "claim-safety.md"
    if claim_report.exists():
        text = claim_report.read_text(encoding="utf-8")
        if not text.strip():
            issues.append("claim-safety.md is blank")
        for marker in ("## What Was Scored", "## Ground Truth And Pack", "## Metrics", "## Warnings"):
            if marker not in text:
                issues.append(f"claim-safety.md missing section: {marker}")
        issues.extend(_check_claim_safety_report_consistency(score_dir, eval_run, metrics))
    if not isinstance(metrics, dict):
        issues.append("metrics artifact is not a JSON object")
    return issues


def _warning_texts(eval_run: dict[str, Any]) -> list[str]:
    warnings = eval_run.get("warnings")
    if not isinstance(warnings, list):
        return []
    return [str(warning) for warning in warnings]


def _has_warning(eval_run: dict[str, Any], prefix: str) -> bool:
    return any(warning.startswith(prefix) for warning in _warning_texts(eval_run))


def _claim_blocker(issues: list[str], eval_run: dict[str, Any], mode: str, reason: str, warning_prefix: str) -> None:
    if eval_run.get("claim_safe") is True:
        issues.append(f"{mode} claim_safe is true despite {reason}")
    if not _has_warning(eval_run, warning_prefix):
        issues.append(f"{mode} missing claim-safety warning for {reason}: {warning_prefix}")


def _string_set(value: Any) -> set[str]:
    if not isinstance(value, list):
        return set()
    return {str(item) for item in value}


def _check_eval_run_identity_lists(
    eval_run: dict[str, Any],
    rows: list[dict[str, str]],
    *,
    run_label: str,
    row_label: str,
) -> list[str]:
    issues: list[str] = []
    if not rows:
        return issues
    mappings = (
        ("languages", "language"),
        ("scripts", "script"),
        ("domains", "domain"),
        ("gt_statuses", "gt_status"),
        ("splits", "split"),
    )
    for run_field, row_field in mappings:
        recorded = eval_run.get(run_field)
        expected = sorted({row.get(row_field) or "" for row in rows})
        if not isinstance(recorded, list):
            issues.append(f"{run_label} {run_field} is not a list for {row_label} identity audit")
            continue
        recorded_values = [str(item) for item in recorded]
        if recorded_values != expected:
            issues.append(
                f"{run_label} {run_field} does not match {row_label} {row_field} values: "
                f"recorded={recorded_values} recomputed={expected}"
            )
    return issues


def _check_shared_claim_blockers(mode: str, eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    if not isinstance(eval_run.get("model_name"), str) or not eval_run["model_name"].strip():
        _claim_blocker(issues, eval_run, mode, "missing model identity", "model name not recorded")
    if mode == "page" and (not isinstance(eval_run.get("system_name"), str) or not eval_run["system_name"].strip()):
        _claim_blocker(issues, eval_run, mode, "missing system identity", "system name not recorded")
    if not eval_run.get("eval_pack_version"):
        _claim_blocker(issues, eval_run, mode, "missing eval-pack version", "eval pack version not recorded")
    artifact_identity = eval_run.get("artifact_identity")
    if isinstance(artifact_identity, dict):
        for name, identity in sorted(artifact_identity.items()):
            if isinstance(identity, dict) and not identity.get("verified"):
                _claim_blocker(issues, eval_run, mode, f"unverified {name} artifact", f"{name} artifact is not hash-verifiable:")
    if eval_run.get("frozen_eval_pack") is not True:
        _claim_blocker(issues, eval_run, mode, "non-frozen eval pack", "eval pack is not declared frozen")
    if eval_run.get("unseen_for_selection") is not True:
        _claim_blocker(issues, eval_run, mode, "eval pack not declared unseen for selection", "eval pack is not declared unseen for model/checkpoint selection")
    if eval_run.get("selected_checkpoint_on_test") is True:
        _claim_blocker(issues, eval_run, mode, "checkpoint selection on test data", "checkpoint/model selection on this test pack is declared")
    if not eval_run.get("summary_file"):
        _claim_blocker(issues, eval_run, mode, "missing eval pack summary/datasheet", "eval pack summary/datasheet missing")
    if metrics.get("metadata_contradictions"):
        _claim_blocker(issues, eval_run, mode, "metadata contradictions", "metadata contradictions detected:")
    if eval_run.get("known_leakage"):
        _claim_blocker(issues, eval_run, mode, "known leakage acknowledgement", "known leakage acknowledged:")

    languages = _string_set(eval_run.get("languages"))
    scripts = _string_set(eval_run.get("scripts"))
    domains = _string_set(eval_run.get("domains"))
    gt_statuses = _string_set(eval_run.get("gt_statuses"))
    splits = _string_set(eval_run.get("splits"))
    if len(languages) > 1:
        _claim_blocker(issues, eval_run, mode, "mixed languages", "mixed languages:")
    if len(scripts) > 1:
        _claim_blocker(issues, eval_run, mode, "mixed scripts", "mixed scripts:")
    if len(domains) > 1:
        _claim_blocker(issues, eval_run, mode, "mixed eval domains", "mixed eval domains:")
    if len(gt_statuses) > 1:
        _claim_blocker(issues, eval_run, mode, "mixed GT statuses", "mixed GT statuses:")
    if len(splits) > 1:
        _claim_blocker(issues, eval_run, mode, "mixed split statuses", "mixed split statuses:")
    if splits and not splits <= CLAIM_EVAL_SPLITS:
        _claim_blocker(issues, eval_run, mode, "unexpected split status", "unexpected split status for claim evaluation:")
    if domains and not domains <= CLAIM_SAFE_DOMAINS:
        _claim_blocker(issues, eval_run, mode, "unsafe eval domain", "not claim-safe real domain:")
    if gt_statuses and not gt_statuses <= CLAIM_SAFE_GT_STATUSES:
        _claim_blocker(issues, eval_run, mode, "untrusted GT status", "not human-verified/spot-checked GT:")
    uncertainty = metrics.get("uncertainty")
    if not isinstance(uncertainty, dict):
        _claim_blocker(issues, eval_run, mode, "missing claim uncertainty evidence", "claim-facing uncertainty missing")
    elif uncertainty.get("claim_sample_size_ok") is not True:
        _claim_blocker(issues, eval_run, mode, "claim-facing sample size too small", "claim-facing sample size too small:")
    slices = metrics.get("slices")
    if isinstance(slices, list):
        for row in slices:
            if not isinstance(row, dict):
                continue
            slice_uncertainty = row.get("uncertainty")
            if isinstance(slice_uncertainty, dict):
                count = int(slice_uncertainty.get("effective_sample_size", 0) or 0)
                minimum = int(slice_uncertainty.get("min_claim_scoring_units", MIN_CLAIM_SCORING_UNITS) or MIN_CLAIM_SCORING_UNITS)
                ok = slice_uncertainty.get("claim_sample_size_ok") is True
            else:
                count = int(row.get("n_lines", row.get("scored_pages", 0)) or 0)
                minimum = MIN_CLAIM_SCORING_UNITS
                ok = count >= minimum
            if not ok or count < minimum:
                _claim_blocker(issues, eval_run, mode, "slice sample size too small", "slice sample size too small:")
    script_inventory = metrics.get("script_inventory")
    if not isinstance(script_inventory, dict) or not script_inventory.get("inventory_file"):
        _claim_blocker(issues, eval_run, mode, "missing script inventory evidence", "script inventory file missing")
    elif script_inventory.get("missing_required_codepoints") or script_inventory.get("missing_required_graphemes"):
        if script_inventory.get("missing_required_codepoints"):
            _claim_blocker(issues, eval_run, mode, "missing required script codepoints", "missing required script codepoints:")
        if script_inventory.get("missing_required_graphemes"):
            _claim_blocker(issues, eval_run, mode, "missing required script graphemes", "missing required script graphemes:")
    if "machine_converted_spot_checked" in gt_statuses:
        calibration = eval_run.get("spotcheck_calibration")
        if not isinstance(calibration, dict):
            _claim_blocker(
                issues,
                eval_run,
                mode,
                "spot-checked machine GT without calibration artifact",
                "machine_converted_spot_checked GT declared without native spot-check calibration artifact",
            )
        elif not calibration.get("claim_evidence_eligible"):
            _claim_blocker(
                issues,
                eval_run,
                mode,
                "ineligible native spot-check calibration",
                "native spot-check calibration artifact is not claim evidence eligible",
            )

    leakage = metrics.get("leakage")
    if not isinstance(leakage, dict):
        _claim_blocker(issues, eval_run, mode, "unrun leakage check", "train/dev leakage check not run")
        return issues
    if not leakage.get("checked"):
        train_manifests = eval_run.get("train_manifests")
        warning_prefix = (
            "train/dev leakage manifests were provided but no train rows were checked"
            if isinstance(train_manifests, list) and train_manifests
            else "train/dev leakage check not run"
        )
        _claim_blocker(issues, eval_run, mode, "unrun leakage check", warning_prefix)
    overlaps = leakage.get("overlaps")
    if not isinstance(overlaps, dict):
        return issues
    hard_leakage = {
        key: values
        for key, values in overlaps.items()
        if key != "text_sha256" and isinstance(values, list) and values
    }
    if hard_leakage:
        _claim_blocker(issues, eval_run, mode, "train/dev/eval leakage", "train/dev/eval leakage detected:")
    text_overlap = overlaps.get("text_sha256")
    if isinstance(text_overlap, list) and text_overlap:
        _claim_blocker(issues, eval_run, mode, "train/dev/eval text overlap", "train/dev/eval text overlap detected:")
    return issues


def _check_recognizer_claim_blockers(eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    issues = _check_shared_claim_blockers("recognizer", eval_run, metrics)
    matched_lines = metrics.get("matched_lines")
    if matched_lines == 0:
        _claim_blocker(issues, eval_run, "recognizer", "no matched rows scored", "no matched rows scored")
    unmatched_count = int(metrics.get("unmatched_labels", 0) or 0) + int(metrics.get("unmatched_predictions", 0) or 0)
    if unmatched_count:
        _claim_blocker(issues, eval_run, "recognizer", "unmatched prediction/label rows", "unmatched rows present:")
    match_rate = metrics.get("prediction_match_rate")
    min_match_rate = eval_run.get("min_match_rate")
    if _is_number(match_rate) and _is_number(min_match_rate) and float(match_rate) < float(min_match_rate):
        _claim_blocker(issues, eval_run, "recognizer", "low prediction match rate", "low prediction match rate:")
    if not eval_run.get("manifest_file"):
        _claim_blocker(issues, eval_run, "recognizer", "missing eval manifest", "eval manifest missing")
    if eval_run.get("claim_eligible_default") is not True:
        _claim_blocker(issues, eval_run, "recognizer", "rows not guaranteed claim eligible", "not all rows are claim eligible:")
    coverage = metrics.get("provenance_coverage")
    if isinstance(coverage, dict):
        for key, count in sorted(coverage.items()):
            if count:
                _claim_blocker(issues, eval_run, "recognizer", f"missing provenance field {key}", f"{key}:")
    return issues


def _check_recognizer_row_claim_eligibility_blockers(score_dir: Path, eval_run: dict[str, Any]) -> list[str]:
    rows = _tsv_rows(score_dir / "predictions.tsv")
    if not rows:
        return []
    ineligible = [
        row.get("sample_id") or row.get("image_path") or f"row-{index}"
        for index, row in enumerate(rows, 1)
        if row.get("claim_eligible") != "True"
    ]
    if not ineligible:
        return []
    issues: list[str] = []
    _claim_blocker(issues, eval_run, "recognizer", "row-level claim ineligible values", "not all rows are claim eligible:")
    return issues


def _read_page_output_audit_for_replay(
    sample_id: str,
    output_dir: Path,
    *,
    filename: str,
    passed_field: str,
) -> dict[str, Any]:
    audit_path = output_dir / filename
    row: dict[str, Any] = {
        "sample_id": sample_id,
        "output_dir": str(output_dir),
        "audit_path": str(audit_path),
        "exists": audit_path.is_file(),
        "passed": False,
        "sha256": None,
        "size_bytes": None,
        "issue": "",
    }
    if not audit_path.is_file():
        row["issue"] = f"missing page output audit: {audit_path}"
        return row
    row["sha256"] = _sha256_file(audit_path)
    row["size_bytes"] = audit_path.stat().st_size
    try:
        payload = json.loads(audit_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        row["issue"] = f"page output audit is invalid JSON: {audit_path}: {exc}"
        return row
    if not isinstance(payload, dict):
        row["issue"] = f"page output audit must contain a JSON object: {audit_path}"
        return row
    passed = payload.get(passed_field)
    row["passed"] = passed is True
    if passed is not True:
        row["issue"] = f"page output audit did not pass: {audit_path} {passed_field}={passed!r}"
    return row


def _expected_page_output_audit(score_dir: Path, eval_run: dict[str, Any]) -> dict[str, Any]:
    required = bool(eval_run.get("require_output_audit"))
    filename = str(eval_run.get("output_audit_filename") or "limbu-output-audit.json")
    passed_field = str(eval_run.get("output_audit_passed_field") or "passed")
    output_audit_rows: list[dict[str, Any]] = []
    page_rows = _csv_rows(score_dir / "page-metrics.csv")
    if required:
        for row in page_rows:
            sample_id = str(row.get("sample_id") or "")
            document_path_value = row.get("document_path") or ""
            if not document_path_value:
                output_audit_rows.append(
                    {
                        "sample_id": sample_id,
                        "output_dir": "",
                        "audit_path": filename,
                        "exists": False,
                        "passed": False,
                        "sha256": None,
                        "size_bytes": None,
                        "issue": f"page-metrics.csv row has no document_path for output audit replay: {sample_id}",
                    }
                )
                continue
            output_audit_rows.append(
                _read_page_output_audit_for_replay(
                    sample_id,
                    Path(document_path_value).parent,
                    filename=filename,
                    passed_field=passed_field,
                )
            )
    return {
        "required": required,
        "filename": filename,
        "passed_field": passed_field,
        "expected_count": len(page_rows) if required else 0,
        "checked_count": len(output_audit_rows),
        "passed_count": sum(1 for row in output_audit_rows if row.get("passed") is True),
        "missing_count": sum(1 for row in output_audit_rows if row.get("exists") is not True),
        "failed_count": sum(1 for row in output_audit_rows if row.get("exists") is True and row.get("passed") is not True),
        "issues": [str(row.get("issue")) for row in output_audit_rows if row.get("issue")],
        "artifacts": output_audit_rows,
    }


def _check_page_output_audit(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    expected = _expected_page_output_audit(score_dir, eval_run)
    recorded_metrics = metrics.get("page_output_audit")
    if not isinstance(recorded_metrics, dict):
        issues.append("metrics.json missing page_output_audit object")
    elif recorded_metrics != expected:
        issues.append("metrics.json page_output_audit does not match current page output audit artifacts")
    recorded_eval_run = eval_run.get("page_output_audit")
    if not isinstance(recorded_eval_run, dict):
        issues.append("page-eval-run.json missing page_output_audit object")
    elif recorded_eval_run != expected:
        issues.append("page-eval-run.json page_output_audit does not match current page output audit artifacts")
    if expected["required"] and expected["passed_count"] != expected["expected_count"]:
        issues.append(
            "replayed page output audits are not all passing: "
            f"{expected['passed_count']}/{expected['expected_count']} filename={expected['filename']!r}"
        )
    return issues


def _check_page_claim_blockers(eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    issues = _check_shared_claim_blockers("page", eval_run, metrics)
    if int(metrics.get("missing_documents", 0) or 0):
        _claim_blocker(issues, eval_run, "page", "missing document outputs", "missing document outputs:")
    if int(metrics.get("missing_references", 0) or 0):
        _claim_blocker(issues, eval_run, "page", "missing references", "missing references:")
    scored_pages = metrics.get("scored_pages")
    manifest_samples = metrics.get("manifest_samples")
    if _is_number(scored_pages) and _is_number(manifest_samples) and int(scored_pages) < int(manifest_samples):
        _claim_blocker(issues, eval_run, "page", "incomplete page scoring coverage", "incomplete page scoring coverage:")
    if metrics.get("document_source_path_mismatches"):
        _claim_blocker(issues, eval_run, "page", "document source_path mismatches", "document source_path mismatches detected:")
    if eval_run.get("claim_eligible_default") is not True:
        _claim_blocker(issues, eval_run, "page", "eval pack not declared claim eligible", "eval pack is not declared claim eligible")
    claim_eligible_rows = metrics.get("claim_eligible_rows")
    if _is_number(claim_eligible_rows) and _is_number(manifest_samples) and int(claim_eligible_rows) != int(manifest_samples):
        _claim_blocker(issues, eval_run, "page", "not all manifest rows are claim eligible", "not all manifest rows are claim eligible:")
    metadata_coverage = metrics.get("metadata_coverage")
    if isinstance(metadata_coverage, dict):
        for key, count in sorted(metadata_coverage.items()):
            if count:
                _claim_blocker(issues, eval_run, "page", f"missing row metadata {key}", f"{key}:")
    reference_coverage = metrics.get("reference_coverage")
    if isinstance(reference_coverage, dict):
        if not reference_coverage.get("text"):
            _claim_blocker(issues, eval_run, "page", "no text references scored", "no text references scored")
        if not reference_coverage.get("reading_order"):
            _claim_blocker(issues, eval_run, "page", "no reading-order references scored", "no reading-order references scored")
        if not reference_coverage.get("line_alignment_scored"):
            _claim_blocker(issues, eval_run, "page", "no line-bbox alignment references scored", "no line-bbox alignment references scored")
        if not (reference_coverage.get("tables") or reference_coverage.get("figures")):
            _claim_blocker(issues, eval_run, "page", "no layout detection references scored", "no layout detection references scored")
    return issues


def _check_ratio(metrics: dict[str, Any], numerator: str, denominator: str, ratio: str) -> list[str]:
    issues: list[str] = []
    for key in (numerator, denominator, ratio):
        if key not in metrics or not _is_number(metrics[key]):
            issues.append(f"metrics missing numeric field: {key}")
            return issues
    expected = metrics[numerator] / max(metrics[denominator], 1)
    if not _close(float(metrics[ratio]), float(expected)):
        issues.append(f"metrics {ratio} does not equal {numerator}/{denominator}")
    return issues


def _nfc(value: str) -> str:
    return unicodedata.normalize("NFC", value or "")


def _graphemes(value: str) -> list[str]:
    return regex.findall(r"\X", _nfc(value))


def _codepoint_id(ch: str) -> str:
    return f"U+{ord(ch):04X}"


def _hash_existing_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _read_script_inventory(path: Path | None) -> tuple[dict[str, Any], list[str]]:
    if path is None:
        return {}, []
    if not path.exists():
        return {}, [f"script inventory file does not exist: {path}"]
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        return {}, [f"script inventory file is invalid JSON: {path}: {exc}"]
    if not isinstance(payload, dict):
        return {}, [f"script inventory file must contain a JSON object: {path}"]
    return payload, []


def _required_codepoints(payload: dict[str, Any]) -> tuple[list[str], list[str]]:
    raw = payload.get("required_codepoints", [])
    if not isinstance(raw, list):
        return [], ["script inventory required_codepoints must be a list"]
    required: set[str] = set()
    issues: list[str] = []
    for item in raw:
        if not isinstance(item, str):
            issues.append(f"script inventory codepoint entry must be a string: {item!r}")
            continue
        value = item.strip()
        if not value:
            continue
        if value.upper().startswith("U+"):
            try:
                required.add(f"U+{int(value[2:], 16):04X}")
            except ValueError:
                issues.append(f"script inventory codepoint entry is not valid hex: {item!r}")
            continue
        normalized = _nfc(value)
        if len(normalized) != 1:
            issues.append(f"script inventory codepoint entry must be one character or U+XXXX: {item!r}")
            continue
        required.add(_codepoint_id(normalized))
    return sorted(required), issues


def _required_graphemes(payload: dict[str, Any]) -> tuple[list[str], list[str]]:
    raw = payload.get("required_graphemes", [])
    if not isinstance(raw, list):
        return [], ["script inventory required_graphemes must be a list"]
    required: set[str] = set()
    issues: list[str] = []
    for item in raw:
        if not isinstance(item, str):
            issues.append(f"script inventory grapheme entry must be a string: {item!r}")
            continue
        value = _nfc(item)
        if value.strip():
            required.add(value)
    return sorted(required), issues


def _expected_script_inventory(texts: list[str], inventory_path: Path | None) -> tuple[dict[str, Any], list[str]]:
    payload, issues = _read_script_inventory(inventory_path)
    required_cps, cp_issues = _required_codepoints(payload)
    required_graphs, graph_issues = _required_graphemes(payload)
    issues.extend(cp_issues)
    issues.extend(graph_issues)
    text = _nfc("\n".join(texts))
    codepoints = sorted({_codepoint_id(ch) for ch in text if not ch.isspace()})
    graphemes = sorted({cluster for cluster in _graphemes(text) if cluster.strip()})
    categories = [unicodedata.category(ch) for ch in text if not ch.isspace()]
    return {
        "inventory_file": str(inventory_path) if inventory_path else None,
        "inventory_file_sha256": _hash_existing_file(inventory_path) if inventory_path and inventory_path.exists() else None,
        "observed_codepoint_count": len(codepoints),
        "observed_grapheme_count": len(graphemes),
        "observed_codepoints": codepoints,
        "observed_graphemes": graphemes,
        "required_codepoints": required_cps,
        "required_graphemes": required_graphs,
        "missing_required_codepoints": sorted(set(required_cps) - set(codepoints)),
        "missing_required_graphemes": sorted(set(required_graphs) - set(graphemes)),
        "digit_codepoint_count": sum(1 for ch in text if not ch.isspace() and unicodedata.category(ch) == "Nd"),
        "punctuation_codepoint_count": sum(1 for category in categories if category.startswith("P")),
        "combining_mark_codepoint_count": sum(1 for category in categories if category.startswith("M")),
    }, issues


def _check_script_inventory(recorded: Any, expected: dict[str, Any], label: str) -> list[str]:
    if not isinstance(recorded, dict):
        return [f"{label} script_inventory missing or not an object"]
    issues: list[str] = []
    for key, expected_value in expected.items():
        if recorded.get(key) != expected_value:
            issues.append(f"{label} script_inventory {key} mismatch: recorded={recorded.get(key)} recomputed={expected_value}")
    return issues


def _dictionary_codepoints(dictionary: str) -> set[str] | None:
    path = Path(str(dictionary or ""))
    if not path.exists() or not path.is_file():
        return None
    codepoints: set[str] = set()
    for line in path.read_text(encoding="utf-8").splitlines():
        token = _nfc(line.strip())
        if not token:
            continue
        for ch in token:
            if not ch.isspace():
                codepoints.add(_codepoint_id(ch))
    return codepoints


def _expected_dictionary_coverage(texts: list[str], dictionary: Any) -> dict[str, Any]:
    dictionary_text = str(dictionary or "")
    dictionary_path = Path(dictionary_text)
    gt_codepoints = sorted({_codepoint_id(ch) for text in texts for ch in _nfc(text) if not ch.isspace()})
    dictionary_codepoints = _dictionary_codepoints(dictionary_text)
    if dictionary_codepoints is None:
        return {
            "dictionary": dictionary_text,
            "dictionary_file_sha256": None,
            "checked": False,
            "gt_codepoint_count": len(gt_codepoints),
            "missing_gt_codepoints": [],
            "missing_gt_codepoint_count": 0,
            "reason": "dictionary file is not readable",
        }
    missing = sorted(set(gt_codepoints) - dictionary_codepoints)
    return {
        "dictionary": dictionary_text,
        "dictionary_file_sha256": _hash_existing_file(dictionary_path),
        "checked": True,
        "dictionary_codepoint_count": len(dictionary_codepoints),
        "gt_codepoint_count": len(gt_codepoints),
        "missing_gt_codepoints": missing,
        "missing_gt_codepoint_count": len(missing),
    }


def _check_dictionary_coverage(recorded: Any, expected: dict[str, Any], label: str) -> list[str]:
    if not isinstance(recorded, dict):
        return [f"{label} dictionary_coverage missing or not an object"]
    issues: list[str] = []
    for key, expected_value in expected.items():
        if recorded.get(key) != expected_value:
            issues.append(f"{label} dictionary_coverage {key} mismatch: recorded={recorded.get(key)} recomputed={expected_value}")
    return issues


def _bool_text(value: str) -> bool | None:
    lowered = str(value).strip().lower()
    if lowered in {"true", "1", "yes", "y"}:
        return True
    if lowered in {"false", "0", "no", "n"}:
        return False
    return None


def _metadata_bool_value(metadata: dict[str, Any], keys: tuple[str, ...], fallback: Any) -> bool:
    for key in keys:
        if key not in metadata:
            continue
        value = metadata[key]
        if isinstance(value, bool):
            return value
        if isinstance(value, str):
            parsed = _bool_text(value)
            if parsed is not None:
                return parsed
        return bool(value)
    return fallback is True


def _metadata_signal_text(metadata: dict[str, Any]) -> str:
    values: list[str] = []
    for key in PROVENANCE_SIGNAL_KEYS:
        value = metadata.get(key)
        if value in (None, "", [], {}):
            continue
        if isinstance(value, list):
            values.extend(str(item) for item in value)
        elif isinstance(value, dict):
            values.extend(f"{item_key}:{item_value}" for item_key, item_value in value.items())
        else:
            values.append(str(value))
    return " ".join(values).lower().replace("_", " ").replace("-", " ")


def _metadata_contradictions_for(sample_id: str, metadata: dict[str, Any], domain: str, gt_status: str) -> list[str]:
    signal_text = _metadata_signal_text(metadata)
    if not signal_text:
        return []
    contradictions: list[str] = []
    if domain in CLAIM_SAFE_DOMAINS and any(term in signal_text for term in ("synthetic", "transliterated", "transliteration")):
        contradictions.append(f"{sample_id}: synthetic/transliterated provenance is declared as real domain {domain}")
    if gt_status == "human_verified" and any(
        term in signal_text
        for term in ("machine converted", "machine", "synthetic", "transliterated", "transliteration")
    ):
        contradictions.append(f"{sample_id}: machine/synthetic provenance is declared as human_verified GT")
    return contradictions


def _metadata_has_any(metadata: dict[str, Any], keys: tuple[str, ...]) -> bool:
    for key in keys:
        if metadata.get(key) not in (None, "", [], {}):
            return True
    return False


def _metadata_value_for_keys(metadata: dict[str, Any], keys: tuple[str, ...]) -> str:
    for key in keys:
        value = metadata.get(key)
        if value not in (None, "", [], {}):
            if isinstance(value, (list, dict)):
                return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
            return str(value)
    return ""


def _bbox_text(bbox: BBox | None) -> str:
    if bbox is None:
        return ""
    return json.dumps(bbox.to_list(), ensure_ascii=False, separators=(",", ":"))


def _int_text(value: str, field: str, row_index: int, issues: list[str]) -> int | None:
    try:
        return int(value)
    except (TypeError, ValueError):
        issues.append(f"predictions.tsv row {row_index} has non-integer {field}: {value!r}")
        return None


def _float_text(value: str, field: str, row_index: int, issues: list[str]) -> float | None:
    try:
        return float(value)
    except (TypeError, ValueError):
        issues.append(f"CSV row {row_index} has non-numeric {field}: {value!r}")
        return None


def _check_recognizer_predictions_recompute(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    rows = _tsv_rows(score_dir / "predictions.tsv")
    if not rows:
        return ["predictions.tsv has no scored rows"]
    cp_edits_total = 0
    cp_len_total = 0
    gr_edits_total = 0
    gr_len_total = 0
    exact_total = 0
    zero_length_gt = 0
    slice_totals: dict[tuple[str, str, str, str, str], dict[str, int]] = {}
    required = {
        "sample_id",
        "image_path",
        "image_sha256",
        "language",
        "script",
        "domain",
        "gt_status",
        "split",
        "claim_eligible",
        "source_document",
        "source_page",
        "source_bbox",
        "gt_text",
        "prediction",
        "codepoint_edits",
        "grapheme_edits",
        "exact",
    }
    for row_index, row in enumerate(rows, 1):
        missing = sorted(required - set(row))
        if missing:
            issues.append(f"predictions.tsv row {row_index} missing columns: {missing}")
            continue
        gt_text = row.get("gt_text") or ""
        prediction = row.get("prediction") or ""
        prediction_nfc = _nfc(prediction)
        gt_nfc = _nfc(gt_text)
        cp_edits = Levenshtein.distance(prediction_nfc, gt_nfc)
        cp_len = len(gt_nfc)
        if cp_len == 0:
            zero_length_gt += 1
        pred_graph = _graphemes(prediction_nfc)
        gt_graph = _graphemes(gt_nfc)
        gr_edits = Levenshtein.distance(pred_graph, gt_graph)
        gr_len = len(gt_graph)
        exact = prediction_nfc == gt_nfc
        recorded_cp = _int_text(row.get("codepoint_edits", ""), "codepoint_edits", row_index, issues)
        recorded_gr = _int_text(row.get("grapheme_edits", ""), "grapheme_edits", row_index, issues)
        recorded_exact = _bool_text(row.get("exact", ""))
        sample_id = row.get("sample_id") or f"row {row_index}"
        if recorded_cp is not None and recorded_cp != cp_edits:
            issues.append(f"predictions.tsv {sample_id} codepoint_edits mismatch: recorded={recorded_cp} recomputed={cp_edits}")
        if recorded_gr is not None and recorded_gr != gr_edits:
            issues.append(f"predictions.tsv {sample_id} grapheme_edits mismatch: recorded={recorded_gr} recomputed={gr_edits}")
        if recorded_exact is None:
            issues.append(f"predictions.tsv {sample_id} exact is not boolean-like: {row.get('exact')!r}")
        elif recorded_exact != exact:
            issues.append(f"predictions.tsv {sample_id} exact mismatch: recorded={recorded_exact} recomputed={exact}")
        cp_edits_total += cp_edits
        cp_len_total += cp_len
        gr_edits_total += gr_edits
        gr_len_total += gr_len
        exact_total += int(exact)
        slice_key = (
            row.get("language") or "",
            row.get("script") or "",
            row.get("domain") or "",
            row.get("gt_status") or "",
            row.get("split") or "",
        )
        bucket = slice_totals.setdefault(
            slice_key,
            {
                "n_lines": 0,
                "matched_lines": 0,
                "codepoint_edits": 0,
                "codepoint_ref_len": 0,
                "grapheme_edits": 0,
                "grapheme_ref_len": 0,
                "exact": 0,
            },
        )
        bucket["n_lines"] += 1
        bucket["matched_lines"] += 1
        bucket["codepoint_edits"] += cp_edits
        bucket["codepoint_ref_len"] += cp_len
        bucket["grapheme_edits"] += gr_edits
        bucket["grapheme_ref_len"] += gr_len
        bucket["exact"] += int(exact)
    expected_values = {
        "n_lines": len(rows),
        "matched_lines": len(rows),
        "zero_length_gt_lines": zero_length_gt,
        "codepoint_edits": cp_edits_total,
        "codepoint_ref_len": cp_len_total,
        "grapheme_edits": gr_edits_total,
        "grapheme_ref_len": gr_len_total,
    }
    for key, expected in expected_values.items():
        if metrics.get(key) != expected:
            issues.append(f"metrics {key} does not match recomputed predictions.tsv value: recorded={metrics.get(key)} recomputed={expected}")
    if zero_length_gt:
        _claim_blocker(issues, eval_run, "recognizer", "zero-length GT rows", "zero-length GT rows present:")
    expected_exact_accuracy = exact_total / max(len(rows), 1)
    if not _is_number(metrics.get("exact_line_accuracy")) or not _close(float(metrics["exact_line_accuracy"]), expected_exact_accuracy):
        issues.append(
            "metrics exact_line_accuracy does not match recomputed predictions.tsv value: "
            f"recorded={metrics.get('exact_line_accuracy')} recomputed={expected_exact_accuracy}"
        )
    expected_cp_cer = cp_edits_total / max(cp_len_total, 1)
    if not _is_number(metrics.get("cer_codepoint_micro")) or not _close(float(metrics["cer_codepoint_micro"]), expected_cp_cer):
        issues.append(
            "metrics cer_codepoint_micro does not match recomputed predictions.tsv value: "
            f"recorded={metrics.get('cer_codepoint_micro')} recomputed={expected_cp_cer}"
        )
    expected_gr_cer = gr_edits_total / max(gr_len_total, 1)
    if not _is_number(metrics.get("cer_grapheme_micro")) or not _close(float(metrics["cer_grapheme_micro"]), expected_gr_cer):
        issues.append(
            "metrics cer_grapheme_micro does not match recomputed predictions.tsv value: "
            f"recorded={metrics.get('cer_grapheme_micro')} recomputed={expected_gr_cer}"
        )
    issues.extend(_check_recognizer_slice_metrics(slice_totals, metrics.get("slices")))
    return issues


def _check_recognizer_uncertainty(score_dir: Path, metrics: dict[str, Any]) -> list[str]:
    units: list[dict[str, int]] = []
    issues: list[str] = []
    for row_index, row in enumerate(_tsv_rows(score_dir / "predictions.tsv"), 1):
        prediction_nfc = _nfc(row.get("prediction") or "")
        gt_nfc = _nfc(row.get("gt_text") or "")
        pred_graph = _graphemes(prediction_nfc)
        gt_graph = _graphemes(gt_nfc)
        units.append(
            {
                "codepoint_edits": Levenshtein.distance(prediction_nfc, gt_nfc),
                "codepoint_ref_len": len(gt_nfc),
                "grapheme_edits": Levenshtein.distance(pred_graph, gt_graph),
                "grapheme_ref_len": len(gt_graph),
                "exact": int(row.get("exact") == "True"),
            }
        )
    expected = _expected_uncertainty(
        units,
        method="deterministic_row_bootstrap",
        metrics=("cer_codepoint_micro", "cer_grapheme_micro", "exact_line_accuracy"),
    )
    issues.extend(_check_uncertainty(metrics.get("uncertainty"), expected, "recognizer"))
    for index, row in enumerate(metrics.get("slices") if isinstance(metrics.get("slices"), list) else [], 1):
        if not isinstance(row, dict):
            continue
        slice_key = (
            str(row.get("language") or ""),
            str(row.get("script") or ""),
            str(row.get("domain") or ""),
            str(row.get("gt_status") or ""),
            str(row.get("split") or ""),
        )
        slice_units: list[dict[str, int]] = []
        for source_row in _tsv_rows(score_dir / "predictions.tsv"):
            source_key = (
                str(source_row.get("language") or ""),
                str(source_row.get("script") or ""),
                str(source_row.get("domain") or ""),
                str(source_row.get("gt_status") or ""),
                str(source_row.get("split") or ""),
            )
            if source_key != slice_key:
                continue
            prediction_nfc = _nfc(source_row.get("prediction") or "")
            gt_nfc = _nfc(source_row.get("gt_text") or "")
            pred_graph = _graphemes(prediction_nfc)
            gt_graph = _graphemes(gt_nfc)
            slice_units.append(
                {
                    "codepoint_edits": Levenshtein.distance(prediction_nfc, gt_nfc),
                    "codepoint_ref_len": len(gt_nfc),
                    "grapheme_edits": Levenshtein.distance(pred_graph, gt_graph),
                    "grapheme_ref_len": len(gt_graph),
                    "exact": int(source_row.get("exact") == "True"),
                }
            )
        expected_slice = _expected_uncertainty(
            slice_units,
            method="deterministic_row_bootstrap",
            metrics=("cer_codepoint_micro", "cer_grapheme_micro", "exact_line_accuracy"),
        )
        issues.extend(_check_uncertainty(row.get("uncertainty"), expected_slice, f"recognizer slices[{index}]"))
    return issues


def _check_recognizer_script_inventory(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    inventory_path = Path(eval_run["script_inventory_file"]) if isinstance(eval_run.get("script_inventory_file"), str) and eval_run.get("script_inventory_file") else None
    expected, issues = _expected_script_inventory([row.get("gt_text") or "" for row in _tsv_rows(score_dir / "predictions.tsv")], inventory_path)
    issues.extend(_check_script_inventory(metrics.get("script_inventory"), expected, "recognizer metrics"))
    issues.extend(_check_script_inventory(eval_run.get("script_inventory"), expected, "recognizer eval-run"))
    return issues


def _check_recognizer_dictionary_coverage(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    expected = _expected_dictionary_coverage(
        [row.get("gt_text") or "" for row in _tsv_rows(score_dir / "predictions.tsv")],
        eval_run.get("dictionary"),
    )
    issues = _check_dictionary_coverage(metrics.get("dictionary_coverage"), expected, "recognizer metrics")
    if expected.get("checked") and expected.get("missing_gt_codepoints"):
        _claim_blocker(issues, eval_run, "recognizer", "GT codepoints missing from dictionary", "GT codepoints missing from dictionary:")
    return issues


def _recognizer_confusions_from_predictions(score_dir: Path, limit: int = 200) -> dict[str, int]:
    counts: dict[str, int] = {}
    for row in _tsv_rows(score_dir / "predictions.tsv"):
        gt = _nfc(row.get("gt_text") or "")
        pred = _nfc(row.get("prediction") or "")
        for opcode in Levenshtein.opcodes(pred, gt):
            tag, i1, i2, j1, j2 = opcode
            if tag == "equal":
                continue
            left = pred[i1:i2] or "<eps>"
            right = gt[j1:j2] or "<eps>"
            key = f"{left}->{right}"
            counts[key] = counts.get(key, 0) + 1
    return dict(sorted(counts.items(), key=lambda item: item[1], reverse=True)[:limit])


def _check_recognizer_confusions(score_dir: Path) -> list[str]:
    path = score_dir / "confusions.json"
    if not path.exists():
        return []
    try:
        payload = _read_json(path)
    except (FileNotFoundError, ValueError) as exc:
        return [str(exc)]
    if not isinstance(payload, dict):
        return ["confusions.json must contain a JSON object"]

    issues: list[str] = []
    recorded: dict[str, int] = {}
    for key, value in payload.items():
        if isinstance(value, bool) or not isinstance(value, int):
            issues.append(f"confusions.json {key!r} count is not an integer: {value!r}")
            continue
        recorded[str(key)] = value
    expected = _recognizer_confusions_from_predictions(score_dir)
    if recorded != expected:
        issues.append(f"confusions.json does not match recomputed predictions.tsv confusions: recorded={recorded} recomputed={expected}")
    return issues


def _check_recognizer_slice_metrics(slice_totals: dict[tuple[str, str, str, str, str], dict[str, int]], slices: Any) -> list[str]:
    issues: list[str] = []
    if not isinstance(slices, list) or not slices:
        return ["recognizer slice metrics are missing"]
    recorded_by_key: dict[tuple[str, str, str, str, str], dict[str, Any]] = {}
    for index, row in enumerate(slices, 1):
        if not isinstance(row, dict):
            issues.append(f"recognizer slices[{index}] is not an object")
            continue
        key = (
            str(row.get("language") or ""),
            str(row.get("script") or ""),
            str(row.get("domain") or ""),
            str(row.get("gt_status") or ""),
            str(row.get("split") or ""),
        )
        if key in recorded_by_key:
            issues.append(f"duplicate recognizer slice metric for {key}")
        recorded_by_key[key] = row
    expected_keys = set(slice_totals)
    recorded_keys = set(recorded_by_key)
    missing = sorted(expected_keys - recorded_keys)
    extra = sorted(recorded_keys - expected_keys)
    if missing:
        issues.append(f"recognizer slice metrics missing slices: {missing[:10]}")
    if extra:
        issues.append(f"recognizer slice metrics contain extra slices: {extra[:10]}")
    for key in sorted(expected_keys & recorded_keys):
        totals = slice_totals[key]
        recorded = recorded_by_key[key]
        expected_numbers: dict[str, float | int] = {
            "n_lines": totals["n_lines"],
            "matched_lines": totals["matched_lines"],
            "codepoint_edits": totals["codepoint_edits"],
            "codepoint_ref_len": totals["codepoint_ref_len"],
            "cer_codepoint_micro": totals["codepoint_edits"] / max(totals["codepoint_ref_len"], 1),
            "grapheme_edits": totals["grapheme_edits"],
            "grapheme_ref_len": totals["grapheme_ref_len"],
            "cer_grapheme_micro": totals["grapheme_edits"] / max(totals["grapheme_ref_len"], 1),
            "exact_line_accuracy": totals["exact"] / max(totals["n_lines"], 1),
        }
        for field, expected in expected_numbers.items():
            value = recorded.get(field)
            if isinstance(expected, int):
                if value != expected:
                    issues.append(f"recognizer slice {key} {field} mismatch: recorded={value} recomputed={expected}")
            elif not _is_number(value) or not _close(float(value), expected):
                issues.append(f"recognizer slice {key} {field} mismatch: recorded={value} recomputed={expected}")
    return issues


def _expected_recognizer_worst_rows(score_dir: Path) -> tuple[list[dict[str, Any]], list[str]]:
    issues: list[str] = []
    expected_rows: list[dict[str, Any]] = []
    for row_index, row in enumerate(_tsv_rows(score_dir / "predictions.tsv"), 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        gt_text = row.get("gt_text") or ""
        prediction = row.get("prediction") or ""
        prediction_nfc = _nfc(prediction)
        gt_nfc = _nfc(gt_text)
        cp_edits = Levenshtein.distance(prediction_nfc, gt_nfc)
        cp_len = len(gt_nfc)
        pred_graph = _graphemes(prediction_nfc)
        gt_graph = _graphemes(gt_nfc)
        gr_edits = Levenshtein.distance(pred_graph, gt_graph)
        gr_len = len(gt_graph)
        expected_rows.append(
            {
                "sample_id": sample_id,
                "image_path": row.get("image_path") or "",
                "image_sha256": row.get("image_sha256") or "",
                "language": row.get("language") or "",
                "script": row.get("script") or "",
                "domain": row.get("domain") or "",
                "gt_status": row.get("gt_status") or "",
                "split": row.get("split") or "",
                "claim_eligible": row.get("claim_eligible") or "",
                "source_document": row.get("source_document") or "",
                "source_page": row.get("source_page") or "",
                "source_bbox": row.get("source_bbox") or "",
                "gt_text": gt_text,
                "prediction": prediction,
                "prediction_score": row.get("prediction_score") or "",
                "cer_codepoint": cp_edits / max(cp_len, 1),
                "cer_grapheme": gr_edits / max(gr_len, 1),
                "sort_key": (gr_edits / max(gr_len, 1), gr_edits),
            }
        )
    expected_rows.sort(key=lambda row: row["sort_key"], reverse=True)
    return expected_rows, issues


def _check_sample_id_order(label: str, expected_rows: list[dict[str, Any]], recorded_rows: list[dict[str, str]]) -> list[str]:
    if expected_rows and not recorded_rows:
        return [f"{label} has no review rows"]
    if len(recorded_rows) > len(expected_rows):
        return [f"{label} has more rows than scored examples: recorded={len(recorded_rows)} scored={len(expected_rows)}"]
    expected_ids = [str(row["sample_id"]) for row in expected_rows[: len(recorded_rows)]]
    recorded_ids = [row.get("sample_id") or "" for row in recorded_rows]
    if recorded_ids != expected_ids:
        return [f"{label} sample order does not match recomputed worst examples: recorded={recorded_ids} recomputed={expected_ids}"]
    return []


def _check_review_csv_fields(
    label: str,
    expected_rows: list[dict[str, Any]],
    recorded_rows: list[dict[str, str]],
    fields: tuple[str, ...],
) -> list[str]:
    issues: list[str] = []
    expected_by_id = {str(row["sample_id"]): row for row in expected_rows}
    for row_index, row in enumerate(recorded_rows, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        expected = expected_by_id.get(sample_id)
        if expected is None:
            continue
        for field in fields:
            expected_value = expected.get(field)
            if isinstance(expected_value, float):
                recorded = _float_text(row.get(field, ""), field, row_index, issues)
                if recorded is not None and not _close(recorded, expected_value):
                    issues.append(f"{label} {sample_id} {field} mismatch: recorded={recorded} recomputed={expected_value}")
            elif (row.get(field) or "") != str(expected_value or ""):
                issues.append(f"{label} {sample_id} {field} mismatch")
    return issues


def _check_review_html_contents(
    score_dir: Path,
    label: str,
    expected_rows: list[dict[str, Any]],
    review_rows: list[dict[str, str]],
    fields: tuple[str, ...],
) -> list[str]:
    path = score_dir / "sample-review.html"
    if not path.exists() or not review_rows:
        return []
    try:
        content = path.read_text(encoding="utf-8")
    except OSError as exc:
        return [f"sample-review.html could not be read: {exc}"]

    issues: list[str] = []
    for row in expected_rows[: len(review_rows)]:
        sample_id = str(row["sample_id"])
        missing_fields: list[str] = []
        for field in fields:
            value = str(row.get(field) or "")
            if value and html.escape(value) not in content:
                missing_fields.append(field)
        if missing_fields:
            issues.append(f"sample-review.html missing {label} review sample {sample_id} fields: {missing_fields}")
    return issues


def _check_recognizer_worst_artifacts(score_dir: Path) -> list[str]:
    issues: list[str] = []
    expected_rows, row_issues = _expected_recognizer_worst_rows(score_dir)
    issues.extend(row_issues)
    worst_rows = _csv_rows(score_dir / "worst-lines.csv")
    review_rows = _csv_rows(score_dir / "sample-review.csv")
    issues.extend(_check_sample_id_order("worst-lines.csv", expected_rows, worst_rows))
    issues.extend(_check_sample_id_order("sample-review.csv", expected_rows, review_rows))
    issues.extend(_check_review_csv_fields("sample-review.csv", expected_rows, review_rows, ("image_path", "gt_text", "prediction", "prediction_score")))
    issues.extend(
        _check_review_html_contents(
            score_dir,
            "recognizer",
            expected_rows,
            review_rows,
            ("sample_id", "image_path", "gt_text", "prediction"),
        )
    )
    expected_by_id = {str(row["sample_id"]): row for row in expected_rows}
    for row_index, row in enumerate(worst_rows, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        expected = expected_by_id.get(sample_id)
        if expected is None:
            continue
        for field in ("cer_grapheme", "cer_codepoint"):
            recorded = _float_text(row.get(field, ""), field, row_index, issues)
            if recorded is not None and not _close(recorded, float(expected[field])):
                issues.append(f"worst-lines.csv {sample_id} {field} mismatch: recorded={recorded} recomputed={expected[field]}")
        for field in (
            "image_path",
            "image_sha256",
            "language",
            "script",
            "domain",
            "gt_status",
            "split",
            "claim_eligible",
            "source_document",
            "source_page",
            "source_bbox",
            "gt_text",
            "prediction",
            "prediction_score",
        ):
            if (row.get(field) or "") != str(expected[field]):
                issues.append(f"worst-lines.csv {sample_id} {field} mismatch")
    return issues


def _check_recognizer_output_duplicates(score_dir: Path) -> list[str]:
    issues: list[str] = []
    predictions = _tsv_rows(score_dir / "predictions.tsv")
    worst_rows = _csv_rows(score_dir / "worst-lines.csv")
    review_rows = _csv_rows(score_dir / "sample-review.csv")
    unmatched_rows = _tsv_rows(score_dir / "unmatched.tsv")
    issues.extend(_check_unique_field("predictions.tsv", predictions, "sample_id"))
    issues.extend(_check_unique_field("predictions.tsv", predictions, "image_path"))
    issues.extend(_check_unique_field("worst-lines.csv", worst_rows, "sample_id"))
    issues.extend(_check_unique_field("sample-review.csv", review_rows, "sample_id"))
    issues.extend(_check_unique_key("unmatched.tsv", unmatched_rows, ("kind", "image_path")))
    return issues


def _read_recognizer_label_source(path: Path) -> tuple[list[dict[str, str]], list[str]]:
    issues: list[str] = []
    rows: list[dict[str, str]] = []
    seen: set[str] = set()
    if not path.exists():
        return rows, [f"recognizer label source does not exist for unmatched audit: {path}"]
    with path.open("r", encoding="utf-8", newline="") as handle:
        for line_no, line in enumerate(handle, 1):
            line = line.rstrip("\n")
            if not line:
                continue
            if "\t" not in line:
                issues.append(f"recognizer label source {path}:{line_no} is not tab-separated")
                continue
            image_path, text = line.split("\t", 1)
            image_key = Path(image_path).name
            if image_key in seen:
                issues.append(f"recognizer label source duplicate image basename: {image_key}")
            seen.add(image_key)
            rows.append({"image_key": image_key, "image_path": image_path, "text": text})
    return rows, issues


def _read_recognizer_prediction_source(path: Path) -> tuple[list[dict[str, str]], list[str]]:
    issues: list[str] = []
    rows: list[dict[str, str]] = []
    seen: set[str] = set()
    if not path.exists():
        return rows, [f"recognizer prediction source does not exist for unmatched audit: {path}"]
    with path.open("r", encoding="utf-8", newline="") as handle:
        for line_no, line in enumerate(handle, 1):
            line = line.rstrip("\n")
            if not line:
                continue
            parts = line.split("\t")
            if len(parts) < 2:
                issues.append(f"recognizer prediction source {path}:{line_no} is not tab-separated")
                continue
            image_path = parts[0]
            image_key = Path(image_path).name
            if image_key in seen:
                issues.append(f"recognizer prediction source duplicate image basename: {image_key}")
            seen.add(image_key)
            rows.append({"image_key": image_key, "image_path": image_path, "text": parts[1], "score": parts[2] if len(parts) > 2 else ""})
    return rows, issues


def _read_recognizer_manifest_source(path_value: Any) -> tuple[dict[str, dict[str, Any]], list[str]]:
    if not isinstance(path_value, str) or not path_value:
        return {}, []
    path = Path(path_value)
    if not path.exists():
        return {}, [f"recognizer manifest source does not exist for predictions.tsv audit: {path}"]
    rows: dict[str, dict[str, Any]] = {}
    seen_ids: set[str] = set()
    issues: list[str] = []
    with path.open("r", encoding="utf-8") as handle:
        for line_no, line in enumerate(handle, 1):
            line = line.strip()
            if not line:
                continue
            try:
                payload = json.loads(line)
            except json.JSONDecodeError as exc:
                issues.append(f"recognizer manifest source {path}:{line_no} invalid JSON: {exc}")
                continue
            if not isinstance(payload, dict):
                issues.append(f"recognizer manifest source {path}:{line_no} row is not an object")
                continue
            sample_id = str(payload.get("sample_id") or "")
            if sample_id:
                if sample_id in seen_ids:
                    issues.append(f"recognizer manifest source duplicate sample_id: {sample_id}")
                seen_ids.add(sample_id)
                rows[sample_id] = payload
            image_path = str(payload.get("image_path") or payload.get("image") or "")
            if image_path:
                rows[image_path] = payload
                rows[Path(image_path).name] = payload
    return rows, issues


def _recognizer_metadata_for(label: dict[str, str], manifest: dict[str, dict[str, Any]]) -> dict[str, Any]:
    payload = manifest.get(label["image_path"]) or manifest.get(label["image_key"]) or {}
    metadata = dict(payload.get("metadata") or {})
    for key, value in payload.items():
        if key == "metadata":
            continue
        if key not in metadata:
            metadata[key] = value
    for key in ("sample_id", "dataset", "split", "image_path", "sha256"):
        if key in payload and key not in metadata:
            metadata[key] = payload[key]
    return metadata


def _recognizer_eval_run_fallback(eval_run: dict[str, Any], key: str) -> str:
    values = eval_run.get(key)
    if isinstance(values, list) and len(values) == 1:
        return str(values[0])
    return ""


def _recognizer_domain(metadata: dict[str, Any], fallback: str) -> str:
    for key in ("domain", "eval_domain"):
        if metadata.get(key):
            return str(metadata[key])
    slices = metadata.get("slices")
    if isinstance(slices, list):
        if "synthetic" in slices:
            return "synthetic"
        if "real" in slices:
            return fallback
    return fallback


def _recognizer_gt_status(metadata: dict[str, Any], fallback: str) -> str:
    for key in ("gt_status", "label_status"):
        if metadata.get(key):
            return str(metadata[key])
    provenance = str(metadata.get("label_provenance") or "").lower()
    if "human" in provenance and "pending" not in provenance:
        return "human_verified"
    return fallback


def _expected_recognizer_prediction_rows(eval_run: dict[str, Any]) -> tuple[list[dict[str, str]], list[str]]:
    label_file = eval_run.get("label_file")
    prediction_file = eval_run.get("prediction_file")
    data_dir = eval_run.get("data_dir")
    if not isinstance(label_file, str) or not label_file:
        return [], ["eval-run.json missing label_file for predictions.tsv source audit"]
    if not isinstance(prediction_file, str) or not prediction_file:
        return [], ["eval-run.json missing prediction_file for predictions.tsv source audit"]
    if not isinstance(data_dir, str) or not data_dir:
        return [], ["eval-run.json missing data_dir for predictions.tsv source audit"]

    labels, label_issues = _read_recognizer_label_source(Path(label_file))
    predictions, prediction_issues = _read_recognizer_prediction_source(Path(prediction_file))
    manifest, manifest_issues = _read_recognizer_manifest_source(eval_run.get("manifest_file"))
    issues = [*label_issues, *prediction_issues, *manifest_issues]
    if issues:
        return [], issues

    prediction_by_key = {row["image_key"]: row for row in predictions}
    language_fallback = _recognizer_eval_run_fallback(eval_run, "languages")
    script_fallback = _recognizer_eval_run_fallback(eval_run, "scripts")
    domain_fallback = _recognizer_eval_run_fallback(eval_run, "domains")
    gt_status_fallback = _recognizer_eval_run_fallback(eval_run, "gt_statuses")
    split_fallback = _recognizer_eval_run_fallback(eval_run, "splits")
    expected: list[dict[str, str]] = []
    seen_sample_ids: set[str] = set()
    for index, label in enumerate(labels):
        prediction = prediction_by_key.get(label["image_key"])
        if prediction is None:
            continue
        metadata = _recognizer_metadata_for(label, manifest)
        sample_id = str(metadata.get("sample_id") or f"row-{index:06d}")
        if sample_id in seen_sample_ids:
            issues.append(f"recognizer source rows duplicate resolved sample_id: {sample_id}")
        seen_sample_ids.add(sample_id)
        image_path = Path(data_dir) / label["image_path"]
        image_sha256 = _sha256_file(image_path) if image_path.exists() else ""
        declared_image_sha256 = str(metadata.get("sha256") or metadata.get("image_sha256") or "")
        if declared_image_sha256 and declared_image_sha256 != image_sha256:
            issues.append(
                f"recognizer manifest {sample_id} sha256 mismatch: "
                f"recorded={declared_image_sha256} actual={image_sha256}"
            )
        text_sha256 = _audit_hash_text(label["text"])
        declared_text_sha256 = str(metadata.get("text_sha256") or "")
        if declared_text_sha256 and declared_text_sha256 != text_sha256:
            issues.append(
                f"recognizer manifest {sample_id} text_sha256 mismatch: "
                f"recorded={declared_text_sha256} actual={text_sha256}"
            )
        declared_sample_sha256 = str(metadata.get("sample_sha256") or "")
        if declared_sample_sha256:
            actual_sample_sha256 = _audit_sample_hash(image_sha256, text_sha256)
            if declared_sample_sha256 != actual_sample_sha256:
                issues.append(
                    f"recognizer manifest {sample_id} sample_sha256 mismatch: "
                    f"recorded={declared_sample_sha256} actual={actual_sample_sha256}"
                )
        expected.append(
            {
                "sample_id": sample_id,
                "image_path": label["image_path"],
                "image_sha256": image_sha256,
                "language": str(metadata.get("language") or language_fallback),
                "script": str(metadata.get("script") or script_fallback),
                "domain": _recognizer_domain(metadata, domain_fallback),
                "gt_status": _recognizer_gt_status(metadata, gt_status_fallback),
                "split": str(metadata.get("split") or metadata.get("split_role") or split_fallback),
                "claim_eligible": str(_metadata_bool_value(metadata, CLAIM_ELIGIBLE_KEYS, eval_run.get("claim_eligible_default"))),
                "source_document": _metadata_value_for_keys(metadata, SOURCE_DOCUMENT_KEYS),
                "source_page": _metadata_value_for_keys(metadata, PAGE_KEYS),
                "source_bbox": _metadata_value_for_keys(metadata, BBOX_KEYS),
                "gt_text": label["text"],
                "prediction": prediction["text"],
                "prediction_score": prediction["score"],
            }
        )
    return expected, issues


def _recognizer_pack_content_digest(rows: list[dict[str, str]]) -> str:
    canonical_rows = [
        {
            "sample_id": row.get("sample_id") or "",
            "image_sha256": row.get("image_sha256") or "",
            "gt_text_sha256_nfc": _audit_hash_text(row.get("gt_text") or ""),
            "language": row.get("language") or "",
            "script": row.get("script") or "",
            "domain": row.get("domain") or "",
            "gt_status": row.get("gt_status") or "",
            "split": row.get("split") or "",
            "claim_eligible": _bool_text(row.get("claim_eligible") or ""),
        }
        for row in rows
    ]
    payload = "\n".join(
        json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
        for row in sorted(canonical_rows, key=lambda item: item["sample_id"])
    )
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def _summary_pack_content_sha256(summary: dict[str, Any]) -> str:
    value = summary.get("pack_content_sha256")
    if isinstance(value, str) and value:
        return value
    eval_pack = summary.get("eval_pack")
    if isinstance(eval_pack, dict):
        nested = eval_pack.get("pack_content_sha256")
        if isinstance(nested, str) and nested:
            return nested
    return ""


def _check_recognizer_pack_content_digest(eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    expected_rows, issues = _expected_recognizer_prediction_rows(eval_run)
    if issues:
        return issues
    expected = _recognizer_pack_content_digest(expected_rows)
    for label, payload in (("eval-run.json", eval_run), ("metrics.json", metrics)):
        recorded = payload.get("pack_content_sha256")
        if recorded != expected:
            issues.append(f"{label} pack_content_sha256 mismatch: recorded={recorded!r} recomputed={expected}")
    summary, summary_issues = _read_summary_for_audit(eval_run, "recognizer", "pack content digest audit")
    issues.extend(summary_issues)
    if summary:
        summary_digest = _summary_pack_content_sha256(summary)
        if not summary_digest:
            issues.append("recognizer summary missing pack_content_sha256")
        elif summary_digest != expected:
            issues.append(f"recognizer summary pack_content_sha256 mismatch: recorded={summary_digest} recomputed={expected}")
    return issues


def _check_recognizer_prediction_source_rows(score_dir: Path, eval_run: dict[str, Any]) -> list[str]:
    recorded = _tsv_rows(score_dir / "predictions.tsv")
    expected, issues = _expected_recognizer_prediction_rows(eval_run)
    if issues:
        return issues
    if len(recorded) != len(expected):
        issues.append(f"predictions.tsv row count does not match source matched rows: recorded={len(recorded)} recomputed={len(expected)}")
    for index in range(min(len(recorded), len(expected))):
        recorded_row = recorded[index]
        expected_row = expected[index]
        sample_id = recorded_row.get("sample_id") or expected_row["sample_id"] or f"row {index + 1}"
        for field in (
            "sample_id",
            "image_path",
            "image_sha256",
            "language",
            "script",
            "domain",
            "gt_status",
            "split",
            "claim_eligible",
            "source_document",
            "source_page",
            "source_bbox",
            "gt_text",
            "prediction",
            "prediction_score",
        ):
            if (recorded_row.get(field) or "") != expected_row[field]:
                issues.append(f"predictions.tsv {sample_id} {field} does not match source files")
    return issues


def _check_recognizer_metadata_contradictions(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    manifest, manifest_issues = _read_recognizer_manifest_source(eval_run.get("manifest_file"))
    if manifest_issues:
        return manifest_issues
    expected: list[str] = []
    for row in _tsv_rows(score_dir / "predictions.tsv"):
        image_path = row.get("image_path") or ""
        label = {"image_path": image_path, "image_key": Path(image_path).name}
        metadata = _recognizer_metadata_for(label, manifest)
        sample_id = row.get("sample_id") or str(metadata.get("sample_id") or "")
        expected.extend(
            _metadata_contradictions_for(
                sample_id,
                metadata,
                row.get("domain") or "",
                row.get("gt_status") or "",
            )
        )
    recorded = metrics.get("metadata_contradictions")
    if recorded != expected:
        return [f"recognizer metadata_contradictions do not match source metadata: recorded={recorded} recomputed={expected}"]
    return []


def _check_recognizer_provenance_coverage(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    manifest, manifest_issues = _read_recognizer_manifest_source(eval_run.get("manifest_file"))
    if manifest_issues:
        return manifest_issues
    rows = _tsv_rows(score_dir / "predictions.tsv")
    expected = {
        "missing_source_document": 0,
        "missing_page": 0,
        "missing_bbox": 0,
        "missing_claim_eligibility": 0,
        "missing_human_review_evidence": 0,
    }
    for row in rows:
        image_path = row.get("image_path") or ""
        label = {"image_path": image_path, "image_key": Path(image_path).name}
        metadata = _recognizer_metadata_for(label, manifest)
        if not _metadata_has_any(metadata, SOURCE_DOCUMENT_KEYS):
            expected["missing_source_document"] += 1
        if not _metadata_has_any(metadata, PAGE_KEYS):
            expected["missing_page"] += 1
        if not _metadata_has_any(metadata, BBOX_KEYS):
            expected["missing_bbox"] += 1
        if not any(key in metadata for key in CLAIM_ELIGIBLE_KEYS):
            expected["missing_claim_eligibility"] += 1
        if _recognizer_gt_status(metadata, "") == "human_verified" and not _metadata_has_any(metadata, HUMAN_REVIEW_EVIDENCE_KEYS):
            expected["missing_human_review_evidence"] += 1
    recorded = metrics.get("provenance_coverage")
    if recorded != expected:
        return [f"recognizer provenance_coverage does not match source metadata: recorded={recorded} recomputed={expected}"]
    return []


def _recognizer_eval_leakage_rows(score_dir: Path) -> list[dict[str, str]]:
    rows: list[dict[str, str]] = []
    for row in _tsv_rows(score_dir / "predictions.tsv"):
        image_sha256 = row.get("image_sha256") or ""
        text_sha256 = _audit_hash_text(row.get("gt_text") or "")
        rows.append(
            {
                "sample_id": row.get("sample_id") or "",
                "source_sample_id": row.get("source_sample_id") or row.get("sample_id") or "",
                "image_path": row.get("image_path") or "",
                "image_sha256": image_sha256,
                "text_sha256": text_sha256,
                "sample_sha256": _audit_sample_hash(image_sha256, text_sha256) if image_sha256 and text_sha256 else "",
            }
        )
    return rows


def _check_recognizer_leakage_report(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    train_paths, issues = _train_manifest_paths(eval_run)
    train_rows: list[dict[str, str]] = []
    for path in train_paths:
        rows, row_issues = _audit_manifest_leakage_rows(path, compute_missing_image_sha=False)
        train_rows.extend(rows)
        issues.extend(row_issues)
    if issues:
        return issues
    eval_rows = _recognizer_eval_leakage_rows(score_dir) if train_rows else []
    expected = {
        "train_manifests": [str(path) for path in train_paths],
        "checked": bool(train_rows),
        "train_rows": len(train_rows),
        "eval_rows": len(eval_rows),
        "overlaps": _leakage_overlaps(train_rows, eval_rows),
    }
    return _compare_leakage_report("recognizer", metrics.get("leakage"), expected)


def _check_recognizer_unmatched_artifact(score_dir: Path, eval_run: dict[str, Any]) -> list[str]:
    path = score_dir / "unmatched.tsv"
    if not path.exists():
        return []
    label_file = eval_run.get("label_file")
    prediction_file = eval_run.get("prediction_file")
    data_dir = eval_run.get("data_dir")
    if not isinstance(label_file, str) or not label_file:
        return ["eval-run.json missing label_file for unmatched.tsv audit"]
    if not isinstance(prediction_file, str) or not prediction_file:
        return ["eval-run.json missing prediction_file for unmatched.tsv audit"]
    if not isinstance(data_dir, str) or not data_dir:
        return ["eval-run.json missing data_dir for unmatched.tsv audit"]

    labels, label_issues = _read_recognizer_label_source(Path(label_file))
    predictions, prediction_issues = _read_recognizer_prediction_source(Path(prediction_file))
    issues = [*label_issues, *prediction_issues]
    if issues:
        return issues

    prediction_by_key = {row["image_key"]: row for row in predictions}
    label_keys = {row["image_key"] for row in labels}
    expected = [
        {
            "kind": "label_without_prediction",
            "image_key": row["image_key"],
            "image_path": row["image_path"],
            "image_sha256": _sha256_file(Path(data_dir) / row["image_path"]) if (Path(data_dir) / row["image_path"]).exists() else "",
            "text": row["text"],
            "prediction_score": "",
        }
        for row in labels
        if row["image_key"] not in prediction_by_key
    ]
    expected.extend(
        {
            "kind": "prediction_without_label",
            "image_key": row["image_key"],
            "image_path": row["image_path"],
            "image_sha256": "",
            "text": row["text"],
            "prediction_score": row["score"],
        }
        for row in predictions
        if row["image_key"] not in label_keys
    )
    fields = ["kind", "image_key", "image_path", "image_sha256", "text", "prediction_score"]
    recorded = [{field: row.get(field) or "" for field in fields} for row in _tsv_rows(path)]
    if recorded != expected:
        issues.append(
            "unmatched.tsv rows do not match recomputed label/prediction misses: "
            f"recorded={_short_rows(recorded)} recomputed={_short_rows(expected)}"
        )
    return issues


def _check_recognizer_match_count_metrics(metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    label_file = eval_run.get("label_file")
    prediction_file = eval_run.get("prediction_file")
    if not isinstance(label_file, str) or not label_file:
        return ["eval-run.json missing label_file for recognizer match-count audit"]
    if not isinstance(prediction_file, str) or not prediction_file:
        return ["eval-run.json missing prediction_file for recognizer match-count audit"]

    labels, label_issues = _read_recognizer_label_source(Path(label_file))
    predictions, prediction_issues = _read_recognizer_prediction_source(Path(prediction_file))
    issues = [*label_issues, *prediction_issues]
    if issues:
        return issues

    label_keys = {row["image_key"] for row in labels}
    prediction_keys = {row["image_key"] for row in predictions}
    matched = len(label_keys & prediction_keys)
    expected_counts = {
        "label_lines": len(labels),
        "n_lines": matched,
        "matched_lines": matched,
        "unmatched_labels": len(label_keys - prediction_keys),
        "unmatched_predictions": len(prediction_keys - label_keys),
    }
    for field, expected in expected_counts.items():
        recorded = metrics.get(field)
        if not _is_number(recorded):
            issues.append(f"metrics missing numeric field: {field}")
        elif float(recorded) != float(expected):
            issues.append(
                f"metrics {field} does not match recomputed recognizer source value: "
                f"recorded={recorded} recomputed={expected}"
            )

    expected_match_rate = matched / max(len(labels), 1)
    recorded_match_rate = metrics.get("prediction_match_rate")
    if not _is_number(recorded_match_rate):
        issues.append("metrics missing numeric field: prediction_match_rate")
    elif not _close(float(recorded_match_rate), expected_match_rate):
        issues.append(
            "metrics prediction_match_rate does not match recomputed recognizer source value: "
            f"recorded={recorded_match_rate} recomputed={expected_match_rate}"
        )
    return issues


def _check_recognizer_row_hashes(score_dir: Path, eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    data_dir = eval_run.get("data_dir")
    if not isinstance(data_dir, str) or not data_dir:
        return ["recognizer data_dir is missing for row hash verification"]
    for row_index, row in enumerate(_tsv_rows(score_dir / "predictions.tsv"), 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        image_path = row.get("image_path")
        expected = row.get("image_sha256")
        if not image_path:
            issues.append(f"predictions.tsv {sample_id} missing image_path")
            continue
        if not expected:
            issues.append(f"predictions.tsv {sample_id} missing image_sha256")
            continue
        path = Path(data_dir) / image_path
        if not path.exists():
            issues.append(f"predictions.tsv {sample_id} image path does not exist: {path}")
            continue
        actual = _sha256_file(path)
        if actual != expected:
            issues.append(f"predictions.tsv {sample_id} image_sha256 mismatch: recorded={expected} actual={actual}")
    return issues


def _detection_values(predicted_count: int, reference_count: int, matches: int) -> dict[str, float | int]:
    precision = matches / predicted_count if predicted_count else (1.0 if reference_count == 0 else 0.0)
    recall = matches / reference_count if reference_count else (1.0 if predicted_count == 0 else 0.0)
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
    return {
        "line_reference_count": reference_count,
        "line_prediction_count": predicted_count,
        "line_match_count": matches,
        "line_detection_precision": precision,
        "line_detection_recall": recall,
        "line_detection_f1": f1,
    }


def _audit_reference_payload(input_path: Path, metadata: dict[str, Any], manifest_dir: Path) -> tuple[dict[str, Any] | None, list[str]]:
    issues: list[str] = []
    explicit = metadata.get("reference_path")
    candidates: list[Path] = []
    if isinstance(explicit, str) and explicit:
        candidates.append(_resolve_audit_manifest_path(explicit, manifest_dir))
    candidates.extend([input_path.with_suffix(input_path.suffix + ".ref.json"), input_path.with_suffix(".ref.json")])
    for candidate in candidates:
        if not candidate.exists() or candidate.suffix.lower() != ".json":
            continue
        try:
            payload = json.loads(candidate.read_text(encoding="utf-8"))
        except json.JSONDecodeError as exc:
            issues.append(f"reference JSON is invalid for line-alignment audit: {candidate}: {exc}")
            return None, issues
        if not isinstance(payload, dict):
            issues.append(f"reference JSON must contain an object for line-alignment audit: {candidate}")
            return None, issues
        return payload, issues
    return None, issues


def _audit_reference_lines(payload: dict[str, Any] | None) -> list[dict[str, Any]]:
    if payload is None:
        return []
    candidates = payload.get("reading_order")
    if candidates is None:
        candidates = payload.get("lines")
    if not isinstance(candidates, list):
        return []
    rows: list[dict[str, Any]] = []
    for index, item in enumerate(candidates):
        if not isinstance(item, dict):
            continue
        raw_bbox = item.get("bbox")
        if raw_bbox is None:
            continue
        try:
            bbox = BBox.from_any(raw_bbox)
        except Exception:
            continue
        if bbox.w <= 0 or bbox.h <= 0:
            continue
        rows.append(
            {
                "line_id": str(item.get("id") or item.get("line_id") or f"ref-{index:04d}"),
                "text": str(item.get("text") or ""),
                "bbox": bbox,
                "page_index": int(item.get("page_index", 0)),
            }
        )
    return rows


def _audit_predicted_lines(document_path: Path) -> tuple[list[TextLine], list[str]]:
    try:
        payload = json.loads(document_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        return [], [f"document JSON is invalid for line-alignment audit: {document_path}: {exc}"]
    if not isinstance(payload, dict):
        return [], [f"document JSON must contain an object for line-alignment audit: {document_path}"]
    try:
        document = Document.from_dict(payload)
    except Exception as exc:
        return [], [f"document JSON failed schema parse for line-alignment audit: {document_path}: {exc}"]
    predicted: list[TextLine] = []
    for page in document.pages:
        predicted.extend(page.text_lines)
    return predicted, []


def _codepoint_cer(prediction: str, reference: str) -> float:
    pred_nfc = _nfc(prediction)
    ref_nfc = _nfc(reference)
    return Levenshtein.distance(pred_nfc, ref_nfc) / max(len(ref_nfc), 1)


def _text_micro_counts(prediction: str, reference: str) -> tuple[int, int, int, int]:
    pred_nfc = _nfc(prediction)
    ref_nfc = _nfc(reference)
    pred_graph = _graphemes(pred_nfc)
    ref_graph = _graphemes(ref_nfc)
    return (
        Levenshtein.distance(pred_nfc, ref_nfc),
        len(ref_nfc),
        Levenshtein.distance(pred_graph, ref_graph),
        len(ref_graph),
    )


def _audit_document_text(document_path: Path) -> tuple[str | None, list[str]]:
    try:
        payload = json.loads(document_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        return None, [f"document JSON is invalid for text metric audit: {document_path}: {exc}"]
    if not isinstance(payload, dict):
        return None, [f"document JSON must contain an object for text metric audit: {document_path}"]
    try:
        document = Document.from_dict(payload)
    except Exception as exc:
        return None, [f"document JSON failed schema parse for text metric audit: {document_path}: {exc}"]
    return document.text, []


def _audit_document_source_path(document_path: Path) -> tuple[str | None, list[str]]:
    try:
        payload = json.loads(document_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        return None, [f"document JSON is invalid for source-path audit: {document_path}: {exc}"]
    if not isinstance(payload, dict):
        return None, [f"document JSON must contain an object for source-path audit: {document_path}"]
    try:
        document = Document.from_dict(payload)
    except Exception as exc:
        return None, [f"document JSON failed schema parse for source-path audit: {document_path}: {exc}"]
    return document.source_path, []


def _audit_reference_text(input_path: Path, metadata: dict[str, Any], manifest_dir: Path) -> tuple[str | None, list[str]]:
    explicit = metadata.get("reference_path")
    explicit_path = _resolve_audit_manifest_path(explicit, manifest_dir) if isinstance(explicit, str) and explicit else None
    try:
        reference = load_reference(input_path, explicit_path=explicit_path)
    except Exception as exc:
        return None, [f"reference failed to parse for text metric audit: {input_path}: {exc}"]
    if reference is None:
        return None, [f"reference is missing for text metric audit: {input_path}"]
    return reference.text, []


def _audit_reference_path(input_path: Path, metadata: dict[str, Any], manifest_dir: Path) -> Path | None:
    explicit = metadata.get("reference_path")
    candidates: list[Path] = []
    if isinstance(explicit, str) and explicit:
        candidates.append(_resolve_audit_manifest_path(explicit, manifest_dir))
    candidates.extend(
        [
            input_path.with_suffix(input_path.suffix + ".ref.json"),
            input_path.with_suffix(".ref.json"),
            input_path.with_suffix(input_path.suffix + ".ref.txt"),
            input_path.with_suffix(".ref.txt"),
        ]
    )
    for candidate in candidates:
        if candidate.exists():
            return candidate
    return None


def _text_sha256(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def _expected_page_reference_artifact_rows(eval_run: dict[str, Any]) -> tuple[list[dict[str, str]], list[str]]:
    issues: list[str] = []
    eval_manifest = eval_run.get("eval_manifest")
    if not isinstance(eval_manifest, str) or not eval_manifest:
        return [], ["page-eval-run.json missing eval_manifest for reference-artifacts.tsv audit"]
    manifest_path = Path(eval_manifest)
    manifest_rows, manifest_issues = _read_page_manifest_source(manifest_path)
    issues.extend(manifest_issues)
    manifest_dir = manifest_path.parent
    expected: list[dict[str, str]] = []
    for manifest_row in manifest_rows:
        sample_id = str(manifest_row["sample_id"])
        metadata = manifest_row["metadata"]
        input_path = _resolve_audit_manifest_path(str(manifest_row["image_path"]), manifest_dir)
        reference_path = _audit_reference_path(input_path, metadata, manifest_dir)
        if reference_path is None:
            continue
        try:
            reference = load_reference(input_path, explicit_path=reference_path)
        except Exception as exc:
            issues.append(f"reference failed to parse for reference-artifacts.tsv audit: {input_path}: {exc}")
            continue
        if reference is None:
            continue
        fields, field_issues = _audit_reference_fields(input_path, metadata, manifest_dir)
        issues.extend(field_issues)
        if field_issues:
            continue
        text = reference.text or ""
        claim_value = (reference.metadata or {}).get("claim_evidence_eligible")
        expected.append(
            {
                "sample_id": sample_id,
                "input_path": str(input_path),
                "reference_path": str(reference_path),
                "reference_sha256": _sha256_file(reference_path),
                "reference_fields": ";".join(fields),
                "reference_text_sha256": _text_sha256(text),
                "reference_status": str((reference.metadata or {}).get("reference_status") or ""),
                "reference_claim_eligible": str(claim_value) if claim_value is not None else "",
            }
        )
    return expected, issues


def _check_page_reference_artifacts(score_dir: Path, eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    recorded = _tsv_rows(score_dir / "reference-artifacts.tsv")
    expected, expected_issues = _expected_page_reference_artifact_rows(eval_run)
    issues.extend(expected_issues)
    if not recorded:
        return [*issues, "reference-artifacts.tsv has no scored reference rows"]
    recorded_by_id: dict[str, dict[str, str]] = {}
    for row_index, row in enumerate(recorded, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        if sample_id not in recorded_by_id:
            recorded_by_id[sample_id] = row
    expected_by_id = {row["sample_id"]: row for row in expected}
    missing = sorted(set(expected_by_id) - set(recorded_by_id))
    extra = sorted(set(recorded_by_id) - set(expected_by_id))
    if missing:
        issues.append(f"reference-artifacts.tsv missing scored reference rows: {missing[:10]}")
    if extra:
        issues.append(f"reference-artifacts.tsv has rows not backed by scored references: {extra[:10]}")
    issues.extend(_check_unique_field("reference-artifacts.tsv", recorded, "sample_id"))
    required = {
        "sample_id",
        "input_path",
        "reference_path",
        "reference_sha256",
        "reference_fields",
        "reference_text_sha256",
        "reference_status",
        "reference_claim_eligible",
    }
    for row_index, row in enumerate(recorded, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        missing_fields = sorted(required - set(row))
        if missing_fields:
            issues.append(f"reference-artifacts.tsv {sample_id} missing columns: {missing_fields}")
            continue
        expected_row = expected_by_id.get(sample_id)
        if expected_row is None:
            continue
        for field in ("input_path", "reference_path"):
            if not _same_path(row.get(field), Path(expected_row[field])):
                issues.append(
                    f"reference-artifacts.tsv {sample_id} {field} does not match reference source: "
                    f"recorded={row.get(field) or ''} recomputed={expected_row[field]}"
                )
        for field in ("reference_sha256", "reference_fields", "reference_text_sha256", "reference_status", "reference_claim_eligible"):
            if (row.get(field) or "") != expected_row[field]:
                issues.append(
                    f"reference-artifacts.tsv {sample_id} {field} does not match reference source: "
                    f"recorded={row.get(field) or ''} recomputed={expected_row[field]}"
                )
    return issues


def _page_pack_content_digest(metric_rows: list[dict[str, str]], reference_rows: list[dict[str, str]]) -> str:
    references_by_id = {row["sample_id"]: row for row in reference_rows}
    canonical_rows: list[dict[str, Any]] = []
    for row in metric_rows:
        reference = references_by_id.get(row["sample_id"], {})
        canonical_rows.append(
            {
                "sample_id": row.get("sample_id") or "",
                "input_sha256": row.get("input_sha256") or "",
                "reference_sha256": reference.get("reference_sha256") or "",
                "reference_text_sha256": reference.get("reference_text_sha256") or "",
                "language": row.get("language") or "",
                "script": row.get("script") or "",
                "domain": row.get("domain") or "",
                "gt_status": row.get("gt_status") or "",
                "split": row.get("split") or "",
                "claim_eligible": _bool_text(row.get("claim_eligible") or ""),
                "source_document": row.get("source_document") or "",
                "source_page": row.get("source_page") or "",
                "source_bbox": row.get("source_bbox") or "",
                "reference_fields": reference.get("reference_fields") or row.get("reference_fields") or "",
                "reference_status": reference.get("reference_status") or "",
                "reference_claim_eligible": reference.get("reference_claim_eligible") or "",
            }
        )
    payload = "\n".join(
        json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
        for row in sorted(canonical_rows, key=lambda item: item["sample_id"])
    )
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def _check_page_pack_content_digest(eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    metric_rows, metric_issues = _expected_page_metric_identity_rows(eval_run)
    reference_rows, reference_issues = _expected_page_reference_artifact_rows(eval_run)
    issues = [*metric_issues, *reference_issues]
    if issues:
        return issues
    expected = _page_pack_content_digest(metric_rows, reference_rows)
    for label, payload in (("page-eval-run.json", eval_run), ("metrics.json", metrics)):
        recorded = payload.get("pack_content_sha256")
        if recorded != expected:
            issues.append(f"{label} pack_content_sha256 mismatch: recorded={recorded!r} recomputed={expected}")
    summary, summary_issues = _read_summary_for_audit(eval_run, "page", "pack content digest audit")
    issues.extend(summary_issues)
    if summary:
        summary_digest = _summary_pack_content_sha256(summary)
        if not summary_digest:
            issues.append("page summary missing pack_content_sha256")
        elif summary_digest != expected:
            issues.append(f"page summary pack_content_sha256 mismatch: recorded={summary_digest} recomputed={expected}")
    return issues


def _check_page_text_pairs_artifact(score_dir: Path, eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    page_rows = _csv_rows(score_dir / "page-metrics.csv")
    text_rows = _tsv_rows(score_dir / "text-pairs.tsv")
    if not page_rows:
        return ["page-metrics.csv has no scored rows for text-pairs.tsv audit"]
    if not text_rows:
        return ["text-pairs.tsv has no scored rows"]
    page_rows_by_id = {row.get("sample_id") or "": row for row in page_rows}
    text_rows_by_id = {row.get("sample_id") or "": row for row in text_rows}
    missing = sorted(set(page_rows_by_id) - set(text_rows_by_id))
    extra = sorted(set(text_rows_by_id) - set(page_rows_by_id))
    if missing:
        issues.append(f"text-pairs.tsv missing scored page rows: {missing[:10]}")
    if extra:
        issues.append(f"text-pairs.tsv has rows not present in page-metrics.csv: {extra[:10]}")
    issues.extend(_check_unique_field("text-pairs.tsv", text_rows, "sample_id"))

    manifest_rows_by_id: dict[str, dict[str, Any]] = {}
    manifest_dir = Path("")
    eval_manifest = eval_run.get("eval_manifest")
    if isinstance(eval_manifest, str) and eval_manifest:
        manifest_path = Path(eval_manifest)
        manifest_dir = manifest_path.parent
        manifest_rows, manifest_issues = _read_page_manifest_source(manifest_path)
        issues.extend(manifest_issues)
        manifest_rows_by_id = {str(row["sample_id"]): row for row in manifest_rows}
    else:
        issues.append("page-eval-run.json missing eval_manifest for text-pairs.tsv audit")

    required = {
        "sample_id",
        "input_path",
        "document_path",
        "prediction_text_sha256",
        "reference_text_sha256",
        "prediction_text",
        "reference_text",
        "text_codepoint_edits",
        "text_codepoint_ref_len",
        "text_grapheme_edits",
        "text_grapheme_ref_len",
        "text_exact",
    }
    for row_index, row in enumerate(text_rows, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        missing_fields = sorted(required - set(row))
        if missing_fields:
            issues.append(f"text-pairs.tsv {sample_id} missing columns: {missing_fields}")
            continue
        prediction_text = row.get("prediction_text") or ""
        reference_text = row.get("reference_text") or ""
        if row.get("prediction_text_sha256") != _text_sha256(prediction_text):
            issues.append(f"text-pairs.tsv {sample_id} prediction_text_sha256 mismatch")
        if row.get("reference_text_sha256") != _text_sha256(reference_text):
            issues.append(f"text-pairs.tsv {sample_id} reference_text_sha256 mismatch")
        cp_edits = _int_text(row.get("text_codepoint_edits", ""), "text_codepoint_edits", row_index, issues)
        cp_len = _int_text(row.get("text_codepoint_ref_len", ""), "text_codepoint_ref_len", row_index, issues)
        gr_edits = _int_text(row.get("text_grapheme_edits", ""), "text_grapheme_edits", row_index, issues)
        gr_len = _int_text(row.get("text_grapheme_ref_len", ""), "text_grapheme_ref_len", row_index, issues)
        exact = _bool_text(row.get("text_exact", ""))
        if exact is None:
            issues.append(f"text-pairs.tsv {sample_id} text_exact is not boolean-like: {row.get('text_exact')!r}")
        expected_counts = _text_micro_counts(prediction_text, reference_text)
        for field, recorded, expected in (
            ("text_codepoint_edits", cp_edits, expected_counts[0]),
            ("text_codepoint_ref_len", cp_len, expected_counts[1]),
            ("text_grapheme_edits", gr_edits, expected_counts[2]),
            ("text_grapheme_ref_len", gr_len, expected_counts[3]),
        ):
            if recorded is not None and recorded != expected:
                issues.append(f"text-pairs.tsv {sample_id} {field} mismatch: recorded={recorded} recomputed={expected}")
        expected_exact = _nfc(prediction_text) == _nfc(reference_text)
        if exact is not None and exact != expected_exact:
            issues.append(f"text-pairs.tsv {sample_id} text_exact mismatch: recorded={exact} recomputed={expected_exact}")

        page_row = page_rows_by_id.get(sample_id)
        if page_row is not None:
            for field in ("input_path", "document_path", "text_codepoint_edits", "text_codepoint_ref_len", "text_grapheme_edits", "text_grapheme_ref_len", "text_exact"):
                if str(row.get(field) or "") != str(page_row.get(field) or ""):
                    issues.append(
                        f"text-pairs.tsv {sample_id} {field} does not match page-metrics.csv: "
                        f"recorded={row.get(field)!r} page_metrics={page_row.get(field)!r}"
                    )

        manifest_row = manifest_rows_by_id.get(sample_id)
        if manifest_row is None:
            issues.append(f"text-pairs.tsv {sample_id} missing manifest row for source text audit")
            continue
        document_path = Path(row.get("document_path") or "")
        input_path = _resolve_audit_manifest_path(str(manifest_row["image_path"]), manifest_dir)
        document_text, document_issues = _audit_document_text(document_path)
        reference_source_text, reference_issues = _audit_reference_text(input_path, manifest_row["metadata"], manifest_dir)
        issues.extend(document_issues)
        issues.extend(reference_issues)
        if not document_issues and document_text is not None and prediction_text != document_text:
            issues.append(f"text-pairs.tsv {sample_id} prediction_text does not match document JSON text")
        if not reference_issues and reference_source_text is not None and reference_text != reference_source_text:
            issues.append(f"text-pairs.tsv {sample_id} reference_text does not match reference source text")
    return issues


def _page_confusions_from_text_pairs(score_dir: Path, limit: int = 200) -> dict[str, int]:
    counts: dict[str, int] = {}
    for row in _tsv_rows(score_dir / "text-pairs.tsv"):
        prediction = _nfc(row.get("prediction_text") or "")
        reference = _nfc(row.get("reference_text") or "")
        for opcode in Levenshtein.opcodes(prediction, reference):
            tag, i1, i2, j1, j2 = opcode
            if tag == "equal":
                continue
            left = prediction[i1:i2] or "<eps>"
            right = reference[j1:j2] or "<eps>"
            key = f"{left}->{right}"
            counts[key] = counts.get(key, 0) + 1
    return dict(sorted(counts.items(), key=lambda item: item[1], reverse=True)[:limit])


def _check_page_confusions(score_dir: Path) -> list[str]:
    path = score_dir / "confusions.json"
    if not path.exists():
        return []
    try:
        payload = _read_json(path)
    except (FileNotFoundError, ValueError) as exc:
        return [str(exc)]
    if not isinstance(payload, dict):
        return ["confusions.json must contain a JSON object"]

    issues: list[str] = []
    recorded: dict[str, int] = {}
    for key, value in payload.items():
        if isinstance(value, bool) or not isinstance(value, int):
            issues.append(f"confusions.json {key!r} count is not an integer: {value!r}")
            continue
        recorded[str(key)] = value
    expected = _page_confusions_from_text_pairs(score_dir)
    if recorded != expected:
        issues.append(f"confusions.json does not match recomputed text-pairs.tsv confusions: recorded={recorded} recomputed={expected}")
    return issues


def _expected_line_alignment_rows(sample_id: str, reference_lines: list[dict[str, Any]], predicted_lines: list[TextLine], iou_threshold: float) -> list[dict[str, Any]]:
    unmatched_predicted = set(range(len(predicted_lines)))
    rows: list[dict[str, Any]] = []
    for reference in reference_lines:
        best_index: int | None = None
        best_iou = 0.0
        for predicted_index in sorted(unmatched_predicted):
            predicted = predicted_lines[predicted_index]
            if predicted.page_index != reference["page_index"]:
                continue
            overlap = bbox_iou(predicted.bbox, reference["bbox"])
            if overlap > best_iou:
                best_iou = overlap
                best_index = predicted_index
        if best_index is None or best_iou < iou_threshold:
            rows.append(
                {
                    "sample_id": sample_id,
                    "kind": "reference_unmatched",
                    "reference_line_id": reference["line_id"],
                    "predicted_line_id": "",
                    "reference_bbox": _bbox_text(reference["bbox"]),
                    "predicted_bbox": "",
                    "page_index": reference["page_index"],
                    "iou": best_iou,
                    "reference_text": reference["text"],
                    "predicted_text": "",
                    "text_cer_codepoint": 1.0 if reference["text"] else 0.0,
                }
            )
            continue
        predicted = predicted_lines[best_index]
        unmatched_predicted.remove(best_index)
        rows.append(
            {
                "sample_id": sample_id,
                "kind": "matched",
                "reference_line_id": reference["line_id"],
                "predicted_line_id": predicted.line_id or "",
                "reference_bbox": _bbox_text(reference["bbox"]),
                "predicted_bbox": _bbox_text(predicted.bbox),
                "page_index": reference["page_index"],
                "iou": best_iou,
                "reference_text": reference["text"],
                "predicted_text": predicted.text,
                "text_cer_codepoint": _codepoint_cer(predicted.text, reference["text"]),
            }
        )
    for predicted_index in sorted(unmatched_predicted):
        predicted = predicted_lines[predicted_index]
        rows.append(
            {
                "sample_id": sample_id,
                "kind": "prediction_unmatched",
                "reference_line_id": "",
                "predicted_line_id": predicted.line_id or "",
                "reference_bbox": "",
                "predicted_bbox": _bbox_text(predicted.bbox),
                "page_index": predicted.page_index,
                "iou": 0.0,
                "reference_text": "",
                "predicted_text": predicted.text,
                "text_cer_codepoint": 1.0 if predicted.text else 0.0,
            }
        )
    return rows


def _compare_line_alignment_rows(sample_id: str, recorded_rows: list[dict[str, str]], expected_rows: list[dict[str, Any]], issues: list[str]) -> None:
    if len(recorded_rows) != len(expected_rows):
        issues.append(f"line-alignment.csv {sample_id} row count mismatch: recorded={len(recorded_rows)} recomputed={len(expected_rows)}")
    comparable = min(len(recorded_rows), len(expected_rows))
    for index in range(comparable):
        recorded = recorded_rows[index]
        expected = expected_rows[index]
        row_label = f"line-alignment.csv {sample_id} row {index + 1}"
        for field in (
            "sample_id",
            "kind",
            "reference_line_id",
            "predicted_line_id",
            "reference_bbox",
            "predicted_bbox",
            "reference_text",
            "predicted_text",
        ):
            if (recorded.get(field) or "") != str(expected[field]):
                issues.append(f"{row_label} {field} mismatch")
        recorded_page = _int_text(recorded.get("page_index", ""), "page_index", index + 1, issues)
        if recorded_page is not None and recorded_page != int(expected["page_index"]):
            issues.append(f"{row_label} page_index mismatch: recorded={recorded_page} recomputed={expected['page_index']}")
        for field in ("iou", "text_cer_codepoint"):
            recorded_float = _float_text(recorded.get(field, ""), field, index + 1, issues)
            if recorded_float is not None and not _close(recorded_float, float(expected[field])):
                issues.append(f"{row_label} {field} mismatch: recorded={recorded_float} recomputed={expected[field]}")


def _check_page_line_alignment_recompute(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    page_rows = _csv_rows(score_dir / "page-metrics.csv")
    line_rows = _csv_rows(score_dir / "line-alignment.csv")
    if not page_rows:
        return ["page-metrics.csv has no scored rows"]
    if not line_rows:
        return ["line-alignment.csv has no alignment rows"]
    line_rows_by_sample: dict[str, list[dict[str, str]]] = {}
    for row in line_rows:
        sample_id = row.get("sample_id") or ""
        if sample_id:
            line_rows_by_sample.setdefault(sample_id, []).append(row)
    page_sample_ids = {row.get("sample_id") or "" for row in page_rows}
    extra_line_samples = sorted(set(line_rows_by_sample) - page_sample_ids)
    if extra_line_samples:
        issues.append(f"line-alignment.csv has samples not present in page-metrics.csv: {extra_line_samples[:10]}")
    iou_threshold = eval_run.get("line_iou_threshold")
    if not _is_number(iou_threshold):
        issues.append(f"page-eval-run.json line_iou_threshold is not numeric: {iou_threshold!r}")
        iou_threshold = 0.0
    manifest_rows_by_id: dict[str, dict[str, Any]] = {}
    eval_manifest = eval_run.get("eval_manifest")
    manifest_dir = Path("")
    if isinstance(eval_manifest, str) and eval_manifest:
        manifest_path = Path(eval_manifest)
        manifest_dir = manifest_path.parent
        manifest_rows, manifest_issues = _read_page_manifest_source(manifest_path)
        issues.extend(manifest_issues)
        manifest_rows_by_id = {str(row["sample_id"]): row for row in manifest_rows}
    else:
        issues.append("page-eval-run.json missing eval_manifest for line-alignment audit")
    metric_values: dict[str, list[float]] = {}
    for row_index, page_row in enumerate(page_rows, 1):
        sample_id = page_row.get("sample_id") or f"row {row_index}"
        sample_line_rows = line_rows_by_sample.get(sample_id, [])
        manifest_row = manifest_rows_by_id.get(sample_id)
        document_path_value = page_row.get("document_path")
        if manifest_row is None:
            issues.append(f"line-alignment.csv {sample_id} missing manifest row for recomputation")
        elif not document_path_value:
            issues.append(f"page-metrics.csv {sample_id} missing document_path for line-alignment recomputation")
        else:
            input_path = _resolve_audit_manifest_path(str(manifest_row["image_path"]), manifest_dir)
            reference_payload, reference_issues = _audit_reference_payload(input_path, manifest_row["metadata"], manifest_dir)
            issues.extend(reference_issues)
            predicted_lines, predicted_issues = _audit_predicted_lines(Path(document_path_value))
            issues.extend(predicted_issues)
            if not reference_issues and not predicted_issues:
                expected_rows = _expected_line_alignment_rows(
                    sample_id,
                    _audit_reference_lines(reference_payload),
                    predicted_lines,
                    float(iou_threshold),
                )
                _compare_line_alignment_rows(sample_id, sample_line_rows, expected_rows, issues)
        matched_rows = [row for row in sample_line_rows if row.get("kind") == "matched"]
        reference_count = sum(1 for row in sample_line_rows if row.get("kind") in {"matched", "reference_unmatched"})
        prediction_count = sum(1 for row in sample_line_rows if row.get("kind") in {"matched", "prediction_unmatched"})
        match_count = len(matched_rows)
        matched_ious: list[float] = []
        for line_index, line_row in enumerate(matched_rows, 1):
            parsed_iou = _float_text(line_row.get("iou", ""), "iou", line_index, issues)
            if parsed_iou is not None:
                matched_ious.append(parsed_iou)
        recomputed = _detection_values(prediction_count, reference_count, match_count)
        recomputed["line_mean_iou"] = sum(matched_ious) / len(matched_ious) if matched_ious else 0.0
        for field, expected in recomputed.items():
            if field not in page_row:
                issues.append(f"page-metrics.csv {sample_id} missing {field}")
                continue
            recorded = _float_text(page_row.get(field, ""), field, row_index, issues)
            if recorded is not None and not _close(recorded, float(expected)):
                issues.append(f"page-metrics.csv {sample_id} {field} mismatch: recorded={recorded} recomputed={expected}")
        for field, value in page_row.items():
            if field in {
                "sample_id",
                "input_path",
                "input_sha256",
                "document_path",
                "document_sha256",
                "language",
                "script",
                "domain",
                "gt_status",
                "split",
                "reference_fields",
                "text_cer_codepoint",
                "text_cer_grapheme",
            }:
                continue
            if value in (None, ""):
                continue
            try:
                metric_values.setdefault(field, []).append(float(value))
            except ValueError:
                continue
    metric_means = metrics.get("metric_means")
    if not isinstance(metric_means, dict):
        return issues
    for field, values in sorted(metric_values.items()):
        if field not in metric_means:
            continue
        expected = sum(values) / len(values)
        recorded = metric_means.get(field)
        if not _is_number(recorded) or not _close(float(recorded), expected):
            issues.append(f"metrics metric_means.{field} does not match page-metrics.csv mean: recorded={recorded} recomputed={expected}")
    return issues


def _check_page_text_metrics_recompute(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    page_rows = _csv_rows(score_dir / "page-metrics.csv")
    if not page_rows:
        return ["page-metrics.csv has no scored rows"]
    manifest_rows_by_id: dict[str, dict[str, Any]] = {}
    eval_manifest = eval_run.get("eval_manifest")
    manifest_dir = Path("")
    if isinstance(eval_manifest, str) and eval_manifest:
        manifest_path = Path(eval_manifest)
        manifest_dir = manifest_path.parent
        manifest_rows, manifest_issues = _read_page_manifest_source(manifest_path)
        issues.extend(manifest_issues)
        manifest_rows_by_id = {str(row["sample_id"]): row for row in manifest_rows}
    else:
        issues.append("page-eval-run.json missing eval_manifest for text metric audit")
    cp_edits_total = 0
    cp_len_total = 0
    gr_edits_total = 0
    gr_len_total = 0
    text_reference_pages = 0
    text_exact_pages = 0
    zero_length_text_references = 0
    for row_index, row in enumerate(page_rows, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        required = {
            "text_codepoint_edits",
            "text_codepoint_ref_len",
            "text_cer_codepoint",
            "text_grapheme_edits",
            "text_grapheme_ref_len",
            "text_cer_grapheme",
            "text_exact",
        }
        missing = sorted(required - set(row))
        if missing:
            issues.append(f"page-metrics.csv {sample_id} missing text metric columns: {missing}")
            continue
        cp_edits = _int_text(row.get("text_codepoint_edits", ""), "text_codepoint_edits", row_index, issues)
        cp_len = _int_text(row.get("text_codepoint_ref_len", ""), "text_codepoint_ref_len", row_index, issues)
        gr_edits = _int_text(row.get("text_grapheme_edits", ""), "text_grapheme_edits", row_index, issues)
        gr_len = _int_text(row.get("text_grapheme_ref_len", ""), "text_grapheme_ref_len", row_index, issues)
        cp_cer = _float_text(row.get("text_cer_codepoint", ""), "text_cer_codepoint", row_index, issues)
        gr_cer = _float_text(row.get("text_cer_grapheme", ""), "text_cer_grapheme", row_index, issues)
        recorded_exact = _bool_text(row.get("text_exact", ""))
        if recorded_exact is None:
            issues.append(f"page-metrics.csv {sample_id} text_exact is not boolean-like: {row.get('text_exact')!r}")
        if cp_edits is None or cp_len is None or gr_edits is None or gr_len is None:
            continue
        expected_counts = (cp_edits, cp_len, gr_edits, gr_len)
        expected_exact = False
        has_text_reference = "text" in {field for field in (row.get("reference_fields") or "").split(";") if field}
        manifest_row = manifest_rows_by_id.get(sample_id)
        document_path_value = row.get("document_path")
        if manifest_row is None:
            issues.append(f"page-metrics.csv {sample_id} missing manifest row for text metric recomputation")
        elif not document_path_value:
            issues.append(f"page-metrics.csv {sample_id} missing document_path for text metric recomputation")
        else:
            input_path = _resolve_audit_manifest_path(str(manifest_row["image_path"]), manifest_dir)
            document_text, document_issues = _audit_document_text(Path(document_path_value))
            reference_text, reference_issues = _audit_reference_text(input_path, manifest_row["metadata"], manifest_dir)
            issues.extend(document_issues)
            issues.extend(reference_issues)
            if not document_issues and not reference_issues:
                if reference_text is None:
                    expected_counts = (0, 0, 0, 0)
                    expected_exact = False
                    has_text_reference = False
                else:
                    expected_counts = _text_micro_counts(document_text or "", reference_text)
                    expected_exact = _nfc(document_text or "") == _nfc(reference_text)
                    has_text_reference = True
                    if len(_nfc(reference_text)) == 0:
                        zero_length_text_references += 1
                expected_cp_edits, expected_cp_len, expected_gr_edits, expected_gr_len = expected_counts
                for field, recorded, expected in (
                    ("text_codepoint_edits", cp_edits, expected_cp_edits),
                    ("text_codepoint_ref_len", cp_len, expected_cp_len),
                    ("text_grapheme_edits", gr_edits, expected_gr_edits),
                    ("text_grapheme_ref_len", gr_len, expected_gr_len),
                ):
                    if recorded != expected:
                        issues.append(f"page-metrics.csv {sample_id} {field} mismatch: recorded={recorded} recomputed={expected}")
        expected_cp_cer = expected_counts[0] / max(expected_counts[1], 1)
        expected_gr_cer = expected_counts[2] / max(expected_counts[3], 1)
        if cp_cer is not None and not _close(cp_cer, expected_cp_cer):
            issues.append(f"page-metrics.csv {sample_id} text_cer_codepoint mismatch: recorded={cp_cer} recomputed={expected_cp_cer}")
        if gr_cer is not None and not _close(gr_cer, expected_gr_cer):
            issues.append(f"page-metrics.csv {sample_id} text_cer_grapheme mismatch: recorded={gr_cer} recomputed={expected_gr_cer}")
        if recorded_exact is not None and recorded_exact != expected_exact:
            issues.append(f"page-metrics.csv {sample_id} text_exact mismatch: recorded={recorded_exact} recomputed={expected_exact}")
        cp_edits_total += expected_counts[0]
        cp_len_total += expected_counts[1]
        gr_edits_total += expected_counts[2]
        gr_len_total += expected_counts[3]
        if has_text_reference:
            text_reference_pages += 1
            text_exact_pages += int(expected_exact)
    expected_values = {
        "text_codepoint_edits": cp_edits_total,
        "text_codepoint_ref_len": cp_len_total,
        "text_grapheme_edits": gr_edits_total,
        "text_grapheme_ref_len": gr_len_total,
        "text_reference_pages": text_reference_pages,
        "text_exact_pages": text_exact_pages,
        "zero_length_text_references": zero_length_text_references,
    }
    for key, expected in expected_values.items():
        if metrics.get(key) != expected:
            issues.append(f"metrics {key} does not match page-metrics.csv sum: recorded={metrics.get(key)} recomputed={expected}")
    if zero_length_text_references:
        _claim_blocker(issues, eval_run, "page", "zero-length text references", "zero-length text references present:")
    expected_cp_cer = cp_edits_total / max(cp_len_total, 1)
    if not _is_number(metrics.get("text_cer_codepoint_micro")) or not _close(float(metrics["text_cer_codepoint_micro"]), expected_cp_cer):
        issues.append(
            "metrics text_cer_codepoint_micro does not match page-metrics.csv sum: "
            f"recorded={metrics.get('text_cer_codepoint_micro')} recomputed={expected_cp_cer}"
        )
    expected_gr_cer = gr_edits_total / max(gr_len_total, 1)
    if not _is_number(metrics.get("text_cer_grapheme_micro")) or not _close(float(metrics["text_cer_grapheme_micro"]), expected_gr_cer):
        issues.append(
            "metrics text_cer_grapheme_micro does not match page-metrics.csv sum: "
            f"recorded={metrics.get('text_cer_grapheme_micro')} recomputed={expected_gr_cer}"
        )
    expected_exact_accuracy = text_exact_pages / max(text_reference_pages, 1)
    if not _is_number(metrics.get("text_exact_accuracy")) or not _close(float(metrics["text_exact_accuracy"]), expected_exact_accuracy):
        issues.append(
            "metrics text_exact_accuracy does not match page-metrics.csv sum: "
            f"recorded={metrics.get('text_exact_accuracy')} recomputed={expected_exact_accuracy}"
        )
    return issues


def _page_uncertainty_units(rows: list[dict[str, str]]) -> tuple[list[dict[str, int]], list[str]]:
    issues: list[str] = []
    units: list[dict[str, int]] = []
    for row_index, row in enumerate(rows, 1):
        cp_edits = _int_text(row.get("text_codepoint_edits", ""), "text_codepoint_edits", row_index, issues)
        cp_len = _int_text(row.get("text_codepoint_ref_len", ""), "text_codepoint_ref_len", row_index, issues)
        gr_edits = _int_text(row.get("text_grapheme_edits", ""), "text_grapheme_edits", row_index, issues)
        gr_len = _int_text(row.get("text_grapheme_ref_len", ""), "text_grapheme_ref_len", row_index, issues)
        exact = _bool_text(row.get("text_exact", ""))
        if exact is None:
            issues.append(f"page-metrics.csv row {row_index} text_exact is not boolean-like: {row.get('text_exact')!r}")
        if cp_edits is None or cp_len is None or gr_edits is None or gr_len is None:
            continue
        units.append(
            {
                "codepoint_edits": cp_edits,
                "codepoint_ref_len": cp_len,
                "grapheme_edits": gr_edits,
                "grapheme_ref_len": gr_len,
                "exact": int(bool(exact)),
                "text_reference": int("text" in {field for field in (row.get("reference_fields") or "").split(";") if field}),
            }
        )
    return units, issues


def _check_page_uncertainty(score_dir: Path, metrics: dict[str, Any]) -> list[str]:
    rows = _csv_rows(score_dir / "page-metrics.csv")
    units, issues = _page_uncertainty_units(rows)
    expected = _expected_uncertainty(
        units,
        method="deterministic_page_bootstrap",
        metrics=("text_cer_codepoint_micro", "text_cer_grapheme_micro", "text_exact_accuracy"),
    )
    issues.extend(_check_uncertainty(metrics.get("uncertainty"), expected, "page"))
    for index, row in enumerate(metrics.get("slices") if isinstance(metrics.get("slices"), list) else [], 1):
        if not isinstance(row, dict):
            continue
        slice_key = (
            str(row.get("language") or ""),
            str(row.get("script") or ""),
            str(row.get("domain") or ""),
            str(row.get("gt_status") or ""),
            str(row.get("split") or ""),
        )
        slice_rows = [
            source_row
            for source_row in rows
            if (
                str(source_row.get("language") or ""),
                str(source_row.get("script") or ""),
                str(source_row.get("domain") or ""),
                str(source_row.get("gt_status") or ""),
                str(source_row.get("split") or ""),
            )
            == slice_key
        ]
        slice_units, slice_issues = _page_uncertainty_units(slice_rows)
        issues.extend(slice_issues)
        expected_slice = _expected_uncertainty(
            slice_units,
            method="deterministic_page_bootstrap",
            metrics=("text_cer_codepoint_micro", "text_cer_grapheme_micro", "text_exact_accuracy"),
        )
        issues.extend(_check_uncertainty(row.get("uncertainty"), expected_slice, f"page slices[{index}]"))
    return issues


def _check_page_script_inventory(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    inventory_path = Path(eval_run["script_inventory_file"]) if isinstance(eval_run.get("script_inventory_file"), str) and eval_run.get("script_inventory_file") else None
    manifest_rows_by_id: dict[str, dict[str, Any]] = {}
    eval_manifest = eval_run.get("eval_manifest")
    manifest_dir = Path("")
    if isinstance(eval_manifest, str) and eval_manifest:
        manifest_path = Path(eval_manifest)
        manifest_dir = manifest_path.parent
        manifest_rows, manifest_issues = _read_page_manifest_source(manifest_path)
        issues.extend(manifest_issues)
        manifest_rows_by_id = {str(row["sample_id"]): row for row in manifest_rows}
    else:
        issues.append("page-eval-run.json missing eval_manifest for script inventory audit")
    reference_texts: list[str] = []
    for row in _csv_rows(score_dir / "page-metrics.csv"):
        sample_id = row.get("sample_id") or ""
        manifest_row = manifest_rows_by_id.get(sample_id)
        if manifest_row is None:
            issues.append(f"page-metrics.csv {sample_id or '(missing sample_id)'} missing manifest row for script inventory audit")
            continue
        input_path = _resolve_audit_manifest_path(str(manifest_row["image_path"]), manifest_dir)
        reference_text, reference_issues = _audit_reference_text(input_path, manifest_row["metadata"], manifest_dir)
        issues.extend(reference_issues)
        if reference_text is not None:
            reference_texts.append(reference_text)
    expected, inventory_issues = _expected_script_inventory(reference_texts, inventory_path)
    issues.extend(inventory_issues)
    issues.extend(_check_script_inventory(metrics.get("script_inventory"), expected, "page metrics"))
    issues.extend(_check_script_inventory(eval_run.get("script_inventory"), expected, "page eval-run"))
    return issues


def _check_page_dictionary_coverage(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    reference_texts = [row.get("reference_text") or "" for row in _tsv_rows(score_dir / "text-pairs.tsv")]
    expected = _expected_dictionary_coverage(reference_texts, eval_run.get("dictionary"))
    issues = _check_dictionary_coverage(metrics.get("dictionary_coverage"), expected, "page metrics")
    if expected.get("checked") and expected.get("missing_gt_codepoints"):
        _claim_blocker(issues, eval_run, "page", "GT codepoints missing from dictionary", "GT codepoints missing from dictionary:")
    return issues


def _expected_page_worst_rows(score_dir: Path) -> tuple[list[dict[str, Any]], list[str]]:
    issues: list[str] = []
    expected_rows: list[dict[str, Any]] = []
    reference_by_id = {row.get("sample_id") or "": row for row in _tsv_rows(score_dir / "reference-artifacts.tsv")}
    for row_index, row in enumerate(_csv_rows(score_dir / "page-metrics.csv"), 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        reference_row = reference_by_id.get(sample_id, {})
        cp_edits = _int_text(row.get("text_codepoint_edits", ""), "text_codepoint_edits", row_index, issues)
        cp_len = _int_text(row.get("text_codepoint_ref_len", ""), "text_codepoint_ref_len", row_index, issues)
        gr_edits = _int_text(row.get("text_grapheme_edits", ""), "text_grapheme_edits", row_index, issues)
        gr_len = _int_text(row.get("text_grapheme_ref_len", ""), "text_grapheme_ref_len", row_index, issues)
        if cp_edits is None or cp_len is None or gr_edits is None or gr_len is None:
            continue
        expected_rows.append(
            {
                "sample_id": sample_id,
                "input_path": row.get("input_path") or "",
                "input_sha256": row.get("input_sha256") or "",
                "input_uri": Path(row.get("input_path") or "").resolve().as_uri() if row.get("input_path") else "",
                "document_path": row.get("document_path") or "",
                "document_sha256": row.get("document_sha256") or "",
                "document_source_path": row.get("document_source_path") or "",
                "language": row.get("language") or "",
                "script": row.get("script") or "",
                "domain": row.get("domain") or "",
                "gt_status": row.get("gt_status") or "",
                "split": row.get("split") or "",
                "claim_eligible": row.get("claim_eligible") or "",
                "source_document": row.get("source_document") or "",
                "source_page": row.get("source_page") or "",
                "source_bbox": row.get("source_bbox") or "",
                "reference_path": reference_row.get("reference_path") or "",
                "reference_sha256": reference_row.get("reference_sha256") or "",
                "reference_status": reference_row.get("reference_status") or "",
                "reference_claim_eligible": reference_row.get("reference_claim_eligible") or "",
                "reference_fields": row.get("reference_fields") or "",
                "text_cer_codepoint": cp_edits / max(cp_len, 1),
                "text_cer_grapheme": gr_edits / max(gr_len, 1),
                "sort_key": gr_edits / max(gr_len, 1),
            }
        )
    expected_rows.sort(key=lambda row: row["sort_key"], reverse=True)
    return expected_rows, issues


def _check_page_worst_artifacts(score_dir: Path) -> list[str]:
    issues: list[str] = []
    expected_rows, row_issues = _expected_page_worst_rows(score_dir)
    issues.extend(row_issues)
    worst_rows = _csv_rows(score_dir / "worst-pages.csv")
    review_rows = _csv_rows(score_dir / "sample-review.csv")
    issues.extend(_check_sample_id_order("worst-pages.csv", expected_rows, worst_rows))
    issues.extend(_check_sample_id_order("sample-review.csv", expected_rows, review_rows))
    issues.extend(
        _check_review_csv_fields(
            "sample-review.csv",
            expected_rows,
            review_rows,
            ("input_path", "document_path", "document_source_path", "text_cer_grapheme", "text_cer_codepoint", "reference_fields"),
        )
    )
    issues.extend(
        _check_review_html_contents(
            score_dir,
            "page",
            expected_rows,
            review_rows,
            ("sample_id", "input_uri", "document_path", "document_source_path", "reference_fields"),
        )
    )
    expected_by_id = {str(row["sample_id"]): row for row in expected_rows}
    for row_index, row in enumerate(worst_rows, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        expected = expected_by_id.get(sample_id)
        if expected is None:
            continue
        for field in ("text_cer_grapheme", "text_cer_codepoint"):
            recorded = _float_text(row.get(field, ""), field, row_index, issues)
            if recorded is not None and not _close(recorded, float(expected[field])):
                issues.append(f"worst-pages.csv {sample_id} {field} mismatch: recorded={recorded} recomputed={expected[field]}")
        for field in (
            "input_path",
            "input_sha256",
            "document_path",
            "document_sha256",
            "document_source_path",
            "language",
            "script",
            "domain",
            "gt_status",
            "split",
            "claim_eligible",
            "source_document",
            "source_page",
            "source_bbox",
            "reference_path",
            "reference_sha256",
            "reference_status",
            "reference_claim_eligible",
            "reference_fields",
        ):
            if (row.get(field) or "") != str(expected[field]):
                issues.append(f"worst-pages.csv {sample_id} {field} mismatch")
    return issues


def _check_page_output_duplicates(score_dir: Path) -> list[str]:
    issues: list[str] = []
    page_rows = _csv_rows(score_dir / "page-metrics.csv")
    missing_rows = _csv_rows(score_dir / "missing.tsv")
    worst_rows = _csv_rows(score_dir / "worst-pages.csv")
    review_rows = _csv_rows(score_dir / "sample-review.csv")
    issues.extend(_check_unique_field("page-metrics.csv", page_rows, "sample_id"))
    issues.extend(_check_unique_field("page-metrics.csv", page_rows, "input_path"))
    issues.extend(_check_unique_field("page-metrics.csv", page_rows, "document_path"))
    issues.extend(_check_unique_key("missing.tsv", missing_rows, ("kind", "sample_id")))
    issues.extend(_check_unique_field("worst-pages.csv", worst_rows, "sample_id"))
    issues.extend(_check_unique_field("sample-review.csv", review_rows, "sample_id"))
    return issues


def _resolve_audit_manifest_path(path_value: str, manifest_dir: Path) -> Path:
    path = Path(path_value)
    if path.is_absolute() or path.exists():
        return path
    candidate = manifest_dir / path
    if candidate.exists():
        return candidate
    return path


def _page_document_candidates(sample_id: str, input_path: Path, documents_dir: Path) -> list[Path]:
    return [
        documents_dir / sample_id / "document.json",
        documents_dir / input_path.stem / "document.json",
        documents_dir / f"{sample_id}.json",
        documents_dir / f"{input_path.stem}.json",
    ]


def _page_reference_exists(input_path: Path, metadata: dict[str, Any], manifest_dir: Path) -> bool:
    explicit = metadata.get("reference_path")
    candidates: list[Path] = []
    if isinstance(explicit, str) and explicit:
        candidates.append(_resolve_audit_manifest_path(explicit, manifest_dir))
    candidates.extend(
        [
            input_path.with_suffix(input_path.suffix + ".ref.json"),
            input_path.with_suffix(".ref.json"),
            input_path.with_suffix(input_path.suffix + ".ref.txt"),
            input_path.with_suffix(".ref.txt"),
        ]
    )
    return any(candidate.exists() for candidate in candidates)


def _read_page_manifest_source(path: Path) -> tuple[list[dict[str, Any]], list[str]]:
    issues: list[str] = []
    rows: list[dict[str, Any]] = []
    seen: set[str] = set()
    seen_image_paths: set[str] = set()
    if not path.exists():
        return rows, [f"page eval manifest does not exist for missing.tsv audit: {path}"]
    with path.open("r", encoding="utf-8") as handle:
        for line_no, line in enumerate(handle, 1):
            line = line.strip()
            if not line:
                continue
            try:
                payload = json.loads(line)
            except json.JSONDecodeError as exc:
                issues.append(f"page eval manifest {path}:{line_no} invalid JSON: {exc}")
                continue
            if not isinstance(payload, dict):
                issues.append(f"page eval manifest {path}:{line_no} row is not an object")
                continue
            sample_id = str(payload.get("sample_id") or payload.get("id") or "")
            image_path = str(payload.get("image_path") or payload.get("image") or "")
            if not sample_id:
                issues.append(f"page eval manifest {path}:{line_no} missing sample_id")
                continue
            if not image_path:
                issues.append(f"page eval manifest {path}:{line_no} missing image_path")
                continue
            if sample_id in seen:
                issues.append(f"page eval manifest duplicate sample_id: {sample_id}")
            seen.add(sample_id)
            if image_path in seen_image_paths:
                issues.append(f"page eval manifest duplicate image_path: {image_path}")
            seen_image_paths.add(image_path)
            declared_sha256 = str(payload.get("sha256") or "")
            if declared_sha256:
                resolved_image = _resolve_audit_manifest_path(image_path, path.parent)
                if resolved_image.exists():
                    actual_sha256 = _sha256_file(resolved_image)
                    if actual_sha256 != declared_sha256:
                        issues.append(
                            f"page eval manifest {sample_id} sha256 mismatch: "
                            f"recorded={declared_sha256} actual={actual_sha256}"
                        )
            rows.append(
                {
                    "sample_id": sample_id,
                    "image_path": image_path,
                    "sha256": declared_sha256,
                    "split": str(payload.get("split") or ""),
                    "metadata": dict(payload.get("metadata") or {}),
                }
            )
    return rows, issues


def _audit_page_metadata_value(metadata: dict[str, Any], key: str, fallback: Any) -> str:
    value = metadata.get(key)
    if value in (None, ""):
        return str(fallback or "")
    return str(value)


def _audit_page_split(manifest_row: dict[str, Any]) -> str:
    metadata = manifest_row["metadata"]
    value = metadata.get("split") or metadata.get("split_role") or manifest_row.get("split") or ""
    return str(value)


def _audit_reference_fields(input_path: Path, metadata: dict[str, Any], manifest_dir: Path) -> tuple[list[str], list[str]]:
    issues: list[str] = []
    explicit = metadata.get("reference_path")
    explicit_path = _resolve_audit_manifest_path(explicit, manifest_dir) if isinstance(explicit, str) and explicit else None
    try:
        reference = load_reference(input_path, explicit_path=explicit_path)
    except Exception as exc:
        return [], [f"reference failed to parse for page-metrics identity audit: {input_path}: {exc}"]
    if reference is None:
        return [], [f"reference is missing for page-metrics identity audit: {input_path}"]
    fields: list[str] = []
    if reference.text is not None:
        fields.append("text")
    if reference.markdown is not None:
        fields.append("markdown")
    if reference.reading_order:
        fields.append("reading_order")
    if reference.tables:
        fields.append("tables")
    if reference.figures:
        fields.append("figures")
    payload, payload_issues = _audit_reference_payload(input_path, metadata, manifest_dir)
    issues.extend(payload_issues)
    if _audit_reference_lines(payload):
        fields.append("line_bboxes")
    return fields, issues


def _expected_page_metric_identity_rows(eval_run: dict[str, Any]) -> tuple[list[dict[str, str]], list[str]]:
    issues: list[str] = []
    eval_manifest = eval_run.get("eval_manifest")
    documents_dir_value = eval_run.get("documents_dir")
    if not isinstance(eval_manifest, str) or not eval_manifest:
        return [], ["page-eval-run.json missing eval_manifest for page-metrics identity audit"]
    if not isinstance(documents_dir_value, str) or not documents_dir_value:
        return [], ["page-eval-run.json missing documents_dir for page-metrics identity audit"]
    manifest_path = Path(eval_manifest)
    manifest_rows, manifest_issues = _read_page_manifest_source(manifest_path)
    issues.extend(manifest_issues)
    manifest_dir = manifest_path.parent
    documents_dir = Path(documents_dir_value)
    expected: list[dict[str, str]] = []
    for manifest_row in manifest_rows:
        sample_id = str(manifest_row["sample_id"])
        metadata = manifest_row["metadata"]
        input_path = _resolve_audit_manifest_path(str(manifest_row["image_path"]), manifest_dir)
        document_path = next(
            (candidate for candidate in _page_document_candidates(sample_id, input_path, documents_dir) if candidate.exists()),
            None,
        )
        if document_path is None:
            continue
        document_source_path, document_source_issues = _audit_document_source_path(document_path)
        issues.extend(document_source_issues)
        if document_source_issues:
            continue
        reference_fields, reference_issues = _audit_reference_fields(input_path, metadata, manifest_dir)
        issues.extend(reference_issues)
        if reference_issues:
            continue
        expected.append(
            {
                "sample_id": sample_id,
                "input_path": str(input_path),
                "input_sha256": _sha256_file(input_path) if input_path.exists() else "",
                "document_path": str(document_path),
                "document_source_path": document_source_path or "",
                "ocr_output_kind": str(eval_run.get("ocr_output_kind") or ""),
                "language": _audit_page_metadata_value(metadata, "language", eval_run.get("language_default")),
                "script": _audit_page_metadata_value(metadata, "script", eval_run.get("script_default")),
                "domain": _audit_page_metadata_value(metadata, "domain", eval_run.get("domain_default")),
                "gt_status": _audit_page_metadata_value(metadata, "gt_status", eval_run.get("gt_status_default")),
                "split": _audit_page_split(manifest_row),
                "claim_eligible": str(
                    _metadata_bool_value(metadata, CLAIM_ELIGIBLE_KEYS, eval_run.get("claim_eligible_default"))
                ),
                "source_document": _metadata_value_for_keys(metadata, SOURCE_DOCUMENT_KEYS),
                "source_page": _metadata_value_for_keys(metadata, PAGE_KEYS),
                "source_bbox": _metadata_value_for_keys(metadata, BBOX_KEYS),
                "reference_fields": ";".join(reference_fields),
            }
        )
    return expected, issues


def _check_page_metadata_contradictions(score_dir: Path, metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    eval_manifest = eval_run.get("eval_manifest")
    if not isinstance(eval_manifest, str) or not eval_manifest:
        return ["page-eval-run.json missing eval_manifest for metadata contradiction audit"]
    manifest_path = Path(eval_manifest)
    manifest_rows, issues = _read_page_manifest_source(manifest_path)
    if issues:
        return issues
    manifest_dir = manifest_path.parent
    page_rows = {row.get("sample_id") or "": row for row in _csv_rows(score_dir / "page-metrics.csv")}
    expected: list[str] = []
    for manifest_row in manifest_rows:
        sample_id = str(manifest_row["sample_id"])
        page_row = page_rows.get(sample_id)
        if page_row is None:
            continue
        metadata = manifest_row["metadata"]
        domain = page_row.get("domain") or ""
        gt_status = page_row.get("gt_status") or ""
        expected.extend(_metadata_contradictions_for(sample_id, metadata, domain, gt_status))
        input_path = _resolve_audit_manifest_path(str(manifest_row["image_path"]), manifest_dir)
        reference_payload, reference_issues = _audit_reference_payload(input_path, metadata, manifest_dir)
        issues.extend(reference_issues)
        if isinstance(reference_payload, dict) and isinstance(reference_payload.get("metadata"), dict):
            expected.extend(_metadata_contradictions_for(sample_id, reference_payload["metadata"], domain, gt_status))
    if issues:
        return issues
    recorded = metrics.get("metadata_contradictions")
    if recorded != expected:
        return [f"page metadata_contradictions do not match source metadata: recorded={recorded} recomputed={expected}"]
    return []


def _check_page_metadata_coverage(metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    eval_manifest = eval_run.get("eval_manifest")
    if not isinstance(eval_manifest, str) or not eval_manifest:
        return ["page-eval-run.json missing eval_manifest for metadata coverage audit"]
    manifest_rows, issues = _read_page_manifest_source(Path(eval_manifest))
    if issues:
        return issues

    def missing(key: str) -> int:
        return sum(1 for row in manifest_rows if row["metadata"].get(key) in (None, ""))

    def missing_any(keys: tuple[str, ...]) -> int:
        return sum(1 for row in manifest_rows if not _metadata_has_any(row["metadata"], keys))

    def missing_human_review_evidence() -> int:
        return sum(
            1
            for row in manifest_rows
            if row["metadata"].get("gt_status") == "human_verified"
            and not _metadata_has_any(row["metadata"], HUMAN_REVIEW_EVIDENCE_KEYS)
        )

    expected = {
        "missing_source_document": missing_any(SOURCE_DOCUMENT_KEYS),
        "missing_page": missing_any(PAGE_KEYS),
        "missing_bbox": missing_any(BBOX_KEYS),
        "missing_claim_eligibility": missing_any(CLAIM_ELIGIBLE_KEYS),
        "missing_human_review_evidence": missing_human_review_evidence(),
        "missing_language": missing("language"),
        "missing_script": missing("script"),
        "missing_domain": missing("domain"),
        "missing_gt_status": missing("gt_status"),
    }
    recorded = metrics.get("metadata_coverage")
    if recorded != expected:
        return [f"page metadata_coverage does not match eval manifest: recorded={recorded} recomputed={expected}"]
    return []


def _check_page_reference_coverage(score_dir: Path, metrics: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    rows = _csv_rows(score_dir / "page-metrics.csv")
    fields = ("text", "markdown", "reading_order", "tables", "figures", "line_bboxes")
    expected = dict.fromkeys(fields, 0)
    line_alignment_scored = 0
    for row_index, row in enumerate(rows, 1):
        reference_fields = {field for field in (row.get("reference_fields") or "").split(";") if field}
        for field in fields:
            if field in reference_fields:
                expected[field] += 1
        raw_reference_count = row.get("line_reference_count")
        if raw_reference_count in (None, ""):
            continue
        reference_count = _int_text(raw_reference_count, "line_reference_count", row_index, issues)
        if reference_count is not None and reference_count:
            line_alignment_scored += 1
    expected["line_alignment_scored"] = line_alignment_scored
    recorded = metrics.get("reference_coverage")
    if recorded != expected:
        issues.append(f"page reference_coverage does not match page-metrics.csv: recorded={recorded} recomputed={expected}")
    return issues


def _check_page_metric_identity_rows(score_dir: Path, eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    recorded_rows = _csv_rows(score_dir / "page-metrics.csv")
    expected_rows, expected_issues = _expected_page_metric_identity_rows(eval_run)
    issues.extend(expected_issues)
    recorded_by_id: dict[str, dict[str, str]] = {}
    for row_index, row in enumerate(recorded_rows, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        if sample_id not in recorded_by_id:
            recorded_by_id[sample_id] = row
    expected_by_id = {row["sample_id"]: row for row in expected_rows}
    missing = sorted(set(expected_by_id) - set(recorded_by_id))
    extra = sorted(set(recorded_by_id) - set(expected_by_id))
    if missing:
        issues.append(f"page-metrics.csv missing scored manifest rows: {missing[:10]}")
    if extra:
        issues.append(f"page-metrics.csv has rows not backed by scored manifest/reference/documents: {extra[:10]}")
    for sample_id in sorted(set(expected_by_id) & set(recorded_by_id)):
        expected = expected_by_id[sample_id]
        recorded = recorded_by_id[sample_id]
        for field in (
            "sample_id",
            "input_sha256",
            "language",
            "script",
            "domain",
            "gt_status",
            "split",
            "claim_eligible",
            "source_document",
            "source_page",
            "source_bbox",
            "reference_fields",
            "document_source_path",
        ):
            if (recorded.get(field) or "") != expected[field]:
                issues.append(
                    f"page-metrics.csv {sample_id} {field} does not match eval manifest/reference: "
                    f"recorded={recorded.get(field) or ''} recomputed={expected[field]}"
                )
        for field in ("input_path", "document_path"):
            recorded_path = recorded.get(field) or ""
            if not _same_path(recorded_path, Path(expected[field])):
                issues.append(
                    f"page-metrics.csv {sample_id} {field} does not match eval manifest/reference: "
                    f"recorded={recorded_path} recomputed={expected[field]}"
                )
    return issues


def _expected_page_document_source_path_mismatches(eval_run: dict[str, Any]) -> tuple[list[str], list[str]]:
    eval_manifest = eval_run.get("eval_manifest")
    documents_dir_value = eval_run.get("documents_dir")
    if not isinstance(eval_manifest, str) or not eval_manifest:
        return [], ["page-eval-run.json missing eval_manifest for document source-path audit"]
    if not isinstance(documents_dir_value, str) or not documents_dir_value:
        return [], ["page-eval-run.json missing documents_dir for document source-path audit"]
    manifest_path = Path(eval_manifest)
    manifest_rows, issues = _read_page_manifest_source(manifest_path)
    manifest_dir = manifest_path.parent
    documents_dir = Path(documents_dir_value)
    mismatches: list[str] = []
    for manifest_row in manifest_rows:
        sample_id = str(manifest_row["sample_id"])
        input_path = _resolve_audit_manifest_path(str(manifest_row["image_path"]), manifest_dir)
        document_path = next(
            (candidate for candidate in _page_document_candidates(sample_id, input_path, documents_dir) if candidate.exists()),
            None,
        )
        if document_path is None:
            continue
        document_source_path, document_source_issues = _audit_document_source_path(document_path)
        issues.extend(document_source_issues)
        if document_source_issues:
            continue
        if not _same_path(document_source_path or "", input_path):
            mismatches.append(
                f"{sample_id}: document.source_path {document_source_path!r} does not match eval input {str(input_path)!r}"
            )
    return mismatches, issues


def _check_page_document_source_path_mismatches(metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    expected, issues = _expected_page_document_source_path_mismatches(eval_run)
    if issues:
        return issues
    recorded = metrics.get("document_source_path_mismatches")
    if recorded != expected:
        issues.append(f"page document_source_path_mismatches do not match scored documents: recorded={recorded} recomputed={expected}")
    recorded_count = metrics.get("document_source_path_mismatch_count")
    if recorded_count != len(expected):
        issues.append(
            "page document_source_path_mismatch_count does not match scored documents: "
            f"recorded={recorded_count} recomputed={len(expected)}"
        )
    return issues


def _check_page_missing_artifact(score_dir: Path, eval_run: dict[str, Any]) -> list[str]:
    path = score_dir / "missing.tsv"
    if not path.exists():
        return []
    eval_manifest = eval_run.get("eval_manifest")
    documents_dir_value = eval_run.get("documents_dir")
    if not isinstance(eval_manifest, str) or not eval_manifest:
        return ["page-eval-run.json missing eval_manifest for missing.tsv audit"]
    if not isinstance(documents_dir_value, str) or not documents_dir_value:
        return ["page-eval-run.json missing documents_dir for missing.tsv audit"]

    manifest_path = Path(eval_manifest)
    manifest_rows, issues = _read_page_manifest_source(manifest_path)
    if issues:
        return issues
    manifest_dir = manifest_path.parent
    documents_dir = Path(documents_dir_value)
    expected: list[tuple[str, str]] = []
    for row in manifest_rows:
        sample_id = str(row["sample_id"])
        input_path = _resolve_audit_manifest_path(str(row["image_path"]), manifest_dir)
        document_exists = any(candidate.exists() for candidate in _page_document_candidates(sample_id, input_path, documents_dir))
        if not document_exists:
            expected.append(("missing_document", sample_id))
            continue
        if not _page_reference_exists(input_path, row["metadata"], manifest_dir):
            expected.append(("missing_reference", sample_id))
    recorded = [(row.get("kind") or "", row.get("sample_id") or "") for row in _csv_rows(path)]
    if recorded != expected:
        issues.append(
            "missing.tsv rows do not match recomputed manifest/document/reference misses: "
            f"recorded={_short_rows(recorded)} recomputed={_short_rows(expected)}"
        )
    return issues


def _check_page_manifest_count_metrics(metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    eval_manifest = eval_run.get("eval_manifest")
    documents_dir_value = eval_run.get("documents_dir")
    if not isinstance(eval_manifest, str) or not eval_manifest:
        return ["page-eval-run.json missing eval_manifest for manifest count audit"]
    if not isinstance(documents_dir_value, str) or not documents_dir_value:
        return ["page-eval-run.json missing documents_dir for manifest count audit"]
    manifest_path = Path(eval_manifest)
    manifest_rows, issues = _read_page_manifest_source(manifest_path)
    if issues:
        return issues
    manifest_dir = manifest_path.parent
    documents_dir = Path(documents_dir_value)
    missing_documents = 0
    missing_references = 0
    for row in manifest_rows:
        sample_id = str(row["sample_id"])
        input_path = _resolve_audit_manifest_path(str(row["image_path"]), manifest_dir)
        document_exists = any(candidate.exists() for candidate in _page_document_candidates(sample_id, input_path, documents_dir))
        if not document_exists:
            missing_documents += 1
            continue
        if not _page_reference_exists(input_path, row["metadata"], manifest_dir):
            missing_references += 1
    expected = {
        "manifest_samples": len(manifest_rows),
        "missing_documents": missing_documents,
        "missing_references": missing_references,
        "claim_eligible_rows": sum(
            1
            for row in manifest_rows
            if _metadata_bool_value(row["metadata"], CLAIM_ELIGIBLE_KEYS, eval_run.get("claim_eligible_default"))
        ),
    }
    expected["scored_pages"] = expected["manifest_samples"] - expected["missing_documents"] - expected["missing_references"]
    count_issues: list[str] = []
    for key, value in expected.items():
        if metrics.get(key) != value:
            count_issues.append(f"page metrics {key} does not match manifest/doc/reference sources: recorded={metrics.get(key)} recomputed={value}")
    return count_issues


def _check_page_leakage_report(metrics: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    eval_manifest = eval_run.get("eval_manifest")
    if not isinstance(eval_manifest, str) or not eval_manifest:
        return ["page-eval-run.json missing eval_manifest for leakage audit"]
    train_paths, issues = _train_manifest_paths(eval_run)
    eval_manifest_path = Path(eval_manifest)
    eval_rows, eval_issues = _audit_manifest_leakage_rows(
        eval_manifest_path,
        manifest_dir=eval_manifest_path.parent,
        compute_missing_image_sha=True,
    )
    issues.extend(eval_issues)
    train_rows: list[dict[str, str]] = []
    for path in train_paths:
        rows, row_issues = _audit_manifest_leakage_rows(path, manifest_dir=path.parent, compute_missing_image_sha=True)
        train_rows.extend(rows)
        issues.extend(row_issues)
    if issues:
        return issues
    expected = {
        "train_manifests": [str(path) for path in train_paths],
        "checked": bool(train_paths),
        "train_rows": len(train_rows),
        "eval_rows": len(eval_rows),
        "overlaps": _leakage_overlaps(train_rows, eval_rows),
    }
    return _compare_leakage_report("page", metrics.get("leakage"), expected)


def _check_page_row_hashes(score_dir: Path) -> list[str]:
    issues: list[str] = []
    page_rows = _csv_rows(score_dir / "page-metrics.csv")
    for row_index, row in enumerate(page_rows, 1):
        sample_id = row.get("sample_id") or f"row {row_index}"
        for path_field, hash_field, label in (
            ("input_path", "input_sha256", "input image"),
            ("document_path", "document_sha256", "document output"),
        ):
            path_value = row.get(path_field)
            expected = row.get(hash_field)
            if not path_value:
                issues.append(f"page-metrics.csv {sample_id} missing {path_field}")
                continue
            if not expected:
                issues.append(f"page-metrics.csv {sample_id} missing {hash_field}")
                continue
            path = Path(path_value)
            if not path.exists():
                issues.append(f"page-metrics.csv {sample_id} {label} path does not exist: {path_value}")
                continue
            actual = _sha256_file(path)
            if actual != expected:
                issues.append(f"page-metrics.csv {sample_id} {hash_field} mismatch: recorded={expected} actual={actual}")
    return issues


PAGE_SLICE_IDENTITY_FIELDS = {
    "sample_id",
    "input_path",
    "input_sha256",
    "document_path",
    "document_sha256",
    "document_source_path",
    "ocr_output_kind",
    "language",
    "script",
    "domain",
    "gt_status",
    "split",
    "claim_eligible",
    "source_document",
    "source_page",
    "source_bbox",
    "reference_fields",
}
PAGE_SLICE_TEXT_FIELDS = {
    "text_codepoint_edits",
    "text_codepoint_ref_len",
    "text_cer_codepoint",
    "text_grapheme_edits",
    "text_grapheme_ref_len",
    "text_cer_grapheme",
    "text_exact",
}


def _page_metric_mean_values(row: dict[str, str], row_index: int, issues: list[str]) -> dict[str, float]:
    values: dict[str, float] = {}
    excluded = PAGE_SLICE_IDENTITY_FIELDS | PAGE_SLICE_TEXT_FIELDS
    for field, value in row.items():
        if field in excluded or value in (None, ""):
            continue
        parsed = _float_text(value, field, row_index, issues)
        if parsed is not None:
            values[field] = parsed
    return values


def _check_page_slice_metrics(score_dir: Path, slices: Any) -> list[str]:
    issues: list[str] = []
    page_rows = _csv_rows(score_dir / "page-metrics.csv")
    if not page_rows:
        return ["page-metrics.csv has no scored rows"]
    if not isinstance(slices, list) or not slices:
        return ["page slice metrics are missing"]

    groups: dict[tuple[str, str, str, str, str], dict[str, Any]] = {}
    for row_index, row in enumerate(page_rows, 1):
        key = (
            row.get("language") or "",
            row.get("script") or "",
            row.get("domain") or "",
            row.get("gt_status") or "",
            row.get("split") or "",
        )
        bucket = groups.setdefault(
            key,
            {
                "scored_pages": 0,
                "text_codepoint_edits": 0,
                "text_codepoint_ref_len": 0,
                "text_grapheme_edits": 0,
                "text_grapheme_ref_len": 0,
                "text_reference_pages": 0,
                "text_exact_pages": 0,
                "metric_values": {},
            },
        )
        bucket["scored_pages"] += 1
        cp_edits = _int_text(row.get("text_codepoint_edits", ""), "text_codepoint_edits", row_index, issues)
        cp_len = _int_text(row.get("text_codepoint_ref_len", ""), "text_codepoint_ref_len", row_index, issues)
        gr_edits = _int_text(row.get("text_grapheme_edits", ""), "text_grapheme_edits", row_index, issues)
        gr_len = _int_text(row.get("text_grapheme_ref_len", ""), "text_grapheme_ref_len", row_index, issues)
        if cp_edits is not None:
            bucket["text_codepoint_edits"] += cp_edits
        if cp_len is not None:
            bucket["text_codepoint_ref_len"] += cp_len
        if gr_edits is not None:
            bucket["text_grapheme_edits"] += gr_edits
        if gr_len is not None:
            bucket["text_grapheme_ref_len"] += gr_len
        if "text" in {field for field in (row.get("reference_fields") or "").split(";") if field}:
            bucket["text_reference_pages"] += 1
            exact = _bool_text(row.get("text_exact", ""))
            if exact is None:
                issues.append(f"page-metrics.csv row {row_index} text_exact is not boolean-like: {row.get('text_exact')!r}")
            else:
                bucket["text_exact_pages"] += int(exact)
        metric_values: dict[str, list[float]] = bucket["metric_values"]
        for field, value in _page_metric_mean_values(row, row_index, issues).items():
            metric_values.setdefault(field, []).append(value)

    expected_by_key: dict[tuple[str, str, str, str, str], dict[str, Any]] = {}
    for key, bucket in groups.items():
        cp_edits = bucket["text_codepoint_edits"]
        cp_len = bucket["text_codepoint_ref_len"]
        gr_edits = bucket["text_grapheme_edits"]
        gr_len = bucket["text_grapheme_ref_len"]
        text_reference_pages = bucket["text_reference_pages"]
        text_exact_pages = bucket["text_exact_pages"]
        metric_values = bucket["metric_values"]
        expected_by_key[key] = {
            "scored_pages": bucket["scored_pages"],
            "text_codepoint_edits": cp_edits,
            "text_codepoint_ref_len": cp_len,
            "text_cer_codepoint_micro": cp_edits / max(cp_len, 1),
            "text_grapheme_edits": gr_edits,
            "text_grapheme_ref_len": gr_len,
            "text_cer_grapheme_micro": gr_edits / max(gr_len, 1),
            "text_reference_pages": text_reference_pages,
            "text_exact_pages": text_exact_pages,
            "text_exact_accuracy": text_exact_pages / max(text_reference_pages, 1),
            "metric_means": {
                field: sum(values) / len(values)
                for field, values in sorted(metric_values.items())
                if values
            },
        }

    recorded_by_key: dict[tuple[str, str, str, str, str], dict[str, Any]] = {}
    for index, row in enumerate(slices, 1):
        if not isinstance(row, dict):
            issues.append(f"page slices[{index}] is not an object")
            continue
        key = (
            str(row.get("language") or ""),
            str(row.get("script") or ""),
            str(row.get("domain") or ""),
            str(row.get("gt_status") or ""),
            str(row.get("split") or ""),
        )
        if key in recorded_by_key:
            issues.append(f"duplicate page slice metric for {key}")
        recorded_by_key[key] = row

    expected_keys = set(expected_by_key)
    recorded_keys = set(recorded_by_key)
    missing = sorted(expected_keys - recorded_keys)
    extra = sorted(recorded_keys - expected_keys)
    if missing:
        issues.append(f"page slice metrics missing slices: {missing[:10]}")
    if extra:
        issues.append(f"page slice metrics contain extra slices: {extra[:10]}")

    for key in sorted(expected_keys & recorded_keys):
        expected = expected_by_key[key]
        recorded = recorded_by_key[key]
        for field in (
            "scored_pages",
            "text_codepoint_edits",
            "text_codepoint_ref_len",
            "text_grapheme_edits",
            "text_grapheme_ref_len",
            "text_reference_pages",
            "text_exact_pages",
        ):
            if recorded.get(field) != expected[field]:
                issues.append(f"page slice {key} {field} mismatch: recorded={recorded.get(field)} recomputed={expected[field]}")
        for field in ("text_cer_codepoint_micro", "text_cer_grapheme_micro", "text_exact_accuracy"):
            value = recorded.get(field)
            if not _is_number(value) or not _close(float(value), float(expected[field])):
                issues.append(f"page slice {key} {field} mismatch: recorded={value} recomputed={expected[field]}")

        expected_means = expected["metric_means"]
        recorded_means = recorded.get("metric_means")
        if not isinstance(recorded_means, dict):
            issues.append(f"page slice {key} metric_means missing or not an object")
            continue
        missing_means = sorted(set(expected_means) - set(recorded_means))
        extra_means = sorted(set(recorded_means) - set(expected_means))
        if missing_means:
            issues.append(f"page slice {key} metric_means missing metrics: {missing_means[:10]}")
        if extra_means:
            issues.append(f"page slice {key} metric_means contain extra metrics: {extra_means[:10]}")
        for field in sorted(set(expected_means) & set(recorded_means)):
            value = recorded_means.get(field)
            expected_value = expected_means[field]
            if not _is_number(value) or not _close(float(value), expected_value):
                issues.append(f"page slice {key} metric_means.{field} mismatch: recorded={value} recomputed={expected_value}")
    return issues


def _normalizer_default_counts(payload: dict[str, Any]) -> dict[str, int]:
    raw_counts = payload.get("normalizer_counts")
    if not isinstance(raw_counts, dict):
        return {}
    defaults: dict[str, int] = {}
    for key in (
        "defaulted_language",
        "defaulted_script",
        "defaulted_domain",
        "defaulted_gt_status",
        "defaulted_split",
        "defaulted_claim_eligible",
    ):
        value = raw_counts.get(key, 0) or 0
        if isinstance(value, bool):
            continue
        try:
            count = int(value)
        except (TypeError, ValueError):
            defaults[key] = 1
            continue
        if count:
            defaults[key] = count
    return defaults


def _recognizer_summary_counts(eval_run: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
    summary, issues = _read_summary_for_audit(eval_run, "recognizer", "normalizer_counts audit")
    if issues or not summary:
        return {}, issues
    counts = summary.get("counts")
    if counts is None:
        return {}, []
    if not isinstance(counts, dict):
        summary_file = eval_run.get("summary_file")
        return {}, [f"recognizer summary counts is not an object: {summary_file}"]
    return counts, []


def _check_recognizer_summary_counts(eval_run: dict[str, Any], metrics: dict[str, Any]) -> list[str]:
    summary_counts, issues = _recognizer_summary_counts(eval_run)
    if issues or not summary_counts:
        return issues
    metric_counts = metrics.get("normalizer_counts")
    run_counts = eval_run.get("normalizer_counts")
    if metric_counts != summary_counts:
        issues.append("metrics.json normalizer_counts do not match recognizer summary counts")
    if run_counts != summary_counts:
        issues.append("eval-run.json normalizer_counts do not match recognizer summary counts")
    return issues


def _audit_recognizer(score_dir: Path) -> tuple[list[str], dict[str, Any], dict[str, Any]]:
    issues = _check_required_artifacts(score_dir, RECOGNIZER_ARTIFACTS)
    eval_run = _read_json(score_dir / "eval-run.json")
    metrics = _read_json(score_dir / "metrics.json")
    if not isinstance(eval_run, dict) or not isinstance(metrics, dict):
        return ["recognizer eval artifacts must contain JSON objects"], {}, {}
    issues.extend(_check_required_fields(eval_run, RECOGNIZER_REQUIRED_RUN_FIELDS, "eval-run.json"))
    issues.extend(_check_common(score_dir, eval_run, metrics))
    issues.extend(
        _check_eval_run_identity_lists(
            eval_run,
            _tsv_rows(score_dir / "predictions.tsv"),
            run_label="eval-run.json",
            row_label="predictions.tsv",
        )
    )
    issues.extend(_check_recognizer_metadata_contradictions(score_dir, metrics, eval_run))
    issues.extend(_check_recognizer_provenance_coverage(score_dir, metrics, eval_run))
    issues.extend(_check_recognizer_claim_blockers(eval_run, metrics))
    if eval_run.get("eval_mode") != "recognizer_oracle_crop":
        issues.append(f"unexpected recognizer eval_mode: {eval_run.get('eval_mode')}")
    for path_field, hash_field, label in (
        ("label_file", "label_file_sha256", "recognizer label file"),
        ("prediction_file", "prediction_file_sha256", "recognizer prediction file"),
        ("manifest_file", "manifest_file_sha256", "recognizer manifest file"),
        ("summary_file", "summary_file_sha256", "recognizer summary file"),
        ("script_inventory_file", "script_inventory_file_sha256", "recognizer script inventory file"),
        ("spotcheck_calibration_file", "spotcheck_calibration_file_sha256", "recognizer spotcheck calibration file"),
    ):
        issues.extend(_check_hash_field(eval_run, path_field, hash_field, label))
    issues.extend(_check_summary_metadata_consistency(eval_run, "recognizer"))
    issues.extend(_check_spotcheck_calibration_summary(eval_run, metrics, "recognizer"))
    issues.extend(_check_artifact_identity(eval_run, ("checkpoint", "config", "dictionary"), "recognizer"))
    issues.extend(_check_train_manifest_hashes(eval_run))
    issues.extend(_check_recognizer_leakage_report(score_dir, metrics, eval_run))
    issues.extend(_check_recognizer_output_duplicates(score_dir))
    issues.extend(_check_recognizer_prediction_source_rows(score_dir, eval_run))
    issues.extend(_check_recognizer_pack_content_digest(eval_run, metrics))
    issues.extend(_check_recognizer_row_claim_eligibility_blockers(score_dir, eval_run))
    issues.extend(_check_recognizer_unmatched_artifact(score_dir, eval_run))
    issues.extend(_check_recognizer_match_count_metrics(metrics, eval_run))
    issues.extend(_check_recognizer_row_hashes(score_dir, eval_run))
    issues.extend(_check_recognizer_predictions_recompute(score_dir, metrics, eval_run))
    issues.extend(
        _check_normalization_summary(
            metrics.get("normalization_summary"),
            _expected_recognizer_normalization_summary(score_dir),
            "recognizer metrics",
        )
    )
    issues.extend(_check_recognizer_uncertainty(score_dir, metrics))
    issues.extend(_check_recognizer_script_inventory(score_dir, metrics, eval_run))
    issues.extend(_check_recognizer_dictionary_coverage(score_dir, metrics, eval_run))
    issues.extend(_check_recognizer_confusions(score_dir))
    issues.extend(_check_recognizer_worst_artifacts(score_dir))
    issues.extend(_check_ratio(metrics, "codepoint_edits", "codepoint_ref_len", "cer_codepoint_micro"))
    issues.extend(_check_ratio(metrics, "grapheme_edits", "grapheme_ref_len", "cer_grapheme_micro"))
    if metrics.get("n_lines") != metrics.get("matched_lines"):
        issues.append("recognizer n_lines and matched_lines disagree")
    if metrics.get("matched_lines") != _artifact_rows(score_dir / "predictions.tsv"):
        issues.append("predictions.tsv row count does not match matched_lines")
    unmatched_expected = int(metrics.get("unmatched_labels", 0)) + int(metrics.get("unmatched_predictions", 0))
    if unmatched_expected != _artifact_rows(score_dir / "unmatched.tsv"):
        issues.append("unmatched.tsv row count does not match unmatched counts")
    coverage = metrics.get("provenance_coverage")
    if not isinstance(coverage, dict):
        issues.append("recognizer provenance coverage is missing")
    run_default_counts = _normalizer_default_counts(eval_run)
    metric_default_counts = _normalizer_default_counts(metrics)
    if run_default_counts:
        warnings = eval_run.get("warnings") if isinstance(eval_run.get("warnings"), list) else []
        for key in sorted(run_default_counts):
            expected = f"normalizer_{key}:"
            if not any(str(warning).startswith(expected) for warning in warnings):
                issues.append(f"recognizer normalizer default count missing warning: {key}")
        if eval_run.get("claim_safe") is True:
            issues.append("recognizer claim_safe is true despite normalizer-defaulted metadata")
    if run_default_counts != metric_default_counts:
        issues.append("recognizer normalizer_counts disagree between eval-run.json and metrics.json")
    issues.extend(_check_recognizer_summary_counts(eval_run, metrics))
    leakage = metrics.get("leakage")
    if not isinstance(leakage, dict) or not leakage.get("checked"):
        issues.append("recognizer train/dev leakage check was not run")
    return issues, eval_run, metrics


def _check_materialization_records(payload: dict[str, Any], materialize_dir: Path | None = None) -> list[str]:
    issues: list[str] = []
    mode = payload.get("mode")
    records = payload.get("records")
    if not isinstance(records, list) or not records:
        return ["materialization records are missing"]
    record_count = payload.get("record_count")
    if not isinstance(record_count, int) or isinstance(record_count, bool):
        issues.append(f"materialization record_count is missing or not an integer: {record_count!r}")
    elif record_count != len(records):
        issues.append(f"materialization record_count does not match records length: recorded={record_count} actual={len(records)}")
    for index, record in enumerate(records):
        if not isinstance(record, dict):
            issues.append(f"materialization records[{index}] is not an object")
            continue
        command = record.get("command")
        if not isinstance(command, list) or not command or not all(isinstance(part, str) and part for part in command):
            issues.append(f"materialization records[{index}] command is missing or invalid")
        else:
            command_template = payload.get("command_template")
            if isinstance(command_template, str) and command_template.strip() and materialize_dir is not None:
                values: dict[str, str] | None = None
                if mode == "recognizer":
                    label_file = payload.get("label_file")
                    data_dir = payload.get("data_dir")
                    prediction_file = payload.get("prediction_file")
                    if all(isinstance(value, str) and value for value in (label_file, data_dir, prediction_file)):
                        values = {
                            "label_file": str(label_file),
                            "data_dir": str(data_dir),
                            "prediction_file": str(prediction_file),
                            "out_dir": str(materialize_dir),
                        }
                    else:
                        issues.append(f"materialization records[{index}] missing recognizer fields required to replay command_template")
                elif mode == "page":
                    output_path = record.get("output_path")
                    input_path = record.get("input_path")
                    sample_id = record.get("sample_id")
                    documents_dir = payload.get("documents_dir")
                    if all(isinstance(value, str) and value for value in (output_path, input_path, sample_id, documents_dir)):
                        values = {
                            "input_path": str(input_path),
                            "sample_id": str(sample_id),
                            "output_dir": str(Path(str(output_path)).parent),
                            "document_json": str(output_path),
                            "documents_dir": str(documents_dir),
                            "out_dir": str(materialize_dir),
                        }
                    else:
                        issues.append(f"materialization records[{index}] missing page fields required to replay command_template")
                if values is not None:
                    try:
                        expected_command = shlex.split(command_template.format(**values))
                    except (KeyError, ValueError) as exc:
                        issues.append(f"materialization records[{index}] command_template could not be replayed: {exc}")
                    else:
                        if command != expected_command:
                            issues.append(f"materialization records[{index}] command does not match materialization command_template")
        for log_field in ("stdout_path", "stderr_path"):
            log_path = record.get(log_field)
            sha_field = log_field.replace("_path", "_sha256")
            log_sha256 = record.get(sha_field)
            if not isinstance(log_path, str) or not log_path:
                issues.append(f"materialization records[{index}] missing {log_field}")
            elif not Path(log_path).exists():
                issues.append(f"materialization records[{index}] {log_field} does not exist: {log_path}")
            elif isinstance(log_sha256, str) and log_sha256:
                actual_log_sha256 = _sha256_file(Path(log_path))
                if actual_log_sha256 != log_sha256:
                    issues.append(
                        f"materialization records[{index}] {sha_field} mismatch: "
                        f"recorded={log_sha256} actual={actual_log_sha256}"
                    )
            else:
                issues.append(f"materialization records[{index}] missing {sha_field}")
        output_path = record.get("output_path")
        output_sha256 = record.get("output_sha256")
        returncode = record.get("returncode")
        if returncode != 0:
            issues.append(f"materialization records[{index}] returncode is not zero: {returncode}")
        if not isinstance(output_path, str) or not output_path:
            issues.append(f"materialization records[{index}] missing output_path")
            continue
        if not isinstance(output_sha256, str) or not output_sha256:
            issues.append(f"materialization records[{index}] missing output_sha256")
            continue
        path = Path(output_path)
        if not path.exists():
            issues.append(f"materialization records[{index}] output_path does not exist: {output_path}")
            continue
        actual = _sha256_file(path)
        if actual != output_sha256:
            issues.append(f"materialization records[{index}] output_sha256 mismatch: recorded={output_sha256} actual={actual}")
        if mode == "page":
            input_path = record.get("input_path")
            input_sha256 = record.get("input_sha256")
            if not isinstance(input_path, str) or not input_path:
                issues.append(f"materialization records[{index}] missing input_path for page mode")
                continue
            if not isinstance(input_sha256, str) or not input_sha256:
                issues.append(f"materialization records[{index}] missing input_sha256 for page mode")
                continue
            source_path = Path(input_path)
            if not source_path.exists():
                issues.append(f"materialization records[{index}] input_path does not exist: {input_path}")
                continue
            actual_input_sha256 = _sha256_file(source_path)
            if actual_input_sha256 != input_sha256:
                issues.append(
                    f"materialization records[{index}] input_sha256 mismatch: "
                    f"recorded={input_sha256} actual={actual_input_sha256}"
                )
    return issues


def _check_materialization_provenance(payload: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    issues.extend(_check_timestamp(payload, "created_at", "materialization run"))
    for field in ("mode", "system_name", "command_template", "invocation"):
        value = payload.get(field)
        if not isinstance(value, str) or not value:
            issues.append(f"materialization missing required field: {field}")
    issues.extend(_check_machine_metadata(payload, "materialization"))
    return issues


def _same_path(left: Any, right: Path) -> bool:
    if not isinstance(left, str) or not left:
        return False
    try:
        return Path(left).resolve() == right.resolve()
    except OSError:
        return False


def _is_relative_to(path: Path, parent: Path) -> bool:
    try:
        path.resolve().relative_to(parent.resolve())
    except ValueError:
        return False
    except OSError:
        return False
    return True


def _check_recipe_context_identity(recipe_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    root_value = recipe_run.get("root")
    recipe_file_value = recipe_run.get("recipe_file")
    if not isinstance(root_value, str) or not root_value:
        return ["recipe-run.json root is missing"]
    root_path = Path(root_value)
    if not root_path.exists() or not root_path.is_dir():
        issues.append(f"recipe-run.json root does not exist or is not a directory: {root_value}")
        return issues
    if not isinstance(recipe_file_value, str) or not recipe_file_value:
        return issues
    recipe_file_path = Path(recipe_file_value)
    if recipe_file_path.exists() and not _is_relative_to(recipe_file_path, root_path):
        issues.append("recipe-run.json recipe_file is not under declared root")
    return issues


def _check_recipe_output_lineage(run_dir: Path, recipe_run: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    outputs = recipe_run.get("outputs")
    materialization = recipe_run.get("materialization")
    if not isinstance(outputs, dict) or not isinstance(materialization, dict):
        return issues

    materialization_file = run_dir / "materialize" / "output-command-run.json"
    if materialization_file.exists():
        try:
            materialization_payload = _read_json(materialization_file)
        except (FileNotFoundError, ValueError) as exc:
            issues.append(str(exc))
        else:
            if materialization_payload != materialization:
                issues.append("materialize/output-command-run.json does not match recipe-run.json materialization")

    command_template = materialization.get("command_template")
    command_template_file = run_dir / "materialize" / "command-template.txt"
    if command_template_file.exists() and isinstance(command_template, str):
        if command_template_file.read_text(encoding="utf-8").strip() != command_template.strip():
            issues.append("materialize/command-template.txt does not match recorded materialization command_template")

    report_file = run_dir / "materialize" / "output-command-run.md"
    records = materialization.get("records")
    if report_file.exists() and isinstance(records, list):
        report_text = report_file.read_text(encoding="utf-8")
        expected_record_line = f"- records: {len(records)}"
        if expected_record_line not in report_text:
            issues.append(f"materialize/output-command-run.md missing or stale line: {expected_record_line}")
        for index, record in enumerate(records):
            if not isinstance(record, dict):
                continue
            output_path = record.get("output_path")
            output_sha256 = record.get("output_sha256")
            input_path = record.get("input_path")
            input_sha256 = record.get("input_sha256")
            sample_id = record.get("sample_id")
            if isinstance(output_path, str) and isinstance(output_sha256, str) and isinstance(sample_id, str):
                if isinstance(input_path, str) and isinstance(input_sha256, str):
                    expected_output_line = (
                        f"- {sample_id}: input `{input_path}` sha256={input_sha256}; "
                        f"output `{output_path}` sha256={output_sha256}"
                    )
                else:
                    expected_output_line = f"- {sample_id}: `{output_path}` sha256={output_sha256}"
                if expected_output_line not in report_text:
                    issues.append(f"materialize/output-command-run.md missing or stale output line for record {index}")
            stdout_path = record.get("stdout_path")
            stdout_sha256 = record.get("stdout_sha256")
            if isinstance(stdout_path, str) and isinstance(stdout_sha256, str):
                expected_stdout = f"stdout `{stdout_path}` sha256={stdout_sha256}"
                if expected_stdout not in report_text:
                    issues.append(f"materialize/output-command-run.md missing or stale stdout line for record {index}")
            stderr_path = record.get("stderr_path")
            stderr_sha256 = record.get("stderr_sha256")
            if isinstance(stderr_path, str) and isinstance(stderr_sha256, str):
                expected_stderr = f"stderr `{stderr_path}` sha256={stderr_sha256}"
                if expected_stderr not in report_text:
                    issues.append(f"materialize/output-command-run.md missing or stale stderr line for record {index}")

    if eval_run.get("eval_mode") == "page_level_ocr":
        documents_value = outputs.get("documents_dir")
        eval_documents_dir = eval_run.get("documents_dir")
        if isinstance(documents_value, str) and documents_value:
            if isinstance(eval_documents_dir, str) and eval_documents_dir and not _same_path(documents_value, Path(eval_documents_dir)):
                issues.append("recipe-run.json outputs.documents_dir does not match score eval-run documents_dir")
            if not Path(documents_value).exists():
                issues.append(f"recipe-run.json output path does not exist for documents_dir: {documents_value}")
            if isinstance(records, list):
                for index, record in enumerate(records):
                    if not isinstance(record, dict):
                        continue
                    output_path = record.get("output_path")
                    if isinstance(output_path, str) and output_path and not _is_relative_to(Path(output_path), Path(documents_value)):
                        issues.append(f"recipe-run.json materialization record {index} output_path is not under outputs.documents_dir")
        return issues

    prediction_value = outputs.get("prediction_file")
    eval_prediction = eval_run.get("prediction_file")
    eval_prediction_sha256 = eval_run.get("prediction_file_sha256")
    if isinstance(prediction_value, str) and prediction_value:
        prediction_path = Path(prediction_value)
        if isinstance(eval_prediction, str) and eval_prediction and not _same_path(prediction_value, Path(eval_prediction)):
            issues.append("recipe-run.json outputs.prediction_file does not match score eval-run prediction_file")
        if isinstance(eval_prediction_sha256, str) and eval_prediction_sha256 and prediction_path.exists():
            actual_sha256 = _sha256_file(prediction_path)
            if actual_sha256 != eval_prediction_sha256:
                issues.append(
                    "recipe-run.json outputs.prediction_file sha256 does not match score eval-run prediction_file_sha256: "
                    f"recorded={eval_prediction_sha256} actual={actual_sha256}"
                )

    if isinstance(records, list) and isinstance(prediction_value, str) and prediction_value:
        matching_records = [
            record
            for record in records
            if isinstance(record, dict) and _same_path(record.get("output_path"), Path(prediction_value))
        ]
        if not matching_records:
            issues.append("recipe-run.json materialization records do not include outputs.prediction_file")
        elif isinstance(eval_prediction_sha256, str) and eval_prediction_sha256:
            for index, record in enumerate(matching_records):
                if record.get("output_sha256") != eval_prediction_sha256:
                    issues.append(
                        "recipe-run.json materialization prediction output_sha256 does not match score eval-run "
                        f"prediction_file_sha256 for matching record {index}: "
                        f"recorded={record.get('output_sha256')} score={eval_prediction_sha256}"
                    )
    return issues


def _check_recipe_output_audit_consistency(run_dir: Path, recipe_run: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    if eval_run.get("eval_mode") != "page_level_ocr":
        return []
    output_audit = recipe_run.get("output_audit")
    if output_audit is None:
        return []
    issues: list[str] = []
    if not isinstance(output_audit, dict):
        return ["recipe-run.json output_audit is not an object"]
    outputs = recipe_run.get("outputs")
    if isinstance(outputs, dict):
        output_audit_dir = outputs.get("output_audit_dir")
        if not isinstance(output_audit_dir, str) or not output_audit_dir:
            issues.append("recipe-run.json outputs.output_audit_dir is missing for page output audit")
        elif not _same_path(output_audit_dir, run_dir / "output-audit"):
            issues.append("recipe-run.json outputs.output_audit_dir does not point at root output-audit")
        elif not Path(output_audit_dir).is_dir():
            issues.append(f"recipe-run.json output path does not exist for output_audit_dir: {output_audit_dir}")
    output_audit_path = run_dir / "output-audit" / "output-audit-run.json"
    try:
        output_audit_payload = _read_json(output_audit_path)
    except (FileNotFoundError, ValueError) as exc:
        issues.append(str(exc))
    else:
        if output_audit_payload != output_audit:
            issues.append("output-audit/output-audit-run.json does not match recipe-run.json output_audit")
    command_template = output_audit.get("command_template")
    command_template_file = run_dir / "output-audit" / "command-template.txt"
    if not isinstance(command_template, str) or not command_template.strip():
        issues.append("recipe-run.json output_audit command_template is missing")
    elif not command_template_file.is_file():
        issues.append("missing required artifact: output-audit/command-template.txt")
    else:
        if command_template_file.read_text(encoding="utf-8").strip() != command_template.strip():
            issues.append("output-audit/command-template.txt does not match recorded output_audit command_template")
    records = output_audit.get("records")
    record_count = output_audit.get("record_count")
    if not isinstance(records, list):
        issues.append("recipe-run.json output_audit records is not a list")
        records = []
    elif record_count != len(records):
        issues.append(f"recipe-run.json output_audit record_count mismatch: recorded={record_count} actual={len(records)}")
    if output_audit.get("passed") is not True:
        issues.append("recipe-run.json output_audit did not pass")
    for index, record in enumerate(records):
        if not isinstance(record, dict):
            issues.append(f"recipe-run.json output_audit records[{index}] is not an object")
            continue
        if record.get("returncode") != 0:
            issues.append(f"recipe-run.json output_audit records[{index}] returncode is not zero: {record.get('returncode')}")
        command = record.get("command")
        output_dir = record.get("output_dir")
        if not isinstance(command, list) or not command or not all(isinstance(part, str) and part for part in command):
            issues.append(f"recipe-run.json output_audit records[{index}] command is missing or invalid")
        elif isinstance(command_template, str) and command_template.strip():
            if not isinstance(output_dir, str) or not output_dir:
                issues.append(f"recipe-run.json output_audit records[{index}] missing output_dir")
            else:
                try:
                    expected_command = shlex.split(
                        command_template.format(
                            output_dir=output_dir,
                            documents_dir=str(run_dir / "documents"),
                            out_dir=str(run_dir / "output-audit"),
                        )
                    )
                except (KeyError, ValueError) as exc:
                    issues.append(f"recipe-run.json output_audit records[{index}] command_template could not be replayed: {exc}")
                else:
                    if command != expected_command:
                        issues.append(f"recipe-run.json output_audit records[{index}] command does not match output_audit command_template")
        for path_key in ("stdout_path", "stderr_path"):
            path_value = record.get(path_key)
            sha_key = path_key.replace("_path", "_sha256")
            sha_value = record.get(sha_key)
            if not isinstance(path_value, str) or not path_value:
                issues.append(f"recipe-run.json output_audit records[{index}] missing {path_key}")
            elif not Path(path_value).is_file():
                issues.append(f"recipe-run.json output_audit records[{index}] {path_key} does not exist: {path_value}")
            elif isinstance(sha_value, str) and sha_value:
                actual_log_sha256 = _sha256_file(Path(path_value))
                if actual_log_sha256 != sha_value:
                    issues.append(
                        f"recipe-run.json output_audit records[{index}] {sha_key} mismatch: "
                        f"recorded={sha_value} actual={actual_log_sha256}"
                    )
            else:
                issues.append(f"recipe-run.json output_audit records[{index}] missing {sha_key}")
        audit_json = record.get("audit_json")
        if not isinstance(audit_json, dict):
            issues.append(f"recipe-run.json output_audit records[{index}] missing audit_json artifact")
        else:
            audit_json_path = audit_json.get("path")
            audit_json_sha256 = audit_json.get("sha256")
            if not isinstance(audit_json_path, str) or not audit_json_path:
                issues.append(f"recipe-run.json output_audit records[{index}] audit_json missing path")
            elif not Path(audit_json_path).is_file():
                issues.append(f"recipe-run.json output_audit records[{index}] audit_json path does not exist: {audit_json_path}")
            elif isinstance(audit_json_sha256, str) and audit_json_sha256:
                actual_audit_json_sha256 = _sha256_file(Path(audit_json_path))
                if actual_audit_json_sha256 != audit_json_sha256:
                    issues.append(
                        f"recipe-run.json output_audit records[{index}] audit_json sha256 mismatch: "
                        f"recorded={audit_json_sha256} actual={actual_audit_json_sha256}"
                    )
            else:
                issues.append(f"recipe-run.json output_audit records[{index}] audit_json missing sha256")
        audit_markdown = record.get("audit_markdown")
        if audit_markdown is not None:
            if not isinstance(audit_markdown, dict):
                issues.append(f"recipe-run.json output_audit records[{index}] audit_markdown is not an object")
            else:
                audit_markdown_path = audit_markdown.get("path")
                audit_markdown_sha256 = audit_markdown.get("sha256")
                if not isinstance(audit_markdown_path, str) or not audit_markdown_path:
                    issues.append(f"recipe-run.json output_audit records[{index}] audit_markdown missing path")
                elif not Path(audit_markdown_path).is_file():
                    issues.append(f"recipe-run.json output_audit records[{index}] audit_markdown path does not exist: {audit_markdown_path}")
                elif isinstance(audit_markdown_sha256, str) and audit_markdown_sha256:
                    actual_audit_markdown_sha256 = _sha256_file(Path(audit_markdown_path))
                    if actual_audit_markdown_sha256 != audit_markdown_sha256:
                        issues.append(
                            f"recipe-run.json output_audit records[{index}] audit_markdown sha256 mismatch: "
                            f"recorded={audit_markdown_sha256} actual={actual_audit_markdown_sha256}"
                        )
                else:
                    issues.append(f"recipe-run.json output_audit records[{index}] audit_markdown missing sha256")
    report_path = run_dir / "output-audit" / "output-audit-run.md"
    if not report_path.is_file():
        issues.append("missing required artifact: output-audit/output-audit-run.md")
    else:
        report_text = report_path.read_text(encoding="utf-8")
        expected_record_line = f"- records: {len(records)}"
        if expected_record_line not in report_text:
            issues.append(f"output-audit/output-audit-run.md missing or stale line: {expected_record_line}")
        for index, record in enumerate(records):
            if not isinstance(record, dict):
                continue
            sample_id = record.get("sample_id")
            output_dir = record.get("output_dir")
            returncode = record.get("returncode")
            if isinstance(sample_id, str) and isinstance(output_dir, str):
                expected_output_line = f"- {sample_id}: returncode={returncode} output_dir=`{output_dir}`"
                if expected_output_line not in report_text:
                    issues.append(f"output-audit/output-audit-run.md missing or stale output line for record {index}")
            if isinstance(record.get("stdout_path"), str) and isinstance(record.get("stdout_sha256"), str):
                expected_stdout = f"stdout=`{record['stdout_path']}` sha256={record['stdout_sha256']}"
                if expected_stdout not in report_text:
                    issues.append(f"output-audit/output-audit-run.md missing or stale stdout line for record {index}")
            if isinstance(record.get("stderr_path"), str) and isinstance(record.get("stderr_sha256"), str):
                expected_stderr = f"stderr=`{record['stderr_path']}` sha256={record['stderr_sha256']}"
                if expected_stderr not in report_text:
                    issues.append(f"output-audit/output-audit-run.md missing or stale stderr line for record {index}")
            audit_json = record.get("audit_json")
            if isinstance(audit_json, dict) and isinstance(audit_json.get("path"), str) and isinstance(audit_json.get("sha256"), str):
                expected_audit_json = f"audit_json=`{audit_json['path']}` sha256={audit_json['sha256']}"
                if expected_audit_json not in report_text:
                    issues.append(f"output-audit/output-audit-run.md missing or stale audit JSON line for record {index}")
            audit_markdown = record.get("audit_markdown")
            if (
                isinstance(audit_markdown, dict)
                and isinstance(audit_markdown.get("path"), str)
                and isinstance(audit_markdown.get("sha256"), str)
            ):
                expected_audit_markdown = f"audit_markdown=`{audit_markdown['path']}` sha256={audit_markdown['sha256']}"
                if expected_audit_markdown not in report_text:
                    issues.append(f"output-audit/output-audit-run.md missing or stale audit Markdown line for record {index}")
    return issues


def _check_recipe_materialization_score_identity(recipe_run: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    materialization = recipe_run.get("materialization")
    if not isinstance(materialization, dict):
        return []
    issues: list[str] = []
    recipe_id = recipe_run.get("recipe_id")
    if isinstance(recipe_id, str) and recipe_id:
        system_name = materialization.get("system_name")
        if system_name != recipe_id:
            issues.append(f"recipe-run.json materialization system_name does not match recipe_id: recorded={system_name} recipe_id={recipe_id}")
    for field in ("model_name", "checkpoint", "config"):
        recorded = materialization.get(field)
        scored = eval_run.get(field)
        if recorded != scored:
            issues.append(f"recipe-run.json materialization {field} does not match score eval-run {field}: recorded={recorded} score={scored}")
    recorded = materialization.get("dictionary")
    scored = eval_run.get("dictionary")
    if recorded != scored:
        issues.append(f"recipe-run.json materialization dictionary does not match score eval-run dictionary: recorded={recorded} score={scored}")
    return issues


def _check_recipe_score_artifact_identity(score_dir: Path, score: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    eval_run_name = "page-eval-run.json" if eval_run.get("eval_mode") == "page_level_ocr" else "eval-run.json"
    for key, expected_path in (("metrics_file", score_dir / "metrics.json"), ("eval_run_file", score_dir / eval_run_name)):
        value = score.get(key)
        if not isinstance(value, str) or not value:
            issues.append(f"recipe-run.json score missing {key}")
        elif not _same_path(value, expected_path):
            issues.append(f"recipe-run.json score {key} does not point at score/{expected_path.name}")
        hash_key = f"{key}_sha256"
        recorded_hash = score.get(hash_key)
        if not isinstance(recorded_hash, str) or not recorded_hash:
            issues.append(f"recipe-run.json score missing {hash_key}")
        elif expected_path.exists():
            actual_hash = _sha256_file(expected_path)
            if actual_hash != recorded_hash:
                issues.append(
                    f"recipe-run.json score {hash_key} does not match score/{expected_path.name}: "
                    f"recorded={recorded_hash} actual={actual_hash}"
                )
    return issues


def _check_recipe_train_manifest_identity(recipe_run: dict[str, Any], eval_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    recorded = recipe_run.get("train_manifests")
    scored = eval_run.get("train_manifests")
    if recorded is None:
        recorded = []
    if scored is None:
        scored = []
    if not isinstance(recorded, list):
        return ["recipe-run.json train_manifests is not a list"]
    if not isinstance(scored, list):
        return ["eval-run.json train_manifests is not a list for recipe-root audit"]
    if len(recorded) != len(scored):
        return [f"recipe-run.json train_manifests count does not match eval-run.json: recorded={len(recorded)} score={len(scored)}"]
    for index, (recorded_item, scored_item) in enumerate(zip(recorded, scored, strict=True)):
        if not isinstance(recorded_item, dict):
            issues.append(f"recipe-run.json train_manifests[{index}] is not an object")
            continue
        if not isinstance(scored_item, dict):
            issues.append(f"eval-run.json train_manifests[{index}] is not an object for recipe-root audit")
            continue
        recorded_path = recorded_item.get("path")
        scored_path = scored_item.get("path")
        if not isinstance(recorded_path, str) or not recorded_path:
            issues.append(f"recipe-run.json train_manifests[{index}] missing path")
        elif not _same_path(recorded_path, Path(str(scored_path))):
            issues.append(f"recipe-run.json train_manifests[{index}] path does not match eval-run.json")
        recorded_sha = recorded_item.get("sha256")
        scored_sha = scored_item.get("sha256")
        if not isinstance(recorded_sha, str) or not recorded_sha:
            issues.append(f"recipe-run.json train_manifests[{index}] missing sha256")
        elif recorded_sha != scored_sha:
            issues.append(f"recipe-run.json train_manifests[{index}] sha256 does not match eval-run.json")
    return issues


def _current_recipe_validation(registry_path: Path, root_path: Path, recipe_id: str) -> dict[str, Any]:
    validator = _load_tool("validate_eval_harness_recipes")
    validation = validator.validate_recipes(registry_path, root_path)
    for recipe_validation in validation.get("recipes", []):
        if isinstance(recipe_validation, dict) and recipe_validation.get("id") == recipe_id:
            return recipe_validation
    raise ValueError(f"recipe validator result missing selected recipe: {recipe_id}")


def _check_recipe_artifact_consistency(run_dir: Path, recipe_run: dict[str, Any]) -> list[str]:
    issues: list[str] = []
    outputs = recipe_run.get("outputs")
    if not isinstance(outputs, dict):
        return issues
    recipe_id = recipe_run.get("recipe_id")
    recipe_path_value = outputs.get("recipe_file")
    validation_path_value = outputs.get("recipe_validation_file")
    local_recipe: dict[str, Any] | None = None

    if isinstance(recipe_path_value, str) and recipe_path_value:
        try:
            payload = _read_json(Path(recipe_path_value))
        except (FileNotFoundError, ValueError) as exc:
            issues.append(str(exc))
        else:
            if isinstance(payload, dict):
                local_recipe = payload
                if isinstance(recipe_id, str) and recipe_id and payload.get("id") != recipe_id:
                    issues.append(
                        "recipe.json id does not match recipe-run.json recipe_id: "
                        f"recipe.json={payload.get('id')} recipe-run.json={recipe_id}"
                    )
            else:
                issues.append("recipe.json must contain a JSON object")

    if isinstance(validation_path_value, str) and validation_path_value:
        try:
            validation_payload = _read_json(Path(validation_path_value))
        except (FileNotFoundError, ValueError) as exc:
            issues.append(str(exc))
        else:
            if validation_payload != recipe_run.get("recipe_validation"):
                issues.append("recipe-validation.json does not match recipe-run.json recipe_validation")

    registry_path_value = recipe_run.get("recipe_file")
    if isinstance(registry_path_value, str) and registry_path_value and isinstance(recipe_id, str) and recipe_id and local_recipe:
        registry_path = Path(registry_path_value)
        try:
            registry = _read_json(registry_path)
        except (FileNotFoundError, ValueError) as exc:
            issues.append(str(exc))
        else:
            recipes = registry.get("recipes") if isinstance(registry, dict) else None
            if not isinstance(recipes, list):
                issues.append("recipe registry file must contain a recipes list")
            else:
                matches = [recipe for recipe in recipes if isinstance(recipe, dict) and recipe.get("id") == recipe_id]
                if not matches:
                    issues.append(f"recipe registry file does not contain recipe_id: {recipe_id}")
                elif len(matches) > 1:
                    issues.append(f"recipe registry file contains duplicate recipe_id: {recipe_id}")
                elif matches[0] != local_recipe:
                    issues.append("recipe.json does not match selected recipe in recipe registry file")
        root_value = recipe_run.get("root")
        if isinstance(root_value, str) and root_value:
            try:
                current_validation = _current_recipe_validation(registry_path, Path(root_value), recipe_id)
            except Exception as exc:
                issues.append(f"recipe validation recomputation failed: {type(exc).__name__}: {exc}")
            else:
                if current_validation != recipe_run.get("recipe_validation"):
                    issues.append("recipe-run.json recipe_validation does not match current recipe validator result")

    if isinstance(recipe_path_value, str) and recipe_path_value and not _same_path(recipe_path_value, run_dir / "recipe.json"):
        issues.append("recipe-run.json outputs.recipe_file does not point at root recipe.json")
    if isinstance(validation_path_value, str) and validation_path_value and not _same_path(
        validation_path_value, run_dir / "recipe-validation.json"
    ):
        issues.append("recipe-run.json outputs.recipe_validation_file does not point at root recipe-validation.json")
    return issues


def _audit_recipe_root(run_dir: Path, score_dir: Path, eval_run: dict[str, Any], metrics: dict[str, Any], score_issues: list[str]) -> list[str]:
    if run_dir == score_dir:
        return []
    issues = _check_required_artifacts(run_dir, RECIPE_ROOT_ARTIFACTS)
    if eval_run.get("eval_mode") == "recognizer_oracle_crop":
        issues.extend(_check_required_artifacts(run_dir, ("predictions.txt",)))
    try:
        recipe_run = _read_json(run_dir / "recipe-run.json")
    except (FileNotFoundError, ValueError) as exc:
        return [*issues, str(exc)]
    if not isinstance(recipe_run, dict):
        return [*issues, "recipe-run.json must contain a JSON object"]
    issues.extend(_check_required_fields(recipe_run, RECIPE_REQUIRED_FIELDS, "recipe-run.json"))
    issues.extend(_check_timestamp(recipe_run, "created_at", "recipe run"))
    issues.extend(_check_machine_metadata(recipe_run, "recipe run"))
    issues.extend(_check_recipe_context_identity(recipe_run))
    if not isinstance(recipe_run.get("command"), str) or not recipe_run["command"]:
        issues.append("recipe run command is missing")
    issues.extend(_check_hash_field(recipe_run, "recipe_file", "recipe_file_sha256", "recipe registry file"))
    outputs = recipe_run.get("outputs")
    if not isinstance(outputs, dict):
        issues.append("recipe-run.json outputs is missing or not an object")
    else:
        required_outputs = [
            "materialization_dir",
            "score_dir",
            "recipe_file",
            "recipe_validation_file",
            "audit_file",
            "claim_safety_report",
        ]
        if eval_run.get("eval_mode") == "page_level_ocr":
            required_outputs.append("documents_dir")
        else:
            required_outputs.append("prediction_file")
        for key in required_outputs:
            value = outputs.get(key)
            if not isinstance(value, str) or not value:
                issues.append(f"recipe-run.json outputs missing {key}")
            elif not Path(value).exists():
                issues.append(f"recipe-run.json output path does not exist for {key}: {value}")
        if not _same_path(outputs.get("score_dir"), score_dir):
            issues.append("recipe-run.json outputs.score_dir does not match audited score directory")
        expected_root_paths = {
            "materialization_dir": run_dir / "materialize",
            "audit_file": run_dir / "audit.json",
            "claim_safety_report": run_dir / "claim-safety.md",
        }
        for key, expected_path in expected_root_paths.items():
            if isinstance(outputs.get(key), str) and not _same_path(outputs.get(key), expected_path):
                issues.append(f"recipe-run.json outputs.{key} does not point at root {expected_path.name}")
    materialization = recipe_run.get("materialization")
    if not isinstance(materialization, dict):
        issues.append("recipe-run.json materialization is missing or not an object")
    else:
        issues.extend(_check_materialization_provenance(materialization))
        issues.extend(_check_materialization_records(materialization, run_dir / "materialize"))
    issues.extend(_check_recipe_artifact_consistency(run_dir, recipe_run))
    issues.extend(_check_recipe_train_manifest_identity(recipe_run, eval_run))
    issues.extend(_check_recipe_output_lineage(run_dir, recipe_run, eval_run))
    issues.extend(_check_recipe_output_audit_consistency(run_dir, recipe_run, eval_run))
    issues.extend(_check_recipe_materialization_score_identity(recipe_run, eval_run))
    recipe_audit = recipe_run.get("audit")
    if not isinstance(recipe_audit, dict):
        issues.append("recipe-run.json audit summary is missing or not an object")
    else:
        if bool(recipe_audit.get("audit_passed")) != (not score_issues):
            issues.append("recipe-run.json audit_passed does not match current score audit")
        if bool(recipe_audit.get("claim_safe")) != bool(eval_run.get("claim_safe")):
            issues.append("recipe-run.json audit claim_safe does not match eval run")
        if recipe_audit.get("issues") != score_issues:
            issues.append("recipe-run.json audit issues do not match current score audit")
    score = recipe_run.get("score")
    if not isinstance(score, dict):
        issues.append("recipe-run.json score summary is missing or not an object")
    else:
        if bool(score.get("claim_safe")) != bool(eval_run.get("claim_safe")):
            issues.append("recipe-run.json score claim_safe does not match eval run")
        warnings = eval_run.get("warnings") if isinstance(eval_run.get("warnings"), list) else []
        if score.get("warnings") != warnings:
            issues.append("recipe-run.json score warnings do not match eval run")
        issues.extend(_check_recipe_score_artifact_identity(score_dir, score, eval_run))
    try:
        root_audit = _read_json(run_dir / "audit.json")
    except (FileNotFoundError, ValueError) as exc:
        issues.append(str(exc))
    else:
        if not isinstance(root_audit, dict):
            issues.append("audit.json must contain a JSON object")
        else:
            if bool(root_audit.get("audit_passed")) != (not score_issues):
                issues.append("audit.json audit_passed does not match current score audit")
            if bool(root_audit.get("claim_safe")) != bool(eval_run.get("claim_safe")):
                issues.append("audit.json claim_safe does not match eval run")
            if root_audit.get("warnings") != (eval_run.get("warnings") if isinstance(eval_run.get("warnings"), list) else []):
                issues.append("audit.json warnings do not match eval run")
            if root_audit.get("issues") != score_issues:
                issues.append("audit.json issues do not match current score audit")
            if not _same_path(root_audit.get("score_dir"), score_dir):
                issues.append("audit.json score_dir does not match audited score directory")
    claim_report = run_dir / "claim-safety.md"
    if claim_report.exists():
        text = claim_report.read_text(encoding="utf-8")
        for marker in ("## What Was Scored", "## Ground Truth And Pack", "## Metrics", "## Warnings"):
            if marker not in text:
                issues.append(f"root claim-safety.md missing section: {marker}")
        issues.extend(_check_root_claim_safety_report_consistency(run_dir, recipe_run, eval_run, metrics))
    return issues


def _audit_page(score_dir: Path) -> tuple[list[str], dict[str, Any], dict[str, Any]]:
    issues = _check_required_artifacts(score_dir, PAGE_ARTIFACTS)
    eval_run = _read_json(score_dir / "page-eval-run.json")
    metrics = _read_json(score_dir / "metrics.json")
    if not isinstance(eval_run, dict) or not isinstance(metrics, dict):
        return ["page eval artifacts must contain JSON objects"], {}, {}
    issues.extend(_check_required_fields(eval_run, PAGE_REQUIRED_RUN_FIELDS, "page-eval-run.json"))
    issues.extend(_check_common(score_dir, eval_run, metrics))
    issues.extend(
        _check_eval_run_identity_lists(
            eval_run,
            _csv_rows(score_dir / "page-metrics.csv"),
            run_label="page-eval-run.json",
            row_label="page-metrics.csv",
        )
    )
    issues.extend(_check_page_metadata_contradictions(score_dir, metrics, eval_run))
    issues.extend(_check_page_metadata_coverage(metrics, eval_run))
    issues.extend(_check_page_claim_blockers(eval_run, metrics))
    issues.extend(_check_page_output_audit(score_dir, metrics, eval_run))
    if eval_run.get("eval_mode") != "page_level_ocr":
        issues.append(f"unexpected page eval_mode: {eval_run.get('eval_mode')}")
    for path_field, hash_field, label in (
        ("eval_manifest", "eval_manifest_sha256", "page eval manifest"),
        ("summary_file", "summary_file_sha256", "page summary file"),
        ("script_inventory_file", "script_inventory_file_sha256", "page script inventory file"),
        ("spotcheck_calibration_file", "spotcheck_calibration_file_sha256", "page spotcheck calibration file"),
    ):
        issues.extend(_check_hash_field(eval_run, path_field, hash_field, label))
    issues.extend(_check_summary_metadata_consistency(eval_run, "page"))
    issues.extend(_check_spotcheck_calibration_summary(eval_run, metrics, "page"))
    issues.extend(_check_artifact_identity(eval_run, ("checkpoint", "config", "dictionary"), "page"))
    issues.extend(_check_train_manifest_hashes(eval_run))
    issues.extend(_check_page_leakage_report(metrics, eval_run))
    issues.extend(_check_page_output_duplicates(score_dir))
    issues.extend(_check_page_missing_artifact(score_dir, eval_run))
    issues.extend(_check_page_metric_identity_rows(score_dir, eval_run))
    issues.extend(_check_page_pack_content_digest(eval_run, metrics))
    issues.extend(_check_page_document_source_path_mismatches(metrics, eval_run))
    issues.extend(_check_page_row_hashes(score_dir))
    issues.extend(_check_page_manifest_count_metrics(metrics, eval_run))
    issues.extend(_check_page_line_alignment_recompute(score_dir, metrics, eval_run))
    issues.extend(_check_page_reference_artifacts(score_dir, eval_run))
    issues.extend(_check_page_text_pairs_artifact(score_dir, eval_run))
    issues.extend(_check_page_confusions(score_dir))
    issues.extend(_check_page_text_metrics_recompute(score_dir, metrics, eval_run))
    issues.extend(
        _check_normalization_summary(
            metrics.get("normalization_summary"),
            _expected_page_normalization_summary(score_dir),
            "page metrics",
        )
    )
    issues.extend(_check_page_uncertainty(score_dir, metrics))
    issues.extend(_check_page_script_inventory(score_dir, metrics, eval_run))
    issues.extend(_check_page_dictionary_coverage(score_dir, metrics, eval_run))
    issues.extend(_check_page_worst_artifacts(score_dir))
    issues.extend(_check_ratio(metrics, "text_codepoint_edits", "text_codepoint_ref_len", "text_cer_codepoint_micro"))
    issues.extend(_check_ratio(metrics, "text_grapheme_edits", "text_grapheme_ref_len", "text_cer_grapheme_micro"))
    if metrics.get("scored_pages") != _artifact_rows(score_dir / "page-metrics.csv"):
        issues.append("page-metrics.csv row count does not match scored_pages")
    if int(metrics.get("missing_documents", 0)) + int(metrics.get("missing_references", 0)) != _artifact_rows(score_dir / "missing.tsv"):
        issues.append("missing.tsv row count does not match missing document/reference counts")
    issues.extend(_check_page_reference_coverage(score_dir, metrics))
    coverage = metrics.get("reference_coverage")
    if not isinstance(coverage, dict):
        issues.append("page reference coverage is missing")
    elif int(coverage.get("line_bboxes", 0)) <= 0:
        issues.append("page eval has no line-bbox reference coverage")
    metadata_coverage = metrics.get("metadata_coverage")
    if not isinstance(metadata_coverage, dict):
        issues.append("page metadata coverage is missing")
    gt_statuses = eval_run.get("gt_statuses")
    if isinstance(gt_statuses, list) and "machine_converted_spot_checked" in gt_statuses:
        calibration = eval_run.get("spotcheck_calibration")
        if not isinstance(calibration, dict):
            issues.append("page spot-checked machine GT is missing calibration summary")
        elif not calibration.get("claim_evidence_eligible"):
            issues.append("page spot-check calibration is not claim evidence eligible")
    metric_means = metrics.get("metric_means")
    if not isinstance(metric_means, dict):
        issues.append("page metric means are missing")
    else:
        for key in ("line_detection_f1", "line_mean_iou", "reading_order_pair_accuracy"):
            if key not in metric_means:
                issues.append(f"page metric_means missing {key}")
    issues.extend(_check_page_slice_metrics(score_dir, metrics.get("slices")))
    leakage = metrics.get("leakage")
    if not isinstance(leakage, dict) or not leakage.get("checked"):
        issues.append("page train/dev leakage check was not run")
    return issues, eval_run, metrics


def audit_run(run_dir: Path) -> dict[str, Any]:
    score_dir = _score_dir(run_dir)
    mode = _mode(score_dir)
    if mode == "recognizer_oracle_crop":
        issues, eval_run, metrics = _audit_recognizer(score_dir)
    elif mode == "page_level_ocr":
        issues, eval_run, metrics = _audit_page(score_dir)
    else:
        raise ValueError(f"unsupported eval mode: {mode}")
    issues.extend(_audit_recipe_root(run_dir, score_dir, eval_run, metrics, issues))
    claim_safe = bool(eval_run.get("claim_safe")) if isinstance(eval_run, dict) else False
    return {
        "run_dir": str(run_dir),
        "score_dir": str(score_dir),
        "eval_mode": mode,
        "audit_passed": not issues,
        "claim_safe": claim_safe,
        "warnings": eval_run.get("warnings", []) if isinstance(eval_run, dict) else [],
        "issues": issues,
        "summary": {
            "model_name": eval_run.get("model_name") if isinstance(eval_run, dict) else None,
            "eval_pack_version": eval_run.get("eval_pack_version") if isinstance(eval_run, dict) else None,
            "normalization_profile": eval_run.get("normalization_profile") if isinstance(eval_run, dict) else None,
            "n_lines": metrics.get("n_lines") if isinstance(metrics, dict) else None,
            "scored_pages": metrics.get("scored_pages") if isinstance(metrics, dict) else None,
        },
    }


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--run-dir", type=Path, required=True)
    parser.add_argument("--out", type=Path)
    parser.add_argument("--require-audit-pass", action="store_true")
    parser.add_argument("--require-claim-safe", action="store_true")
    args = parser.parse_args(argv)
    result = audit_run(args.run_dir)
    if args.out:
        args.out.parent.mkdir(parents=True, exist_ok=True)
        args.out.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(
        f"eval_mode={result['eval_mode']} audit_passed={result['audit_passed']} "
        f"claim_safe={result['claim_safe']} issues={len(result['issues'])}"
    )
    if args.require_audit_pass and not result["audit_passed"]:
        raise SystemExit(1)
    if args.require_claim_safe and not result["claim_safe"]:
        raise SystemExit(1)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())