File size: 214,407 Bytes
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""compose_code - the code composer over the shapes of Python values, with the project's own functions as moves (12.0,

CODE_SPEC.md; Ben 2026-11-11: "Code is rules and composition. It can do novel code. It can do larger code.").



This is composer_v3 (swarm/composer_v3.py: typed moves, type-directed bottom-up search, observational equivalence, shortest

first, emitted code read back by a separate interpreter, admitted programs becoming moves) with its types widened from the

dimensions of numbers to the shapes of values: number, text, truth, list of T, mapping, nothing. The rules are what Python

does to each shape:

  MOVES     arithmetic, comparison and logic; text (lower, upper, strip, split, join, replace, slices, starts/ends, count);

            lists (len, sum, max, min, mean, median, sorted, reversed, unique, counts, index, slices, membership);

            mappings (lookup, keys, values, items); and the bodies of comprehensions - map, filter, sort/max/min by a key,

            a mapping built from a list, any/all - each body composed in its own search over the elements

  PARTS     the project's own functions (read from its files: name, inputs, the values the tests show them taking), called

            where their inputs fit; pure ones only (no file, process, network or printing calls)

  LIBRARY   every function composed and read back in this job is a part for the next (a module is composed round by

            round: a function that needs another is reached once that one exists)

  EVIDENCE  the project's tests (assert f(...) == v, assertEqual, approx, abs(... - v) < eps) and the examples written

            in the request (f(...) == v / -> v / returns v)

  WORDS     the request's words for the moves (sum, sort, keep, lower, ...) lower a move's cost: among programs that give

            the examples, the one the request describes wins

  BRANCHES  when no single expression gives every example, a decision list (if c: return a ... return b) in which each

            branch rests on at least two examples, or on one when its condition is an emptiness test (the guard)

  READ-BACK the function is written out and run by a separate interpreter on every example; it must give each one

It declines, and names the gap and the nearest program it reached, when nothing within its bounds gives every example.

All-number goals the shape search does not reach go to composer_v3 itself (units, cited constants, meet-in-the-middle);

its fitted-constant programs are refused here (code is not curve-fitting). No language model.



usage (child process, run by run_job):  compose_code.py <job file> <out file>"""
import ast
import builtins
import hashlib
import itertools
import json
import math
import os
import re
import subprocess
import sys
import tempfile
import time
from pathlib import Path

WB = Path(__file__).resolve().parent
MAX_SIZE = 7            # nodes in an outer program
INNER_MAX = 4           # nodes in a comprehension's body
L_MAX = 5               # nodes in the list a comprehension runs over
L_COUNT = 70            # lists per size a comprehension is tried over (the cheapest)
IDEMPOTENT = {"sorted", "sorted_desc", "unique", "dedupe", "lower", "upper", "strip", "title", "capitalize", "abs", "round",
              "int", "float", "str"}
INVOLUTION = {"reversed", "neg", "not"}
BANK_CAP = 150000       # programs kept per bank
MEM_MB = int(os.environ.get("O7_COMPOSE_MEM_MB", "2600"))   # the search's memory bound (banks inside banks share it)
_MEM = {"t": 0.0, "over": False, "hit": False}
# 12.5 step 6 (round-2 design 3.A): one work counter per goal, charged where a program is evaluated, by stage (bank: every
# program the banks see; probe: every evaluation in the disagreement pass). It is recorded with the result and the hole; it
# changes no decision (allowances by stage come later, set from this count measured on c31).
_WORK = {"bank": 0, "probe": 0, "last": None}


def mem_over():
    """the composer's memory past its bound (read at most four times a second): every bank stops growing, as at its time"""
    now = time.time()
    if now - _MEM["t"] > 0.25:
        _MEM["t"] = now
        try:
            with open("/proc/self/statm") as f:
                rss = int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE") >> 20
        except (OSError, ValueError, AttributeError):
            rss = 0
        _MEM["over"] = rss > MEM_MB
        _MEM["hit"] = _MEM["hit"] or _MEM["over"]
    return _MEM["over"]
INNER_CAP = 6000
GOAL_SECONDS = 50       # search time per goal
CHAIN_SECONDS = 70      # past the bound: chains (a body as its own goal, two programs joined)
PASS_SECONDS = 220      # one goal's whole pass (search, chains, the child's start and read-back), as run_job counts it
CHAIN_SECONDS_SUB = 12  # the same inside a body's own goal
MAX_DEPTH = 3              # goals inside goals: a list of pieces, then each piece
CHAIN_BESIDE_SECONDS = 20   # chains weighed beside a first fit that does not say its whole name
WORD_BONUS = 0.35       # a move the request names costs this much less
NAME_BONUS = 1.5       # each word of the function's name that a move of the program names: the name is a description
LOSSY = {"round", "rounded", "floor", "ceil", "int", "floordiv", "mod"}   # moves that throw information away
BITWISE = {"band", "bor", "bxor", "shl", "shr", "hmac"}   # numbers read as bits: weak evidence unless the words say bits
SPECIAL = {"entropy", "log2", "hexof", "binof", "sha256", "sha1", "md5", "b64enc", "b64dec", "hexenc", "hexdec", "int16",
           "int2", "ord", "chr"}   # special-purpose moves: a fit through one is weak evidence unless the words name it
ARBITRARY = re.compile(r"at1$|take\d|drop\d")   # a fixed position other than first or last: a choice two examples cannot make
AMBIG = 1.0            # rival programs this close in cost that answer differently elsewhere: ask, do not guess
LOSSY_PEN = 3.0        # their cost when the request does not name them: a fit through rounding is weak evidence
LAMBDA_BONUS = 0.2
ERR = "<err>"
SECRET = re.compile(r"(?i)(secret|credential|wallet|password|passwd|token|key_guard|keys\.py|keypair|\.env)")
IMPURE_CALLS = {"open", "print", "input", "exec", "eval", "compile", "__import__", "exit", "quit", "breakpoint", "setattr",
                "delattr", "globals", "locals"}
IMPURE_MODS = {"os", "sys", "subprocess", "shutil", "socket", "requests", "urllib", "pathlib", "http", "random", "time",
               "datetime", "threading", "multiprocessing", "signal", "sqlite3", "logging", "tempfile", "glob", "io"}


# ================================================================ shapes (types read from values)
def tyof(v):
    if v is None:
        return "none"
    if isinstance(v, bool):
        return "bool"
    if isinstance(v, int):
        return "int"
    if isinstance(v, float):
        return "float" if math.isfinite(v) else "?"
    if isinstance(v, str):
        return "str"
    if isinstance(v, (list, tuple)):
        t = None
        for x in v:
            t = join(t, tyof(x))
            if t == "?":
                return "?"
        return ("list" if isinstance(v, list) else "tuple", t)
    if isinstance(v, dict):
        kt = vt = None
        mixed = False
        for k, x in v.items():
            kt = join(kt, tyof(k))
            if not mixed:
                vt = join(vt, tyof(x))
                if vt == "?":                         # a record: fields of different shapes, each read on its own
                    mixed, vt = True, None
            if kt == "?":
                return "?"
        return ("dict", kt, vt)
    return "?"


def join(a, b):
    if a is None:
        return b
    if b is None:
        return a
    if a == b:
        return a
    if {a, b} == {"int", "float"}:
        return "float"
    if isinstance(a, tuple) and isinstance(b, tuple) and a[0] == b[0] and len(a) == len(b):
        parts = [join(x, y) for x, y in zip(a[1:], b[1:])]
        return "?" if "?" in parts else (a[0],) + tuple(parts)
    return "?"


def ty_of_vals(vals):
    t = None
    for v in vals:
        if v is ERR:
            continue
        t = join(t, tyof(v))
        if t == "?":
            return "?"
    return t


def is_num(t):
    return t in ("int", "float")


def is_seq(t):
    return isinstance(t, tuple) and t[0] in ("list", "tuple")


def is_lnum(t):
    return is_seq(t) and t[1] in (None, "int", "float")


def is_lstr(t):
    return is_seq(t) and t[1] in (None, "str")


def is_lbool(t):
    return is_seq(t) and t[1] in (None, "bool")


def is_hashable_seq(t):
    return is_seq(t) and t[1] in (None, "int", "float", "str", "bool")


def is_iter(t):
    return is_seq(t) or t == "str"


def is_dict(t):
    return isinstance(t, tuple) and t[0] == "dict"


def is_sortable(t):
    return (is_seq(t) and t[1] in (None, "int", "float", "str")) or t == "str"


def elem(t):
    return "str" if t == "str" else (t[1] if is_seq(t) else None)


def same(a, b, tol=None):
    """the equality a test asks for: numbers within the test's tolerance (or exactly), truth values strictly"""
    if a is ERR:
        return False
    if isinstance(a, bool) or isinstance(b, bool):
        return isinstance(a, bool) and isinstance(b, bool) and a == b
    if isinstance(a, (int, float)) and isinstance(b, (int, float)):
        if isinstance(b, float) and not isinstance(a, float) and tol is None:
            return False                              # an example written as 5.0 says the value is a decimal number
        if tol is not None:
            return abs(a - b) <= tol
        return abs(a - b) <= 1e-9 * max(1.0, abs(b))
    if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
        return type(a) is type(b) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
    if isinstance(a, dict) and isinstance(b, dict):
        return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
    if isinstance(a, str) and isinstance(b, str):
        return str(a) == str(b)                       # a constant read from a name or a field is text like any other
    return type(a) is type(b) and a == b


def norm(v):
    if v is ERR:
        return ("E",)
    if isinstance(v, float):
        return ("f", round(v, 9))
    if isinstance(v, list):
        return ("L",) + tuple(norm(x) for x in v)
    if isinstance(v, tuple):
        return ("T",) + tuple(norm(x) for x in v)
    if isinstance(v, dict):
        return ("D",) + tuple(sorted(((norm(k), norm(x)) for k, x in v.items()), key=repr))
    if isinstance(v, bool):
        return ("b", v)
    return v


# ================================================================ moves: what Python does to each shape
def _nonempty(f):
    def g(a):
        if not a:
            raise ValueError("empty")
        return f(a)
    return g


def _smallint(f):
    def g(a, b):
        if not isinstance(b, int) or isinstance(b, bool) or abs(b) > 8:
            raise ValueError("exponent")
        return f(a, b)
    return g


def _mean(a):
    import statistics
    return statistics.fmean(a)   # an average is a decimal number


def _median(a):
    import statistics
    return statistics.median(a)


def _ap_prod(a):
    v = math.prod(a)
    if abs(v) > 10 ** 15:
        raise OverflowError("product")
    return v


def _horner(base):
    def f(a):
        acc = 0
        for d in a:
            if isinstance(d, bool) or not isinstance(d, int):
                raise TypeError("digits")
            acc = acc * base + d
        if abs(acc) > 10 ** 15:
            raise OverflowError("fold")
        return acc
    return f


def _hexdigest(name):
    def f(t):
        import hashlib
        return hashlib.new(name, t.encode()).hexdigest()
    return f


def _b64enc(t):
    import base64
    return base64.b64encode(t.encode()).decode()


def _b64dec(t):
    import base64
    return base64.b64decode(t, validate=True).decode()


def _entropy(a):
    import collections
    if not a:
        raise ValueError("empty")
    n = len(a)
    return -sum(c / n * math.log2(c / n) for c in collections.Counter(a).values()) + 0.0


def _hmac(k, m):
    import hashlib
    import hmac
    return hmac.new(k.encode(), m.encode(), hashlib.sha256).hexdigest()


def _is_int(t):
    return t == "int"


def _shift(f):
    def g(a, b):
        if not 0 <= b <= 64:
            raise ValueError("shift")
        return f(a, b)
    return g


PATTERNS = {   # named shapes of text, found with re.findall; the request's or the name's words choose them
    "ipv4s": (r"\b(?:\d{1,3}\.){3}\d{1,3}\b", "ip ips address addresses ipv4"),
    "emails": (r"[\w.+-]+@[\w-]+\.[\w.-]+", "email emails mail address addresses"),
    "urls": (r"https?://[^\s\"'<>]+", "url urls link links address"),
    "hexes": (r"\b[0-9a-fA-F]{8,}\b", "hex hash hashes digest token"),
    "numbers": (r"-?\d+", "number numbers digits integers"),
}


def _tlit(v):
    """a value written into a move's code template: its braces are the value's, not the template's"""
    return repr(v).replace("{", "{{").replace("}", "}}")


def _findall(pat):
    def f(t):
        return re.findall(pat, t)
    return f


def _counter(a):
    import collections
    return dict(collections.Counter(a))


# name, applies to (type), the operation, its code, the words for it, imports
UNARY = [
    ("neg", is_num, lambda a: -a, "(-{0})", "negative negate minus opposite", ()),
    ("abs", is_num, abs, "abs({0})", "absolute magnitude distance", ()),
    ("round", lambda t: t == "float", round, "round({0})", "round rounded nearest whole", ()),
    ("int", lambda t: t in ("float", "str"), int, "int({0})", "integer whole convert number", ()),
    ("float", lambda t: t == "str", float, "float({0})", "decimal convert number", ()),
    ("str", is_num, str, "str({0})", "text string convert digits digit", ()),
    ("not", lambda t: t == "bool", lambda a: not a, "(not {0})", "not opposite", ()),
    ("sqrt", is_num, math.sqrt, "math.sqrt({0})", "square root", ("math",)),
    ("floor", lambda t: t == "float", math.floor, "math.floor({0})", "floor down", ("math",)),
    ("ceil", lambda t: t == "float", math.ceil, "math.ceil({0})", "ceiling up", ("math",)),
    ("len", lambda t: is_iter(t) or is_dict(t), len, "len({0})", "count number length how many size", ()),
    ("empty", lambda t: is_iter(t) or is_dict(t), lambda a: not a, "(not {0})", "empty nothing none no", ()),
    ("sum", is_lnum, sum, "sum({0})", "sum total add together", ()),
    ("prod", is_lnum, lambda a: _ap_prod(a), "math.prod({0})", "product multiply multiplied all together", ("math",)),
    ("max", is_sortable, _nonempty(max), "max({0})", "max maximum largest biggest highest most greatest expensive dearest", ()),
    ("min", is_sortable, _nonempty(min), "min({0})", "min minimum smallest lowest least fewest cheap cheapest", ()),
    ("mean", is_lnum, _nonempty(_mean), "statistics.fmean({0})", "average mean", ("statistics",)),
    ("median", is_lnum, _nonempty(_median), "statistics.median({0})", "median middle", ("statistics",)),
    ("sorted", is_sortable, sorted, "sorted({0})", "sort sorted order ascending alphabetical", ()),
    ("sorted_desc", is_sortable, lambda a: sorted(a, reverse=True), "sorted({0}, reverse=True)",
     "sort sorted descending reverse largest first", ()),
    ("reversed", lambda t: is_seq(t) or t == "str", lambda a: a[::-1], "{0}[::-1]", "reverse reversed backwards", ()),
    ("unique", is_hashable_seq, lambda a: sorted(set(a)), "sorted(set({0}))", "unique distinct deduplicate different", ()),
    ("dedupe", is_hashable_seq, lambda a: list(dict.fromkeys(a)), "list(dict.fromkeys({0}))",
     "unique distinct dedupe duplicates repeats order", ()),
    ("nunique", is_hashable_seq, lambda a: len(set(a)), "len(set({0}))", "distinct unique different count", ()),
    ("counts", is_hashable_seq, _counter, "dict(collections.Counter({0}))", "count counts frequency occurrences each tally",
     ("collections",)),
    ("any", is_lbool, any, "any({0})", "any some at least one", ()),
    ("all", is_lbool, all, "all({0})", "all every each", ()),
    ("chars", lambda t: t == "str", list, "list({0})", "characters letters chars", ()),
    ("sha256", lambda t: t == "str", _hexdigest("sha256"), "hashlib.sha256({0}.encode()).hexdigest()",
     "sha256 sha hash digest checksum hex", ("hashlib",)),
    ("sha1", lambda t: t == "str", _hexdigest("sha1"), "hashlib.sha1({0}.encode()).hexdigest()", "sha1 sha hash digest checksum",
     ("hashlib",)),
    ("md5", lambda t: t == "str", _hexdigest("md5"), "hashlib.md5({0}.encode()).hexdigest()", "md5 hash digest checksum hex",
     ("hashlib",)),
    ("b64enc", lambda t: t == "str", _b64enc, "base64.b64encode({0}.encode()).decode()", "base64 b64 encode encoded", ("base64",)),
    ("b64dec", lambda t: t == "str", _b64dec, "base64.b64decode({0}).decode()", "base64 b64 decode decoded from", ("base64",)),
    ("hexenc", lambda t: t == "str", lambda a: a.encode().hex(), "{0}.encode().hex()", "hex hexadecimal encode to", ()),
    ("hexdec", lambda t: t == "str", lambda a: bytes.fromhex(a).decode(), "bytes.fromhex({0}).decode()",
     "hex hexadecimal decode from", ()),
    ("int16", lambda t: t == "str", lambda a: int(a, 16), "int({0}, 16)", "hex hexadecimal parse number from", ()),
    ("int2", lambda t: t == "str", lambda a: int(a, 2), "int({0}, 2)", "binary bits parse number from", ()),
    ("hexof", _is_int, lambda a: format(a, "x"), "format({0}, 'x')", "hex hexadecimal to", ()),
    ("binof", _is_int, lambda a: format(a, "b"), "format({0}, 'b')", "binary bits to", ()),
    ("ord", lambda t: t == "str", lambda a: ord(a) if len(a) == 1 else 1 / 0, "ord({0})", "code ord ascii codepoint", ()),
    ("chr", _is_int, lambda a: chr(a) if 0 <= a < 0x110000 else 1 / 0, "chr({0})", "character chr letter ascii", ()),
    ("bool", is_num, bool, "bool({0})", "set nonzero true flag is", ()),
    ("log2", is_num, math.log2, "math.log2({0})", "log logarithm bits", ("math",)),
    ("entropy", lambda t: t == "str" or is_hashable_seq(t), _entropy,
     "(-sum(c / len({0}) * math.log2(c / len({0})) for c in collections.Counter({0}).values()) + 0.0)",
     "entropy shannon randomness information", ("math", "collections")),
    ("lower", lambda t: t == "str", str.lower, "{0}.lower()", "lower lowercase case small ignoring", ()),
    ("upper", lambda t: t == "str", str.upper, "{0}.upper()", "upper uppercase capitals capital shout loud", ()),
    ("strip", lambda t: t == "str", str.strip, "{0}.strip()", "strip trim whitespace spaces ends", ()),
    ("title", lambda t: t == "str", str.title, "{0}.title()", "title capitalize capitalise capitals", ()),
    ("capitalize", lambda t: t == "str", str.capitalize, "{0}.capitalize()", "capitalize capitalise first capital", ()),
    ("words", lambda t: t == "str", str.split, "{0}.split()", "split words spaces whitespace collapse", ()),
    ("lines", lambda t: t == "str", str.splitlines, "{0}.splitlines()", "lines line", ()),
    ("isdigit", lambda t: t == "str", str.isdigit, "{0}.isdigit()", "digit digits number numeric", ()),
    ("isalpha", lambda t: t == "str", str.isalpha, "{0}.isalpha()", "letter letters alphabetic", ()),
    ("isupper", lambda t: t == "str", str.isupper, "{0}.isupper()", "upper uppercase capital", ()),
    ("keys", is_dict, lambda a: sorted(a), "sorted({0})", "keys", ()),
    ("values", is_dict, lambda a: list(a.values()), "list({0}.values())", "values", ()),
    ("items", is_dict, lambda a: sorted(a.items()), "sorted({0}.items())", "items pairs entries", ()),
]

CMP_WORDS = ("greater more over above larger exceeds bigger positive less under below smaller fewer negative most within least "
             "at alphabetical alphabetically before after")   # one comparison read from either side (x > 0 is 0 < x): the same words
BINARY = [  # name, applies to (ta, tb), operation, code, words, commutative
    ("add", lambda a, b: is_num(a) and is_num(b), lambda a, b: a + b, "({0} + {1})", "add plus sum total more", True),
    ("sub", lambda a, b: is_num(a) and is_num(b), lambda a, b: a - b, "({0} - {1})", "subtract minus difference less", False),
    ("mul", lambda a, b: is_num(a) and is_num(b), lambda a, b: a * b, "({0} * {1})", "multiply times product double", True),
    ("div", lambda a, b: is_num(a) and is_num(b), lambda a, b: a / b, "({0} / {1})", "divide divided ratio per half share", False),
    ("floordiv", lambda a, b: a == "int" and b == "int", lambda a, b: a // b, "({0} // {1})",
     "divide whole digit digits half halve halving halvings", False),
    ("mod", lambda a, b: a == "int" and b == "int", lambda a, b: a % b, "({0} % {1})",
     "remainder modulo even odd divisible multiple digit digits", False),
    ("pow", lambda a, b: is_num(a) and b == "int", _smallint(lambda a, b: a ** b), "({0} ** {1})", "power squared cubed", False),
    ("max2", lambda a, b: is_num(a) and is_num(b), max, "max({0}, {1})", "max at least floor clamp between larger", True),
    ("min2", lambda a, b: is_num(a) and is_num(b), min, "min({0}, {1})", "min at most cap limit clamp between smaller", True),
    ("concat", lambda a, b: a == "str" and b == "str", lambda a, b: a + b, "({0} + {1})",
     "append add concatenate join suffix prefix end", False),
    ("repeat", lambda a, b: a == "str" and b == "int", lambda a, b: a * b if 0 <= b <= 64 else 1 / 0, "({0} * {1})",
     "repeat times", False),
    ("lconcat", lambda a, b: is_seq(a) and is_seq(b) and a[0] == b[0] and join(a, b) != "?", lambda a, b: a + b,
     "({0} + {1})", "append add combine join extend", False),
    ("eq", lambda a, b: a == b and a in ("int", "str", "bool") or (is_num(a) and is_num(b)), lambda a, b: a == b,
     "({0} == {1})", "equal equals same is", True),
    ("ne", lambda a, b: a == b and a in ("int", "str") or (is_num(a) and is_num(b)), lambda a, b: a != b, "({0} != {1})",
     "not different other", True),
    ("lt", lambda a, b: (is_num(a) and is_num(b)) or a == b == "str", lambda a, b: a < b, "({0} < {1})",
     CMP_WORDS, False),
    ("le", lambda a, b: (is_num(a) and is_num(b)), lambda a, b: a <= b, "({0} <= {1})", CMP_WORDS, False),
    ("gt", lambda a, b: (is_num(a) and is_num(b)) or a == b == "str", lambda a, b: a > b, "({0} > {1})",
     CMP_WORDS, False),
    ("ge", lambda a, b: (is_num(a) and is_num(b)), lambda a, b: a >= b, "({0} >= {1})", CMP_WORDS, False),
    ("and", lambda a, b: a == b == "bool", lambda a, b: a and b, "({0} and {1})", "and both", True),
    ("or", lambda a, b: a == b == "bool", lambda a, b: a or b, "({0} or {1})", "or either", True),
    ("in", lambda a, b: (b == "str" and a == "str") or (is_seq(b) and b[1] in (None, a)) or (is_dict(b) and b[1] in (None, a)),
     lambda a, b: a in b, "({0} in {1})", "in contains includes has member among", False),
    ("count", lambda a, b: (a == "str" and b == "str") or (is_seq(a) and a[1] in (None, b)), lambda a, b: a.count(b),
     "{0}.count({1})", "count occurrences times how many", False),
    ("at", lambda a, b: is_iter(a) and b == "int", lambda a, b: a[b], "{0}[{1}]", "at index position element item", False),
    ("get", lambda a, b: is_dict(a) and a[1] in (None, b), lambda a, b: a[b], "{0}[{1}]", "lookup value of for", False),
    ("startswith", lambda a, b: a == b == "str", lambda a, b: a.startswith(b), "{0}.startswith({1})", "starts begins prefix", False),
    ("band", lambda a, b: a == b == "int", lambda a, b: a & b, "({0} & {1})", "and mask masked byte low bits bitwise nibble byte bit bits", True),
    ("bor", lambda a, b: a == b == "int", lambda a, b: a | b, "({0} | {1})", "or set combine flag flags bitwise nibble byte bit bits", True),
    ("bxor", lambda a, b: a == b == "int", lambda a, b: a ^ b, "({0} ^ {1})", "xor exclusive flip toggle bitwise nibble byte bit bits", True),
    ("shl", lambda a, b: a == b == "int", _shift(lambda a, b: a << b), "({0} << {1})", "shift left bit bits nibble byte bit bits", False),
    ("shr", lambda a, b: a == b == "int", _shift(lambda a, b: a >> b), "({0} >> {1})", "shift right bit bits nibble byte bit bits", False),
    ("hmac", lambda a, b: a == b == "str", _hmac, "hmac.new({0}.encode(), {1}.encode(), hashlib.sha256).hexdigest()",
     "hmac mac signature sign signed keyed", False),
    ("endswith", lambda a, b: a == b == "str", lambda a, b: a.endswith(b), "{0}.endswith({1})", "ends suffix", False),
    ("rounded", lambda a, b: a == "float" and b == "int", lambda a, b: round(a, b) if 0 <= b <= 6 else 1 / 0,
     "round({0}, {1})", "round decimals places", False),
]

# three-place moves: Python's chained comparison (a <= x <= b is one move, as the language writes it)
TERNARY = [
    ("between", lambda a, b, c: is_num(a) and is_num(b) and is_num(c), lambda a, b, c: a <= b <= c, "{0} <= {1} <= {2}",
     CMP_WORDS + " between inclusive range from to", ()),
    ("between_open", lambda a, b, c: is_num(a) and is_num(b) and is_num(c), lambda a, b, c: a < b < c, "{0} < {1} < {2}",
     CMP_WORDS + " between strictly exclusive range", ()),
    ("between_text", lambda a, b, c: a == b == c == "str", lambda a, b, c: a.split(b, 1)[1].split(c, 1)[0] if b and c else 1 / 0,
     "{0}.split({1}, 1)[1].split({2}, 1)[0]", "between inside tag text within enclosed", ()),
]

# two programs joined side by side, found from the answer: given one side's values, the other side's values are known
JOINS = ["add", "sub", "mul", "div", "concat", "lconcat"]

LAMBDAS = {  # the comprehension forms: code with {v} (the element), {L} (the list), {b} (the body); words
    "map": ("[{b} for {v} in {L}]", "each every all of"),
    "filter": ("[{v} for {v} in {L} if {b}]", "keep keeps only where filter select which that whose remove drop"),
    "sortkey": ("sorted({L}, key=lambda {v}: {b})", "sort sorted order by"),
    "maxkey": ("max({L}, key=lambda {v}: {b})", "longest largest biggest most max highest expensive dearest priciest"),
    "minkey": ("min({L}, key=lambda {v}: {b})", "shortest smallest least min lowest cheap cheapest"),
    "dictof": ("{{{v}: {b} for {v} in {L}}}", "mapping dictionary each count per"),
    "anyof": ("any({b} for {v} in {L})", "any some contains"),
    "allof": ("all({b} for {v} in {L})", "all every each"),
}


def stem(w):
    w = w.lower()
    if len(w) > 6 and w.endswith("iest"):
        return w[:-4]                                 # a superlative is its base: priciest -> pric, busiest -> bus
    if len(w) > 6 and w.endswith("est") and not w.endswith(("ffest", "quest", "interest", "contest", "protest")):
        return w[:-3]                                 # cheapest -> cheap, longest -> long
    for suf in ("ing", "es", "ed"):
        if len(w) > 4 and w.endswith(suf):
            return w[: -len(suf)]
    if len(w) > 3 and w.endswith("s") and not w.endswith(("ss", "us", "is")):
        return w[:-1]                                 # a short plural too: odds, keys, bits
    return w


# ================================================================ expressions
class X:
    __slots__ = ("op", "args", "val", "t", "size", "cost", "inp", "dead", "rmask", "imports", "pen", "uses", "nmask", "live",
                 "lossy", "waived")

    def __init__(self, op, args, val, size, inp, named=(0, 0), imports=(), uses=0):
        self.uses = uses
        for a in args:
            if isinstance(a, X):
                self.uses |= a.uses
        self.op, self.args, self.val = op, tuple(args), val
        self.t = ty_of_vals(val)
        self.size, self.inp, self.dead = size, inp, False
        # a move on constants alone is a constant: it describes nothing (no word of the request or the name is covered by it)
        self.live = op[0] in ("in", "var", "body") or (op[0] == "outer" and op[1].live) or any(a.live for a in args if isinstance(a, X))
        rm, nm = named if isinstance(named, tuple) else (0, 0)
        body = op[1] if op[0] in ("body", "scan", "zip") else None   # a step composed as its own goal: it carries its words
        # the request's words / the name's words this names (a text constant names the words it spells)
        self.rmask, self.nmask = (rm, nm) if (self.live or (op[0] == "const" and isinstance(op[1], str))) else (0, 0)
        pasted = op[0] == "b" and op[1] in ("concat", "lconcat")
        for a in args:
            if isinstance(a, X):
                if pasted and _unouter(a).op[0] == "const" and isinstance(_unouter(a).op[1], str):
                    continue                          # a text pasted onto the data is not looked for: it says nothing (C8h)
                self.rmask |= a.rmask
                self.nmask |= a.nmask
        weak = weak_move(op, args)
        own = LOSSY_PEN if (weak and not (rm or nm)) else 0.0
        # a weak move a word excused: it may be chosen, but it never makes a program say more of the name than another
        self.waived = bool(weak and (rm or nm)) or any(a.waived for a in args if isinstance(a, X)) or             (body is not None and body.waived)
        if body is not None:
            self.rmask, self.nmask, own = body.rmask, body.nmask, body.pen
        self.lossy = own > 0 or any(a.lossy for a in args if isinstance(a, X)) or (body is not None and body.lossy)
        if op[0] == "lam":
            own -= LAMBDA_BONUS                    # at equal size, the program that works element by element
        self.pen = own + sum(a.pen for a in args if isinstance(a, X))
        # each word counts once, however many moves name it (a move added only to name a word again gains nothing)
        self.cost = size - WORD_BONUS * bin(self.rmask).count("1") - NAME_BONUS * bin(self.nmask).count("1") + self.pen
        self.imports = set(imports) | (body.imports if body is not None else set())
        for a in args:
            if isinstance(a, X):
                self.imports |= a.imports


WEAK = {   # a fit through one of these moves is weak evidence unless the request or the name says it; declared once, why
    **{m: "throws information away" for m in LOSSY},
    **{m: "reads numbers as bits" for m in BITWISE},
    **{m: "special-purpose" for m in SPECIAL},
}


_COMMUTES = (ast.Add, ast.Mult, ast.BitAnd, ast.BitOr, ast.BitXor)


def _canon(n):
    """a program's shape with the two sides of a commuting move in one order (state + value is value + state)"""
    if isinstance(n, ast.BinOp) and isinstance(n.op, _COMMUTES):
        a, b = sorted([_canon(n.left), _canon(n.right)])
        return "BinOp(%s,%s,%s)" % (type(n.op).__name__, a, b)
    if isinstance(n, ast.Compare) and len(n.ops) == 1 and isinstance(n.ops[0], (ast.Eq, ast.NotEq)):
        a, b = sorted([_canon(n.left), _canon(n.comparators[0])])
        return "Compare(%s,%s,%s)" % (type(n.ops[0]).__name__, a, b)
    if isinstance(n, ast.AST):
        return "%s(%s)" % (type(n).__name__, ",".join(_canon(v) for _f, v in ast.iter_fields(n)))
    if isinstance(n, list):
        return "[%s]" % ",".join(_canon(v) for v in n)
    return repr(n)


def _unwrapped_dumps(t):
    """the program with each one-argument call around a part of it taken away, one at a time"""
    out = []
    def inner(ch):
        if isinstance(ch, ast.Call) and len(ch.args) == 1 and not ch.keywords:
            return ch.args[0]
        return None                                   # a sign is never a wrapper: -x and x differ wherever x is not 0
    i0 = inner(t.body)
    if i0 is not None:
        out.append(_canon(i0))
    for node in ast.walk(t):
        for field, val in ast.iter_fields(node):
            items = val if isinstance(val, list) else [val]
            for i, ch in enumerate(items):
                if not isinstance(ch, ast.AST):
                    continue
                inn = inner(ch)
                if inn is None:
                    continue
                if isinstance(val, list):
                    val[i] = inn
                else:
                    setattr(node, field, inn)
                out.append(_canon(t.body))
                if isinstance(val, list):
                    val[i] = ch
                else:
                    setattr(node, field, ch)
    return out


def wraps(a_src, b_src):
    """one program is the other with a wrapper around some part of it (abs(state) for state): the same program, never

    a rival - the plainer is kept"""
    a_src, b_src = a_src.strip(), b_src.strip()
    try:
        at, bt = ast.parse(a_src, mode="eval"), ast.parse(b_src, mode="eval")
    except SyntaxError:                               # a program over lines: read as text
        return a_src in b_src or b_src in a_src
    da, db = _canon(at.body), _canon(bt.body)
    return da == db or da in _unwrapped_dumps(bt) or db in _unwrapped_dumps(at)


def weak_name(name):
    """a move weak by its kind alone, whatever it is given"""
    return name in WEAK or name in PATTERNS or name.startswith("fold") or bool(ARBITRARY.match(name))


def _unouter(x):
    """a value carried into a comprehension's body from outside it, as it is outside"""
    while isinstance(x, X) and x.op[0] == "outer" and isinstance(x.op[1], X):
        x = x.op[1]
    return x


def weak_move(op, args):
    """why a move is weak evidence here, or None"""
    if op[0] not in ("u", "b"):
        return None
    name = op[1]
    args = [_unouter(a) for a in args]
    a0 = args[0] if args and isinstance(args[0], X) else None
    if name == "int" and a0 is not None and a0.t == "str":
        return None                                   # parsing text keeps all it says
    if name == "repeat":
        return "a text repeated"
    if name == "pow" and len(args) == 2 and isinstance(args[1], X) and args[1].live:
        return "a power read from the data"
    if name == "mod" and len(args) == 2 and isinstance(args[1], X) and args[1].live:
        return "a remainder by a value read from the data"
    if name in ("dedupe", "unique") and a0 is not None and a0.op[0] == "u" and a0.op[1] in ("readlines", "readtext", "lines"):
        return "repeated lines of the input dropped"     # what is unique is what the answer names, not the raw input
    if name == "mod" and len(args) == 2 and isinstance(args[1], X) and args[1].op[0] == "const" and args[1].op[1] == 2:
        return None                                   # odd or even: an ordinary property of a whole number
    if name in WEAK:
        return WEAK[name]
    if name in PATTERNS or name.startswith("fold"):
        return "special-purpose"
    if ARBITRARY.match(name):
        return "a fixed position"
    if name == "at" and len(args) == 2 and isinstance(args[1], X) and not args[1].live and \
            any(v not in (0, -1) for v in args[1].val if v is not ERR):
        return "a fixed position"
    if name == "str" and a0 is not None and is_num(a0.t):
        return "a number's digits read as text"
    if (name in ("lt", "le", "gt", "ge", "max", "min", "sorted", "sorted_desc", "unique")) and a0 is not None and a0.t == "str":
        return "letters' alphabetical order"
    if name in ("eq", "ne") and any(isinstance(a, X) and a.op[0] == "const" and isinstance(a.op[1], Boundary) for a in args):
        return "one value taken from the examples"
    return None


def _ap(f, *xs):
    if any(x is ERR for x in xs):
        return ERR
    try:
        v = f(*xs)
    except Exception:  # noqa: BLE001
        return ERR
    if isinstance(v, float) and not math.isfinite(v):
        return ERR
    if isinstance(v, (int,)) and not isinstance(v, bool) and abs(v) > 10 ** 15:
        return ERR
    if isinstance(v, (str, list, tuple, dict)) and len(v) > 2000:
        return ERR
    return v


class Bank:
    """one search: leaves, then every move whose types fit, level by level; two programs that give the same values on every

    row are one (the cheaper kept)"""

    def __init__(self, n, deadline, cap, words, consts, parts, outer=None, namewords=()):
        self.namewords = list(namewords)
        self.n, self.deadline, self.cap, self.words = n, deadline, cap, words
        self.seen, self.lv, self.consts, self.parts, self.outer = {}, {}, consts, parts, outer
        self.ex = None                               # the examples (outer search only): which inputs matter
        self.alts = {}                               # programs that gave the examples but lost on cost, by key
        self.subalts = {}                            # parts that gave the same values as a kept part, by key
        self.inner_cache = {}
        self.unary = list(UNARY)
        strs = [c for c in consts if isinstance(c, str) and not isinstance(c, Field)]
        for sep in strs:                                  # moves with a constant folded in: join with ", ", split on "-"
            self.unary.append(("join%r" % sep, is_lstr, (lambda s: lambda a: s.join(a))(sep), "%s.join({0})" % _tlit(sep),
                               "join joined combine together glue with", ()))
            if sep:
                self.unary.append(("split%r" % sep, lambda t: t == "str", (lambda s: lambda a: a.split(s))(sep),
                                   "{0}.split(%s)" % _tlit(sep), "split separate", ()))
        for a_, b_ in itertools.permutations(strs, 2):
            if a_:
                self.unary.append(("replace%r%r" % (a_, b_), lambda t: t == "str",
                                   (lambda x, y: lambda s: s.replace(x, y))(a_, b_), "{0}.replace(%s, %s)" % (_tlit(a_), _tlit(b_)),
                                   "replace swap substitute remove", ()))
        for base in sorted({c for c in consts if isinstance(c, int) and not isinstance(c, bool) and 2 <= c <= 16} | {2, 10}):
            # a loop that carries a state: each element folded into the total so far, by position (digits, bits)
            self.unary.append(("fold%d" % base, lambda t: is_seq(t) and t[1] in (None, "int"), _horner(base),
                               "functools.reduce(lambda acc, d: acc * %d + d, {0}, 0)" % base,
                               "digits digit number base binary bits positional combine fold %s" % (
                                   "decimal" if base == 10 else "binary" if base == 2 else ""), ("functools",)))
        for k, w in ((0, "first head initial"), (-1, "last final end"), (1, "second")):
            self.unary.append(("at%d" % k, is_iter, (lambda i: lambda a: a[i])(k), "{0}[%d]" % k, w + " letter element item", ()))
        for k in sorted({c for c in consts if isinstance(c, int) and not isinstance(c, bool) and 1 <= c <= 10} | {1, 2}):
            self.unary.append(("take%d" % k, lambda t: is_seq(t) or t == "str", (lambda i: lambda a: a[:i])(k), "{0}[:%d]" % k,
                               "first top take head", ()))
            self.unary.append(("drop%d" % k, lambda t: is_seq(t) or t == "str", (lambda i: lambda a: a[i:])(k), "{0}[%d:]" % k,
                               "rest drop skip tail without leading remove", ()))
        for pn, (pat, pw) in PATTERNS.items():
            self.unary.append((pn, lambda t: t == "str", _findall(pat), "re.findall(%s, {0})" % _tlit(pat), pw, ("re",)))
        self.unary = [(n, ok, f, code, self.nw(w), imp) for n, ok, f, code, w, imp in self.unary]
        self.binary = [(n, ok, f, code, self.nw(w), c) for n, ok, f, code, w, c in BINARY]
        # a remainder says 'even' or 'odd' only when it is by 2 (C8h): by anything else it is a remainder
        self._mod_other_nw = self.nw("remainder modulo divisible multiple digit digits")
        self.ternary =[(n, ok, f, code, self.nw(w), imp) for n, ok, f, code, w, imp in TERNARY]

    def nw(self, words):
        """(the request's words this move names, the name's words it names), as bit masks"""
        ws = {stem(w) for w in words.split()}
        if not hasattr(self, "reqwords"):
            self.reqwords = sorted(self.words)[:60]
        rm = sum(1 << i for i, w in enumerate(self.reqwords) if w in ws)
        nm = sum(1 << i for i, w in enumerate(self.namewords) if any(wmatch(w, u) for u in ws))
        return (rm, nm)

    def key(self, x):
        """programs that read different inputs, or name different words of the name, are never merged"""
        return (repr(x.t), x.uses, x.nmask if self.outer is None else 0, tuple(norm(v) for v in x.val))

    def rank(self, x):
        """what decides between two programs that give the same values: in a comprehension's body, size (and lossy moves)

        only, since the words a program names count for the whole program, not a part of it"""
        if self.outer is not None:
            return (0, x.size + x.pen)
        return (0, x.cost)

    def choice(self, x):
        """the final choice among programs that give every example: the one naming more of the name's words, then cost"""
        return (len(self.namewords) - bin(x.nmask).count("1"), x.cost, x.size)

    def time_up(self):
        return time.time() > self.deadline or len(self.seen) >= self.cap or mem_over()

    def add(self, x):
        _WORK["bank"] += 1
        _WORK["last"] = "bank"
        if x.t in (None, "?") or all(v is ERR for v in x.val):
            return None
        k = self.key(x)                              # programs reading different inputs are not merged
        o = self.seen.get(k)
        if o is not None:
            if self.ex is not None and as_described(x, o) and len(self.subalts.setdefault(k, [])) < 2:
                self.subalts[k].append(x)             # a part as plain and as described as the kept one: a rival inside
            if self.ex is not None and fits_all(x, self.ex):
                al = self.alts.setdefault(k, [])     # rivals that also give the examples: kept to compare
                for y in (o, x):
                    if len(al) < 10 and all(y is not z for z in al):
                        al.append(y)
            rx, ro = self.rank(x), self.rank(o)
            if rx[0] < ro[0] or (rx[0] == ro[0] and rx[1] < ro[1] - 1e-9):
                o.dead = True
                self.seen[k] = x
                self.lv.setdefault(x.size, []).append(x)
                return x
            if self.ex is not None and bin(x.uses).count("1") > 1 and \
                    not matters(lambda inp: evalx(o, inp), self.ex, o.uses) and matters(lambda inp: evalx(x, inp), self.ex, x.uses):
                o.dead = True                        # the kept one only seemed to read an input: the one that does replaces it
                self.seen[k] = x
                self.lv.setdefault(x.size, []).append(x)
                return x
            return None
        self.seen[k] = x
        self.lv.setdefault(x.size, []).append(x)
        return x

    def alive(self, size):
        return [x for x in self.lv.get(size, []) if not x.dead]

    def by_type(self, size):
        g = {}
        for x in self.alive(size):
            g.setdefault(repr(x.t), []).append(x)
        return g

    def grow(self, size, lambdas=False):
        """every program of this many nodes: the moves that are strong evidence first, the weak ones (special-purpose,

        lossy, bits) after, unless asked for - when the bound cuts a size short, what it cuts is the weak evidence"""
        if size == 1:
            return
        def named(m):
            return bool(m[4][0] or m[4][1])
        weak_u = [u for u in self.unary if not named(u) and weak_name(u[0])]
        weak_b = [b for b in self.binary if not named(b) and weak_name(b[0])]
        strong_u = sorted((u for u in self.unary if u not in weak_u), key=lambda m: not named(m))   # named first
        strong_b = sorted((b for b in self.binary if b not in weak_b), key=lambda m: not named(m))
        self._grow(size, strong_u, strong_b, True, lambdas)
        if not self.time_up():
            self._grow(size, weak_u, weak_b, False, False)

    def _grow(self, size, unary, binary, rest, lambdas):
        for name, ok, f, code, nw, imp in unary:
            for x in self.alive(size - 1):
                if ok(x.t) and (x.inp or self.outer is not None) and canonical(name, x):
                    vals = tuple(_ap(f, v) for v in x.val)
                    if not nw[0] and (_same_vals(vals, x.val) or (x.op[0] == "u" and _same_vals(vals, x.args[0].val))):
                        continue                          # it changes nothing the examples show (int(str(n))), unless asked
                    self.add(X(("u", name, code, f), [x], vals, size, x.inp, nw, imp))
            if self.time_up():
                return
        for a in range(1, size - 1):
            b = size - 1 - a
            ga, gb = self.by_type(a), self.by_type(b)
            for name, ok, f, code, nw, comm in binary:
                if comm and a > b:
                    continue
                for ta, xs in ga.items():
                    for tb, ys in gb.items():
                        if not ok(xs[0].t, ys[0].t):
                            continue
                        for x in xs:
                            for y in ys:
                                if comm and a == b and id(x) > id(y):
                                    continue
                                if not (x.inp or y.inp):
                                    continue
                                vals = tuple(_ap(f, p, q) for p, q in zip(x.val, y.val))
                                if not nw[0] and (_same_vals(vals, x.val) or _same_vals(vals, y.val)):
                                    continue              # x | 0, x + 0, x | x: it changes nothing the examples show
                                self.add(X(("b", name, code, f), [x, y], vals, size, True,
                                           self._mod_other_nw if name == "mod" and not (_unouter(y).op[0] == "const" and
                                                                                        _unouter(y).op[1] == 2)
                                           else nw))
                            if self.time_up():
                                return
        if not rest:
            return
        for combo in _splits(size - 1, 3):                # chained comparisons: lo <= x <= hi (three single values)
            if max(combo[1:]) > 1 or combo[0] > 2:
                continue
            # a read of the world (a file's text, a fetched page) is a leaf too: the input as it is read
            pools = [[x for x in self.alive(s) if (is_num(x.t) or x.t == "str") and (s == 1 or x.op[1] in EDGE_READS)]
                     for s in combo]
            for args in itertools.product(*pools):
                if not any(x.inp for x in args) or not args[1].live:
                    continue
                for name, ok, f, code, nw, imp in self.ternary:
                    if ok(*[x.t for x in args]):
                        self.add(X(("b", name, code, f), list(args),
                                   tuple(_ap(f, *vs) for vs in zip(*[x.val for x in args])), size, True, nw, imp))
            if self.time_up():
                return
        for part in self.parts:                           # the project's functions and the composed ones, where inputs fit
            k = part["arity"]
            if not part.get("types") and size > 3:
                continue                                  # a part the tests show no inputs for: tried on small values only
            if k == 1:
                for x in self.alive(size - 1):
                    if part_fits(part, [x.t]):
                        self.add(X(("p", part["name"], part["code"], part["fn"]), [x], tuple(_ap(part["fn"], v) for v in x.val), size,
                                   x.inp, self.nw(part["words"]), part["imports"]))
            elif k in (2, 3):
                for combo in _splits(size - 1, k):
                    if 0 in combo or max(combo) > 2:
                        continue
                    pools = [self.alive(s) for s in combo]
                    for args in itertools.product(*pools):
                        if not any(x.inp for x in args) or not part_fits(part, [x.t for x in args]):
                            continue
                        self.add(X(("p", part["name"], part["code"], part["fn"]), list(args),
                                   tuple(_ap(part["fn"], *vs) for vs in zip(*[x.val for x in args])), size, True,
                                   self.nw(part["words"]), part["imports"]))
                        if self.time_up():
                            return
        if lambdas:
            self.grow_lambdas(size)

    def grow_lambdas(self, size):
        for a in range(1, min(L_MAX, size - 3) + 1):
            b = size - 1 - a
            if b < 2:
                continue
            for L in sorted((L for L in self.alive(a) if is_iter(L.t) and L.inp), key=lambda x: x.cost)[:L_COUNT]:
                inner = self.inner(L, INNER_SEQ if L.size == 1 else INNER_MAX)   # an input list: tests of 5
                if inner is None:
                    continue
                bank, rows = inner
                for body in bank.alive(b):
                    if not body.inp:                       # a body that never reads the element is not a comprehension
                        continue
                    self.lambda_moves(L, body, rows, size)
                    if self.time_up():
                        return

    def inner(self, L, depth=INNER_MAX):
        key = (id(L), depth)
        if key in self.inner_cache:
            return self.inner_cache[key]
        rows = [(i, e) for i, lst in enumerate(L.val) if lst is not ERR for e in lst]
        if not rows or len(rows) > 400:
            self.inner_cache[key] = None
            return None
        bank = Bank(len(rows), min(self.deadline, time.time() + (4 if depth <= INNER_MAX else 8)),
                    INNER_CAP if depth <= INNER_MAX else 4 * INNER_CAP, self.words, self.consts, namewords=self.namewords, parts=
                    [p for p in self.parts if p["arity"] == 1], outer=self)
        bank.add(X(("var",), [], tuple(e for _i, e in rows), 1, True))
        for x in self.alive(1):                           # the function's inputs, the constants, the list itself
            if x.op[0] in ("in", "const"):
                bank.add(X(("outer", x), [], tuple(x.val[i] for i, _e in rows), 1, False, uses=x.uses))
        if L.size > 1:
            bank.add(X(("outer", L), [], tuple(L.val[i] for i, _e in rows), 1, False, uses=L.uses))
        for s in range(2, depth + 1):
            bank.grow(s)
        self.inner_cache[key] = (bank, rows)
        return self.inner_cache[key]

    def lambda_moves(self, L, body, rows, size):
        per = [[] for _ in range(self.n)]
        for (i, e), bv in zip(rows, body.val):
            per[i].append((e, bv))
        bad = {i for i, lst in enumerate(L.val) if lst is ERR}
        for k, b in enumerate(L.val):
            if b is not ERR and any(bv is ERR for _e, bv in per[k]):
                bad.add(k)

        def mk(kind, f):
            vals = tuple(ERR if k in bad else _ap(f, per[k]) for k in range(self.n))
            nw = self.nw(LAMBDAS[kind][1])
            self.add(X(("lam", kind), [L, body], vals, size, True, nw))

        mk("map", LAM_F["map"])
        bt = body.t
        if bt == "bool":
            for kind in ("filter", "anyof", "allof"):
                mk(kind, LAM_F[kind])
        if bt in ("int", "float", "str"):
            for kind in ("sortkey", "maxkey", "minkey"):
                mk(kind, LAM_F[kind])
        if elem(L.t) in ("int", "str", None) and bt not in ("?", None):
            mk("dictof", LAM_F["dictof"])


LAM_F = {  # what each comprehension gives from its (element, body value) pairs
    "map": lambda ps: [bv for _e, bv in ps],
    "filter": lambda ps: [e for e, bv in ps if bv],
    "anyof": lambda ps: any(bv for _e, bv in ps),
    "allof": lambda ps: all(bv for _e, bv in ps),
    "sortkey": lambda ps: [e for e, _bv in sorted(ps, key=lambda p: p[1])],
    "maxkey": lambda ps: max(ps, key=lambda p: p[1])[0] if ps else 1 / 0,
    "minkey": lambda ps: min(ps, key=lambda p: p[1])[0] if ps else 1 / 0,
    "dictof": lambda ps: {e: bv for e, bv in ps},
}


def evalx(x, inp, v=None, sub=None):
    """a composed expression's value on other inputs (the program run in-process, every move as in the search); sub: a

    part of it replaced by a rival that gave the same values on the examples"""
    if sub and id(x) in sub:
        return evalx(sub[id(x)], inp, v)             # the rival as itself (it may contain the part it replaces)
    k = x.op[0]
    if k == "in":
        return inp[x.op[1]]
    if k == "const":
        return x.op[1]
    if k == "var":
        return v
    if k == "outer":
        return evalx(x.op[1], inp, None, sub)
    if k == "body":                                   # its own goal: the element first, then the function's inputs
        return evalx(x.op[1], [v] + list(inp))
    if k == "loop":
        return _run_loop(x, inp)
    if k == "guard":
        return _run_guard(x, inp)
    if k == "zip":
        la, lb = evalx(x.args[0], inp, None, sub), evalx(x.args[1], inp, None, sub)
        if la is ERR or lb is ERR or not isinstance(la, list) or not isinstance(lb, list) or len(la) != len(lb):
            return ERR
        out = [evalx(x.op[1], [a, b] + list(inp)) for a, b in zip(la, lb)]
        return ERR if any(v is ERR for v in out) else out
    if k == "scan":                                   # the state so far and the next element give the next state
        lst = evalx(x.args[0], inp, None, sub)
        if lst is ERR or not isinstance(lst, (list, tuple, str)):
            return ERR
        out, acc = [], None
        for i, e in enumerate(lst):
            acc = e if i == 0 else evalx(x.op[1], [acc, e] + list(inp))
            if acc is ERR:
                return ERR
            out.append(acc)
        return out
    if k in ("u", "b", "p"):
        return _ap(x.op[3], *[evalx(a, inp, v, sub) for a in x.args])
    if k == "lam":
        L, body = x.args
        lst = evalx(L, inp, None, sub)
        if lst is ERR:
            return ERR
        try:
            ps = [(e, evalx(body, inp, e, sub)) for e in lst]
        except TypeError:
            return ERR
        if any(bv is ERR for _e, bv in ps):
            return ERR
        return _ap(LAM_F[x.op[1]], ps)
    return ERR


def eval_steps(steps, inp):
    for c, e in steps:
        if c is None or evalx(c, inp) is True:
            return evalx(e, inp)
    return ERR


def matters(run, ex, which=None):
    """every input matters: given another example's value for that input, the program's answer changes for some example.

    An input the examples never vary is not judged (they cannot show it)."""
    base = [run(list(a)) for a, _o, _t in ex]
    for i in range(len(ex[0][0])):
        if which is not None and not (which >> i) & 1:
            continue
        others = {repr(a[i]): a[i] for a, _o, _t in ex}
        if len(others) < 2:
            continue
        moved = False
        for j, (a, _o, _t) in enumerate(ex):
            for key, val in others.items():
                if key == repr(a[i]):
                    continue
                b = list(a)
                b[i] = val
                got = run(b)
                if (got is ERR) != (base[j] is ERR) or (got is not ERR and not same(got, base[j]) and not same(base[j], got)):
                    moved = True
                    break
            if moved:
                break
        if not moved:
            return False
    return True


def _same_vals(a, b):
    """the same values on every example (a number cast to another number type with the same value counts as the same)"""
    def eq(p, q):
        if isinstance(p, (int, float)) and isinstance(q, (int, float)) and not isinstance(p, bool) and not isinstance(q, bool):
            return p == q
        return norm(p) == norm(q) and type(p) is type(q)
    return len(a) == len(b) and all(eq(p, q) for p, q in zip(a, b))


def canonical(name, x):
    """one way to write each thing: no move on its own result where that adds nothing (sorted(sorted(x)), x[::-1][::-1]),

    no slice of a slice (one slice says it)"""
    inner = x.op[1] if x.op[0] == "u" else None
    if inner is None:
        return True
    if name == inner and (name in IDEMPOTENT or name in INVOLUTION):
        return False
    if re.match(r"(take|drop)\d", name) and re.match(r"(take|drop)\d", inner):
        return False
    if inner in REORDER and name in ORDER_FREE:       # sum(sorted(x)) is sum(x): the order was never used
        return False
    if inner in ("sorted", "sorted_desc") and name in ("at0", "at-1"):
        return False                                  # sorted(x)[0] is min(x)
    if inner == "take1" and name in ("sum", "max", "min", "mean", "median"):
        return False                                  # a summary of a one-element slice is that element
    return True


REORDER = {"sorted", "sorted_desc", "reversed", "unique"}
ORDER_FREE = {"sum", "len", "max", "min", "mean", "median", "nunique", "counts", "any", "all", "empty", "sorted", "sorted_desc",
              "unique"}


def _splits(total, k):
    if k == 1:
        yield (total,)
        return
    for i in range(1, total):
        for rest in _splits(total - i, k - 1):
            yield (i,) + rest


def part_fits(part, tys):
    want = part.get("types")
    return bool(want) and all(compat(w, t) for w, t in zip(want, tys))


def compat(w, t):
    """a value of shape t may be given where the part was seen taking shape w (None in w: any)"""
    if w is None:
        return True
    if t is None:
        return False
    if w == t or (is_num(w) and is_num(t)):
        return True
    if isinstance(w, tuple) and isinstance(t, tuple) and w[0] == t[0] and len(w) == len(t):
        return all(compat(a, b) or b is None for a, b in zip(w[1:], t[1:]))
    return False


# ================================================================ writing the program out
def var_name(L, params):
    e = elem(L.t)
    v = "ch" if L.t == "str" else "word" if e == "str" else "x" if e in ("int", "float") else "item"
    while v in params:
        v += "_"
    return v


HOIST = {}            # while a chain is written out: the steps already named on their own lines
STEP_NAMES = {"max": "largest", "min": "smallest", "sum": "total", "len": "count", "mean": "average", "median": "middle",
              "sub": "difference", "add": "total", "mul": "product", "div": "ratio", "words": "words", "lower": "lowered",
              "counts": "counts", "sorted": "ordered", "map": "values", "filter": "kept", "concat": "text", "lconcat": "items"}


def step_name(x, taken):
    k = x.op[1] if x.op[0] in ("u", "b", "p", "lam") else ""
    base = (k if x.op[0] == "p" else STEP_NAMES.get(k, "part")).lower()
    nm, i = base, 2
    while nm in taken:
        nm, i = "%s%d" % (base, i), i + 1
    return nm


def code(x, names, v=None):
    if id(x) in HOIST:
        return HOIST[id(x)]
    k = x.op[0]
    if k == "in":
        return names[x.op[1]]
    if k == "const":
        c = x.op[1]
        if isinstance(c, float) and c == math.pi:
            return "math.pi"
        if isinstance(c, (int, float)) and not isinstance(c, bool) and c < 0:
            return "(%r)" % c                         # -1 ** x is -(1 ** x): a negative constant is written in parentheses
        return repr(c)
    if k == "var":
        return v
    if k == "outer":
        return code(x.op[1], names)
    if k == "body":
        return code(x.op[1], [v] + list(names))
    if k == "zip":
        a, b = ("x", "y") if not {"x", "y"} & set(names) else ("x_", "y_")
        return "[%s for %s, %s in zip(%s, %s)]" % (bare(code(x.op[1], [a, b] + list(names))), a, b, code(x.args[0], names),
                                                   code(x.args[1], names))
    if k == "loop":
        st = code(x.args[0], names)
        return "<while %s: %s = %s>" % (bare(code(x.op[2], [st])), st, bare(code(x.op[3], [st])))
    if k == "guard":
        return "<%s, or None where it fails%s>" % (bare(code(x.op[1], names)),
                                                    "" if x.op[2] is None else " or not " + bare(code(x.op[2], ["value"])))
    if k == "scan":
        L = x.args[0]
        vn = var_name(L, names)
        acc = "acc" if "acc" not in names else "so_far"
        return "list(itertools.accumulate(%s, lambda %s, %s: %s))" % (code(L, names), acc, vn,
                                                                     bare(code(x.op[1], [acc, vn] + list(names))))
    if k in ("u", "b"):
        return x.op[2].format(*[code(a, names, v) for a in x.args])
    if k == "p":
        return "%s(%s)" % (x.op[2], ", ".join(code(a, names, v) for a in x.args))
    if k == "lam":
        L, body = x.args
        vn = var_name(L, names)
        return LAMBDAS[x.op[1]][0].format(v=vn, L=code(L, names), b=code(body, names, vn))
    raise ValueError(k)


def bare(s):
    """drop one pair of parentheses around a whole expression"""
    if s.startswith("(") and s.endswith(")"):
        depth = 0
        for i, ch in enumerate(s):
            depth += ch == "("
            depth -= ch == ")"
            if depth == 0 and i < len(s) - 1:
                return s
        return s[1:-1]
    return s


def moves_of(x, out=None):
    out = [] if out is None else out
    for a in x.args:
        if isinstance(a, X):
            moves_of(a, out)
    if x.op[0] in ("u", "b", "p"):
        out.append(x.op[1])
    elif x.op[0] == "lam":
        out.append(x.op[1])
    elif x.op[0] == "body":
        moves_of(x.op[1], out)
    elif x.op[0] == "scan":
        out.append("scan")
        moves_of(x.op[1], out)
    elif x.op[0] == "zip":
        out.append("zip")
        moves_of(x.op[1], out)
    elif x.op[0] == "loop":
        out.append("while")
        for z in x.op[2:5]:
            if z is not None:
                moves_of(z, out)
    elif x.op[0] == "guard":
        out.append("try")
        for z in x.op[1:3]:
            if z is not None:
                moves_of(z, out)
    return out


# ================================================================ composing one goal
def leaves_for(goal, bank, consts):
    ex = goal["examples"]
    n = len(ex)
    k = len(ex[0][0])
    for i in range(k):
        bank.add(X(("in", i), [], tuple(e[0][i] for e in ex), 1, True, uses=1 << i))
    texts = []
    for e in ex:
        _texts(list(e[0]), texts, 20000)
    texty = bool(texts)                               # a spelled word can only point at text the inputs hold (or name)
    for c in consts:                                  # a text the function looks for says the words it spells
        named = bank.nw(" ".join(re.findall(r"[a-z]+", c.lower()))) if texty and isinstance(c, str) and c.strip() \
            else (0, 0)
        bank.add(X(("const", c), [], tuple(c for _ in range(n)), 1, False, named))


def const_pool(goal, words_text):
    ex = goal["examples"]
    pool = [0, 1, 2, -1, "", " ", None, True, False, []]
    name_parts = [w for w in re.sub(r"([a-z])([A-Z])", r"\1 \2", goal["name"]).replace("_", " ").lower().split()]
    for w in re.findall(r"[a-z]+", _strip_examples(words_text, goal["name"]).lower()) + name_parts:
        v = NUMBER_WORDS.get(w)
        if v is not None and v not in pool:
            pool.append(v)
            if 0 <= v <= 9 and Field(str(v)) not in pool:
                pool.append(Field(str(v)))           # "zeros": the digit as text too
    for w in name_parts:                              # the name's words are texts the function may look for
        if len(w) > 1 and w not in NAME_STOP and not NUMBER_WORDS.get(w):
            for form in (w, w.capitalize()):
                if form not in pool:
                    pool.append(Field(form))
    for tag in re.findall(r"\b([a-z]+) tags?\b", (words_text or "").lower()):
        for form in ("<%s>" % tag, "</%s>" % tag):    # "the title tag": its opening and closing marks
            if form not in pool:
                pool.append(Field(form))
    if all(isinstance(o, bool) for _a, o, _t in ex):  # a yes/no answer: the values the data shows are candidate boundaries
        seen_n = []

        def nums(v):
            if isinstance(v, bool):
                return
            if isinstance(v, (int, float)):
                yield v
            elif isinstance(v, (list, tuple)):
                for y in v:
                    yield from nums(y)
            elif isinstance(v, dict):
                for y in v.values():
                    yield from nums(y)
        for args, _o, _t in ex:
            for v in itertools.chain(*[nums(a) for a in args]):
                if v not in seen_n and v not in pool:
                    seen_n.append(v)
        pool += [Boundary(v) if isinstance(v, int) else v for v in seen_n[:8]]
    for m in re.findall(r"(?<![\w.'\"])(-?\d+(?:\.\d+)?)(?![\w.])", _strip_examples(words_text, goal["name"])):
        v = float(m) if "." in m else int(m)
        if v not in pool:
            pool.append(v)
    seen = set()

    def runs(v):
        if isinstance(v, str):
            for r in re.findall(r"[^\w\s]{1,3} ?|\s+(?=\S)", v):
                yield r
        elif isinstance(v, (list, tuple)):
            for y in v:
                yield from runs(y)
        elif isinstance(v, dict):
            for y in list(v.keys()) + list(v.values()):
                yield from runs(y)
    for args, out, _tol in ex:
        for r in itertools.chain(runs(out), *[runs(a) for a in args]):
            if r not in seen and r not in pool and len(seen) < 8:
                seen.add(r)
                pool.append(r)
    def fields(v):                                    # the names a record's fields go by are constants of the code
        if isinstance(v, dict):
            for k in v:
                if isinstance(k, str):
                    yield k
            for y in v.values():
                yield from fields(y)
        elif isinstance(v, (list, tuple)):
            for y in v:
                yield from fields(y)
    named = []
    for args, _o, _t in ex:
        for k in itertools.chain(*[fields(a) for a in args]):
            if k not in named and k not in pool:
                named.append(k)
    pool += [Field(k) for k in named[:10]]
    reps = {}
    for _a, out, _t in ex:                            # a value the function gives for more than one input is a constant of it
        if isinstance(out, (str, int, float)) and not isinstance(out, bool):
            reps[repr(out)] = reps.get(repr(out), 0) + 1
            if reps[repr(out)] == 2 and not any(type(c) is type(out) and c == out for c in pool):
                pool.append(out)
    if any(isinstance(out, float) or tol is not None for _a, out, tol in ex):
        pool.append(math.pi)
    return pool


NUMBER_WORDS = {"zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
                "ten": 10, "twelve": 12, "hundred": 100, "thousand": 1000, "dozen": 12, "half": 2, "halve": 2, "halves": 2,
                "double": 2, "twice": 2, "square": 2, "squares": 2, "squared": 2, "triple": 3, "thrice": 3, "cube": 3,
                "cubes": 3, "cubed": 3, "third": 3, "thirds": 3, "quarter": 4, "quarters": 4, "percent": 100,
                "percentage": 100, "byte": 255, "bytes": 255, "nibble": 15, "zeros": 0}


class Boundary(int):
    """a number the examples show, offered as a boundary: fine to compare against with < or <=, a lookup with == or !="""


class Field(str):
    """a record's field name: a constant to read a field by, not a separator or a text to put in"""


def _strip_examples(text, name):
    return re.sub(r"\b%s\s*\([^)]*\)\s*(?:==|->|=>|returns?|gives?)\s*\S+" % re.escape(name), " ", text or "")


def fits_all(x, ex):
    return all(same(v, out, tol) for v, (_a, out, tol) in zip(x.val, ex))


def mask_of(x, ex):
    m = 0
    for i, (v, (_a, out, tol)) in enumerate(zip(x.val, ex)):
        if same(v, out, tol):
            m |= 1 << i
    return m


def decision_list(bank, ex, every=0):
    """if c1: return e1 / if c2: return e2 / return e3 - each branch resting on two examples, or one under an emptiness test"""
    n = len(ex)
    full = (1 << n) - 1
    best_by_mask = {}
    for x in bank.seen.values():
        if x.dead or not x.inp and x.op[0] != "const":
            continue
        m = mask_of(x, ex)
        if m and (m not in best_by_mask or x.cost < best_by_mask[m].cost):
            best_by_mask[m] = x
    conds = [x for x in bank.seen.values() if not x.dead and x.t == "bool" and x.inp and x.size <= 5
             and all(v is not ERR for v in x.val)]
    conds.sort(key=lambda x: x.cost)
    conds = [(c, sum(1 << i for i, v in enumerate(c.val) if v), c.op[0] == "u" and c.op[1] == "empty") for c in conds[:900]]
    masks = sorted(best_by_mask.items(), key=lambda kv: kv[1].cost)
    covers = {}

    def cover(rest):
        if rest not in covers:
            covers[rest] = next((e for m, e in masks if m & rest == rest), None)
        return covers[rest]

    opts_cache = {}

    def options(rest):
        if rest in opts_cache:
            return opts_cache[rest]
        out = []
        for c, cm, guard in conds:
            tm = cm & rest
            if not tm or tm == rest or bin(tm).count("1") < (1 if guard else 2):
                continue
            e = cover(tm)
            if e is not None:
                out.append((c.cost + e.cost, c, e, tm))
        out.sort(key=lambda o: o[0])
        opts_cache[rest] = out[:12]
        return opts_cache[rest]

    best = [None]

    def dfs(rest, steps, cost, depth):                # the cheapest decision list, searched (not greedy)
        if bin(rest).count("1") >= 2:
            e = cover(rest)
            used = e.uses if e is not None else 0
            for c_, e_ in steps:
                used |= c_.uses | e_.uses
            if e is not None and used & every == every and (best[0] is None or cost + e.cost < best[0][0]):
                best[0] = (cost + e.cost, steps + [(None, e)])
        if depth == 3:
            return
        for oc, c, e, tm in options(rest):
            if best[0] is not None and cost + oc >= best[0][0]:
                break
            dfs(rest & ~tm, steps + [(c, e)], cost + oc, depth + 1)

    dfs(full, [], 0.0, 0)
    return best[0][1] if best[0] else None


def _mirror(v):
    if isinstance(v, str):
        return "".join(chr(ord("a") + ord("z") - ord(c)) if "a" <= c <= "z" else
                       chr(ord("A") + ord("Z") - ord(c)) if "A" <= c <= "Z" else c for c in v)
    if isinstance(v, list):
        return [_mirror(y) for y in v]
    return v


def probes(ex):
    """other inputs made from the examples' own: lists reversed or joined, words in another order, texts joined"""
    ins = [list(a) for a, _o, _t in ex]
    out = []
    for a in ins:
        for i, v in enumerate(a):
            b = list(a)
            if isinstance(v, list) and len(v) > 1:
                b[i] = v[::-1]
            elif isinstance(v, str) and len(v.split()) > 1:
                b[i] = " ".join(v.split()[::-1])
            elif isinstance(v, str) and len(v) > 1:
                b[i] = v[::-1]
            else:
                continue
            out.append(b)
    for a in ins:
        for c in ins:
            if a is c:
                continue
            b, moved = list(a), False
            for i, (v, w) in enumerate(zip(a, c)):
                if isinstance(v, list) and isinstance(w, list):
                    b[i], moved = v + w, True
                elif isinstance(v, str) and isinstance(w, str) and v and w:
                    b[i], moved = (v + " " + w) if (" " in v or " " in w) else v + w, True
            if moved:
                out.append(b)
    if len(ins[0]) > 1:                               # inputs crossed between examples (a from one, b from another)
        for combo in itertools.product(*[sorted({repr(a[i]): a[i] for a in ins}.values(), key=repr) for i in range(len(ins[0]))]):
            if list(combo) not in ins:
                out.append(list(combo))
    for i in range(len(ins[0])):                      # lists made from pairs of elements of different examples, both orders
        lists = [a[i] for a in ins if isinstance(a[i], list)]
        if len(lists) < 2:
            continue
        pool = [e for lst in lists for e in lst]
        pairs = 0
        for p_, q_ in itertools.permutations(range(len(pool)), 2):
            if pairs >= 16:
                break
            if repr(pool[p_]) == repr(pool[q_]):
                continue
            b = list(ins[0])
            b[i] = [pool[p_], pool[q_]]
            if b not in ins and b not in out:
                out.append(b)
                pairs += 1
    for a in ins:                                     # letters mirrored: alphabetical order reversed, structure kept
        b = [_mirror(v) for v in a]
        if b != a and b not in out:
            out.insert(0, b)
    for a in ins:                                     # numbers next to the examples' own
        for i, v in enumerate(a):
            if isinstance(v, int) and not isinstance(v, bool):
                for w in (v + 1, v + 2, 2 * v + 1):
                    b = list(a)
                    b[i] = w
                    out.append(b)
    return out[:80]


def disagreement(best, rivals, ex):
    """the first rival that answers differently from the chosen program on an input made from the examples"""
    if not rivals:
        return None
    for p in probes(ex):
        bv = evalx(best, p)
        _WORK["probe"] += 1
        _WORK["last"] = "probe"
        if bv is ERR:
            continue
        for y in rivals:
            yv = evalx(y, p)
            _WORK["probe"] += 1
            if yv is not ERR and not same(yv, bv) and not same(bv, yv):
                return y, p, bv, yv
    return None


def as_described(x, o):
    """x gave the same values as the kept o, and is as plain (one node more at most, no extra lossy move) and names at least

    the words o names: a real rival, not noise"""
    return (x is not o and x.size <= o.size + 1 and x.pen <= o.pen + 1e-9 and x.cost < o.cost + 1.0 and (x.nmask & o.nmask) == o.nmask
            and (x.rmask & o.rmask) == o.rmask)


def inner_disagreement(best, bank, ex):
    """a part of the chosen program replaced by its rival (same values on the examples): does the whole program answer

    differently on an input made from the examples? Observational equivalence keeps one of the two; this looks again."""
    nodes, stack = [], [best]
    while stack:
        x = stack.pop()
        if x.op[0] in ("u", "b", "p", "lam"):
            nodes.append(x)
        if x.op[0] == "lam":
            stack.append(x.args[0])                   # the body belongs to its own search
        else:
            stack.extend(a for a in x.args if isinstance(a, X))
    pn = ["_in%d" % i for i in range(len(ex[0][0]))]
    ps = probes(ex)
    for node in nodes:
        for alt in bank.subalts.get(bank.key(node), []):
            if alt is node or not as_described(alt, node):
                continue                              # judged against the part kept now
            nc, ac = code(node, pn), code(alt, pn)
            if wraps(nc, ac):
                continue                              # the same part with a wrapper added is not a rival
            for p in ps:
                bv = evalx(best, p)
                if bv is ERR:
                    continue
                yv = evalx(best, p, sub={id(node): alt})
                if yv is not ERR and not same(yv, bv) and not same(bv, yv):
                    return ("sub", node, alt), p, bv, yv
    return None


NAME_STOP = {"get", "make", "calc", "calculate", "compute", "do", "to", "of", "the", "a", "an", "and", "in", "on", "for", "by",
             "from", "with", "my", "fn", "func", "function", "helper", "value", "result"}


def wmatch(w, u):
    """a word of the name and a word of a move or a field: the same stem, or one begins the other (pric / price)"""
    return w == u or (len(w) >= 4 and len(u) >= 4 and (u.startswith(w) or w.startswith(u)))


def name_words(name):
    """the words of a function's name (snake_case or camelCase), as stems, without the words every name has"""
    parts = re.sub(r"([a-z])([A-Z])", r"\1 \2", name).replace("_", " ").lower().split()
    out = []
    for w in parts:
        s = stem(w)
        if w not in NAME_STOP and len(w) > 1 and s not in out:
            out.append(s)
    return out[:6]


def pick(hits, bank):
    """among the programs that give every example and cost at most one more than the cheapest, the one naming the most

    words of the function's name (then cost): the name decides close calls, never against a much plainer program. A program

    that is weak evidence (a lossy move no word excused) is chosen only when no program that is not fits: a weak fit is not

    a fit beside a strong one (C10f: skew_ratio's (max - mean) / (max - min) lost to a cheaper entropy that fit by chance)"""
    strong = [x for x in hits if not x.lossy]
    hits = strong or hits
    low = min(x.cost for x in hits)
    return min((x for x in hits if x.cost <= low + 1.0), key=bank.choice)


def decide(hits, bank, ex, names, ok):
    """the choice among programs that give every example, and the ask when rivals as plain answer differently elsewhere"""
    best = pick(hits, bank)
    bc = code(best, names)
    namewords = bank.namewords

    def rival(y):                                     # a program described as well as the chosen one, as plain
        says_more = (y.nmask & best.nmask) == best.nmask and y.nmask != best.nmask and             (best.waived or not y.waived)            # more of the name said, and not only by an excused weak move
        if y is best or y.pen > best.pen + 1e-9 or (y.waived and not best.waived):
            return False
        if not says_more and (y.cost > best.cost + AMBIG or y.size > best.size + 1):
            return False
        if says_more and y.cost > best.cost + 2 * AMBIG + 1.0:
            return False                              # a plainer program over one that says more of the name: asked
        if (y.nmask & best.nmask) != best.nmask or (y.rmask & best.rmask) != best.rmask:
            return False
        yc = code(y, names)
        return not wraps(bc, yc) and ok(y)            # not the same program with a wrapper added
    seen_r, rivals = set(), []
    for y in hits + [z for al in bank.alts.values() for z in al]:
        if id(y) not in seen_r and rival(y):
            seen_r.add(id(y))
            rivals.append(y)
    amb = disagreement(best, rivals, ex) or inner_disagreement(best, bank, ex)
    if amb:
        return {"kind": "ambiguous", "x": best, "rival": amb[0], "probe": amb[1], "va": amb[2], "vb": amb[3], "bank": bank}
    w = unsaid_in_data(best, bank) if getattr(bank, "depth", 0) == 0 else None
    if w:
        return {"kind": "unsaid", "x": best, "word": w, "bank": bank}
    return {"kind": "expr", "x": best, "steps": None, "bank": bank, "covered": bin(best.nmask).count("1") == len(namewords)}


def _walk_x(x, seen=None):
    seen = set() if seen is None else seen
    if id(x) in seen:
        return
    seen.add(id(x))
    yield x
    for a in list(x.args) + [o for o in x.op if isinstance(o, X)]:
        if isinstance(a, X):
            yield from _walk_x(a, seen)


def _texts(v, out, cap=300000):
    if sum(len(t) for t in out) > cap:
        return
    if isinstance(v, str):
        out.append(v)
    elif isinstance(v, dict):
        for k, u in v.items():
            _texts(k, out, cap)
            _texts(u, out, cap)
    elif isinstance(v, (list, tuple)):
        for u in v[:2000]:
            _texts(u, out, cap)


def unsaid_in_data(best, bank):
    """a word of the function's name that the inputs (or the files and pages they name) contain, and that the chosen

    program neither names by a move nor looks for as a text: the name points at something there, and the fit ignores it"""
    nws = bank.namewords
    said = {w for i, w in enumerate(nws) if best.nmask >> i & 1}
    for z in _walk_x(best):
        if z.op[0] == "const" and isinstance(z.op[1], str):
            said |= {stem(t) for t in re.findall(r"[a-z]+", z.op[1].lower())}
    unsaid = [w for w in nws if w not in said]
    if not unsaid:
        return None
    texts = []
    for x in list(bank.alive(1)) + list(bank.alive(2)):
        if x.op[0] == "in" or (x.op[0] == "u" and x.op[1] in ("readtext", "readlines", "readjson", "fetch")):
            _texts(list(x.val), texts)
    data = {stem(t) for txt in texts for t in re.findall(r"[a-z]+", txt.lower())}
    return next((w for w in unsaid if any(wmatch(w, u) for u in data)), None)


def _vkey(vals):
    """values as a key: numbers by value (5 and 5.0 alike), the rest as they are"""
    out = []
    for v in vals:
        if v is ERR:
            return None
        if isinstance(v, (int, float)) and not isinstance(v, bool):
            out.append(("n", round(float(v), 7)))
        else:
            out.append(norm(v))
    return tuple(out)


def _needs(name, outs, pv):
    """given one side's values, the other side's values that make the join give the answer: (values, this side first)"""
    num = all(isinstance(o, (int, float)) and not isinstance(o, bool) for o in outs) and \
        all(isinstance(p, (int, float)) and not isinstance(p, bool) for p in pv)
    if name in ("add", "sub", "mul", "div") and not num:
        return
    try:
        if name == "add":
            yield [o - p for o, p in zip(outs, pv)], True
        elif name == "sub":
            yield [p - o for o, p in zip(outs, pv)], True            # a - b = o
            yield [o + p for o, p in zip(outs, pv)], False           # b - a = o
        elif name == "mul":
            if all(p != 0 for p in pv):
                yield [o / p for o, p in zip(outs, pv)], True
        elif name == "div":
            if all(o != 0 for o in outs):
                yield [p / o for o, p in zip(outs, pv)], True        # a / b = o
            if all(p != 0 for p in pv):
                yield [o * p for o, p in zip(outs, pv)], False       # b / a = o
        elif name in ("concat", "lconcat"):
            kind = str if name == "concat" else list
            if all(isinstance(o, kind) and isinstance(p, kind) for o, p in zip(outs, pv)):
                if all(o[:len(p)] == p for o, p in zip(outs, pv)):
                    yield [o[len(p):] for o, p in zip(outs, pv)], True
                if all(len(p) <= len(o) and o[len(o) - len(p):] == p for o, p in zip(outs, pv)):
                    yield [o[:len(o) - len(p)] for o, p in zip(outs, pv)], False
    except (ZeroDivisionError, OverflowError, TypeError):
        return


def join_top(bank, ex, ok, deadline, cap=60):
    """larger code side by side: two programs of the search joined by one move. The answer and one side give the other

    side's values, which are looked up among every program kept (meet in the middle), so each side may be as large as the

    search reaches. Evidence bound: a joined program has at most two nodes per example, plus one."""
    outs = [o for _a, o, _t in ex]
    pool = sorted((x for x in bank.seen.values() if not x.dead and (x.live or x.op[0] == "const")
                   and all(v is not ERR for v in x.val)), key=lambda x: x.cost)
    idx = {}
    for x in pool:
        k = _vkey(x.val)
        if k is not None:
            lst = idx.setdefault(k, [])
            if len(lst) < 3:
                lst.append(x)
    binops = {b[0]: b for b in bank.binary}
    limit = 2 * len(ex) + 1
    hits, seen = [], set()
    for a in pool:
        if not a.inp or not a.live or a.size >= limit - 1:
            continue
        if time.time() > deadline or len(hits) >= cap:
            break
        for name in JOINS:
            _n, okf, f, cd, nw, _comm = binops[name]
            for need, a_first in _needs(name, outs, a.val):
                k = _vkey(need)
                for b in idx.get(k, []) if k is not None else []:
                    if b is a or a.size + b.size + 1 > limit:
                        continue
                    args = [a, b] if a_first else [b, a]
                    if not okf(args[0].t, args[1].t):
                        continue
                    sig = (name, id(args[0]), id(args[1]))
                    if sig in seen:
                        continue
                    seen.add(sig)
                    vals = tuple(_ap(f, p, q) for p, q in zip(args[0].val, args[1].val))
                    x = X(("b", name, cd, f), args, vals, a.size + b.size + 1, True, nw)
                    if ok(x):
                        hits.append(x)
    return hits


def _subseq(lv, o):
    """which elements of lv the answer o keeps, in order (None when o is not lv with some left out)"""
    flags, j = [], 0
    for e in lv:
        if j < len(o) and same(e, o[j]):
            flags.append(True)
            j += 1
        else:
            flags.append(False)
    return flags if j == len(o) else None


def deduce_select(goal, bank, parts, words_text, deadline, ok, L):
    """[g(x) for x in L if p(x)]: a small step g on each element whose values, with some left out, are the answer; the

    flags (kept or not) are then known, so the test p is a goal of its own"""
    ex = goal["examples"]
    outs = [o for _a, o, _t in ex]
    inner = bank.inner(L)
    if inner is None:
        return None
    ib, rows = inner
    gs = sorted((b for sz in (2, 3) for b in ib.alive(sz) if b.inp and all(v is not ERR for v in b.val)),
                key=lambda b: b.cost)[:60]
    found = []
    for g in gs:
        per = [[] for _ in ex]
        for (i, e), gv in zip(rows, g.val):
            per[i].append((e, gv))
        flags = [_subseq([gv for _e, gv in ps], o) for ps, o in zip(per, outs)]
        flat = [t for fl in flags if fl is not None for t in fl]
        if any(fl is None for fl in flags) or all(flat) or not any(flat):
            continue
        prow, keyed, clash = [], {}, False
        for (args, _o, _t), ps, fl in zip(ex, per, flags):
            for (e, _gv), t in zip(ps, fl):
                kk = repr((e,) + tuple(args))
                if kk in keyed:
                    clash = clash or keyed[kk] != t
                    continue
                keyed[kk] = t
                prow.append(((e,) + tuple(args), t, None))
        if clash or len(prow) < 2:
            continue
        vname = var_name(L, goal["params"])
        sub = {"name": goal["name"], "params": [vname] + list(goal["params"]), "examples": prow, "need": 1}
        res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=max(5.0, min(20.0, deadline - time.time() - 2)))
        if res["kind"] != "expr" or not (res["x"].uses & 1):
            continue
        bx = res["x"]
        w = X(("body", bx), [], bx.val, bx.size, True, uses=bx.uses >> 1)
        fvals = []
        for (args, _o, _t), lv in zip(ex, L.val):
            ps = [(e, evalx(w, list(args), e)) for e in lv]
            fvals.append(ERR if any(bv is ERR for _e, bv in ps) else _ap(LAM_F["filter"], ps))
        kept = X(("lam", "filter"), [L, w], tuple(fvals), 1 + L.size + w.size, True, bank.nw(LAMBDAS["filter"][1]))
        mvals = []
        for (args, _o, _t), fv in zip(ex, kept.val):
            ps = [] if fv is ERR else [(e, evalx(g, list(args), e)) for e in fv]
            mvals.append(ERR if fv is ERR or any(bv is ERR for _e, bv in ps) else _ap(LAM_F["map"], ps))
        x = X(("lam", "map"), [kept, g], tuple(mvals), 1 + kept.size + g.size, True, bank.nw(LAMBDAS["map"][1]))
        if ok(x):
            found.append(x)
        if len(found) >= 4 or time.time() > deadline - 3:
            break
    return {"kind": "cands", "xs": found} if found else None


def deduce(goal, bank, parts, words_text, deadline, ok):
    """larger code in sequence: when the answer is a list made from a list (the same length: each element turned into

    something; or some left out: a test on each), the body's values are known from the answer, so the body is a goal of its

    own, composed by the same search (and may itself be large or joined)"""
    ex = goal["examples"]
    outs = [o for _a, o, _t in ex]
    if not all(isinstance(o, list) for o in outs):
        return None
    Ls = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and is_seq(x.t) and x.size <= 3
                 and all(isinstance(v, list) for v in x.val) and any(x.val)), key=lambda x: (x.size, x.cost))
    tried, asked = 0, None
    for L in Ls:
        if time.time() > deadline - 2 or tried >= 4:
            break
        if all(len(lv) == len(o) for lv, o in zip(L.val, outs)):
            if all(same(lv, o) for lv, o in zip(L.val, outs)):
                continue
            kind, targets = "map", outs
        else:
            targets = [_subseq(lv, o) for lv, o in zip(L.val, outs)]
            flat = [t for tg in targets if tg is not None for t in tg]
            if any(tg is None for tg in targets) or all(flat) or not any(flat):
                if time.time() < deadline - 4:
                    r = deduce_select(goal, bank, parts, words_text, deadline, ok, L)
                    if r is not None:
                        return r                      # {"kind": "cands"}: weighed with every other chain
                continue
            kind = "filter"
        rows, keyed, clash = [], {}, False
        for (args, _o, tol), lv, tg in zip(ex, L.val, targets):
            for e, t in zip(lv, tg):
                k = repr((e,) + tuple(args))
                if k in keyed:
                    clash = clash or not same(keyed[k], t)
                    continue
                keyed[k] = t
                rows.append(((e,) + tuple(args), t, tol if kind == "map" else None))
        if clash or len(rows) < 2:
            continue
        tried += 1
        vname = var_name(L, goal["params"])
        sub = {"name": goal["name"], "params": [vname] + list(goal["params"]), "examples": rows, "need": 1}
        res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=max(5.0, min(22.0, deadline - time.time() - 2)))
        if res["kind"] == "ambiguous" and asked is None:
            asked = (L, kind, vname, sub, res)
            continue
        if res["kind"] != "expr" or not (res["x"].uses & 1):
            continue
        bx = res["x"]
        w = X(("body", bx), [], bx.val, bx.size, True, uses=bx.uses >> 1)
        vals = []
        for (args, _o, _t), lv in zip(ex, L.val):
            ps = [(e, evalx(w, list(args), e)) for e in lv]
            vals.append(ERR if any(bv is ERR for _e, bv in ps) else _ap(LAM_F[kind], ps))
        lam = X(("lam", kind), [L, w], tuple(vals), 1 + L.size + w.size, True, bank.nw(LAMBDAS[kind][1]))
        if ok(lam):
            return {"kind": "expr", "x": lam, "steps": None, "bank": bank,
                    "covered": bin(lam.nmask).count("1") == len(bank.namewords)}
    if asked is not None:
        L, kind, vname, sub, res = asked
        return {"kind": "ambiguous_body", "L": L, "lam": kind, "sub": sub, "res": res}
    return None


SEQ_REDUCERS = {"sum", "prod", "len", "max", "min", "mean", "median", "nunique", "any", "all", "sorted", "sorted_desc", "unique",
                "dedupe"}
SEQ_L_COUNT = 120       # lists the chain stage continues from (the cheapest)
INNER_SEQ = 5           # a step over each element of a short list (an input, its words, its letters) may be this large


def evidenced(x, n):
    """a program past the bound rests on its examples: at most two nodes per example plus one, and two more for each word of

    the request or the name it says (a described move is not a free choice)"""
    if x.size <= MAX_SIZE:
        return True
    named = bin(x.rmask).count("1") + bin(x.nmask).count("1")
    return x.size <= 2 * n + 1 + 2 * named


def seq_stage(bank, ex, ok, deadline, cap=40):
    """larger code in sequence: any list the search made (a filtered list, words, letters) is carried one step further: a

    step on each element (map) or a test on each (filter), then a summary of the result (sum, count, largest, average,

    joined into text, ...). Each step is small; the chain is as long as they are together."""
    outs = [o for _a, o, _t in ex]
    out_list = all(isinstance(o, list) for o in outs)
    reducers = [u for u in bank.unary if u[0] in SEQ_REDUCERS or u[0].startswith("join") or u[0].startswith("fold")]
    Ls = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and is_seq(x.t)
                 and all(isinstance(v, (list, tuple)) for v in x.val) and any(x.val)), key=lambda x: x.cost)[:SEQ_L_COUNT]
    target = _vkey(outs)
    hits = []
    for L in Ls:
        if time.time() > deadline or len(hits) >= cap:
            break
        inner = bank.inner(L, INNER_SEQ if L.size <= 2 else INNER_MAX)
        if inner is None:
            continue
        ib, rows = inner
        depth = INNER_SEQ if L.size <= 2 else INNER_MAX
        for body in [b for sz in range(1, depth + 1) for b in ib.alive(sz)]:
            if not body.inp or time.time() > deadline:
                continue
            per = [[] for _ in range(len(ex))]
            for (i, e), bv in zip(rows, body.val):
                per[i].append((e, bv))
            if any(bv is ERR for lst in per for _e, bv in lst):
                continue
            kinds = ["map"] + (["filter"] if body.t == "bool" else [])
            for kind in kinds:
                vals = tuple(_ap(LAM_F[kind], ps) for ps in per)
                if any(v is ERR for v in vals):
                    continue
                lam = None
                if out_list:
                    if L.size + body.size + 1 > MAX_SIZE and all(same(v, o, t) for v, (_a, o, t) in zip(vals, ex)):
                        lam = X(("lam", kind), [L, body], vals, 1 + L.size + body.size, True, bank.nw(LAMBDAS[kind][1]))
                        if ok(lam):
                            hits.append(lam)
                    continue
                vt = ty_of_vals(vals)
                for name, okr, f, cd, nw, imp in reducers:
                    if not okr(vt):
                        continue
                    rv = tuple(_ap(f, v) for v in vals)
                    k = _vkey(rv)
                    if k is None or k != target and not all(same(v, o, t) for v, (_a, o, t) in zip(rv, ex)):
                        continue
                    if 1 + L.size + body.size + 1 <= MAX_SIZE:
                        continue                          # within the bound: the search itself had it
                    if lam is None:
                        lam = X(("lam", kind), [L, body], vals, 1 + L.size + body.size, True, bank.nw(LAMBDAS[kind][1]))
                    x = X(("u", name, cd, f), [lam], rv, lam.size + 1, True, nw, imp)
                    if ok(x):
                        hits.append(x)
    return hits


def deduce_scan(goal, bank, parts, words_text, deadline, ok):
    """a loop that carries a state: when the answer is a list as long as a list the search made, starting from its first

    element, each answer is made from the previous answer and the next element: those pairs are known, so the step is a

    goal of its own (its inputs: the state so far, the element, the function's inputs)"""
    ex = goal["examples"]
    outs = [o for _a, o, _t in ex]
    if not all(isinstance(o, list) for o in outs):
        return None
    Ls = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and is_seq(x.t) and x.size <= 3
                 and all(isinstance(v, list) for v in x.val) and any(len(v) >= 2 for v in x.val)), key=lambda x: (x.size, x.cost))
    tried = 0
    for L in Ls:
        if time.time() > deadline - 2 or tried >= 3:
            break
        if not all(len(lv) == len(o) and (not lv or same(o[0], lv[0])) for lv, o in zip(L.val, outs)):
            continue
        if all(same(lv, o) for lv, o in zip(L.val, outs)):
            continue
        rows, keyed, clash = [], {}, False
        for (args, o, tol), lv in zip(ex, L.val):
            for k in range(1, len(lv)):
                kk = repr((o[k - 1], lv[k]) + tuple(args))
                if kk in keyed:
                    clash = clash or not same(keyed[kk], o[k])
                    continue
                keyed[kk] = o[k]
                rows.append(((o[k - 1], lv[k]) + tuple(args), o[k], tol))
        if clash or len(rows) < 3:
            continue
        tried += 1
        vname = var_name(L, goal["params"])
        sub = {"name": goal["name"], "params": ["acc", vname] + list(goal["params"]), "examples": rows, "need": 3}
        res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=max(5.0, min(20.0, deadline - time.time() - 2)))
        if res["kind"] != "expr" or (res["x"].uses & 3) != 3:
            continue
        bx = res["x"]
        x = X(("scan", bx), [L], tuple(outs), 1 + L.size + bx.size, True, imports=("itertools",), uses=bx.uses >> 2)
        x.val = tuple(evalx(x, list(a)) for a, _o, _t in ex)
        if ok(x):
            return {"kind": "expr", "x": x, "steps": None, "bank": bank,
                    "covered": bin(x.nmask).count("1") == len(bank.namewords)}
    return None


def _fn(x, nvars=1):
    """a composed program as a Python function of its inputs (fast to run many times; same moves as the search)"""
    return lambda *vs: evalx(x, list(vs))


def deduce_zip(goal, bank, parts, words_text, deadline, ok):
    """two lists in step: when the answer is as long as two input lists, each answer is made from the pair at its place, so

    the step is a goal of its own (its inputs: the two elements, then the function's inputs)"""
    ex = goal["examples"]
    outs = [o for _a, o, _t in ex]
    if not all(isinstance(o, list) for o in outs) or not any(outs):
        return None
    k = len(ex[0][0])
    leaves = {x.op[1]: x for x in bank.alive(1) if x.op[0] == "in"}
    for i in range(k):
        for j in range(i + 1, k):
            A, B = leaves.get(i), leaves.get(j)
            if A is None or B is None or not (is_seq(A.t) and is_seq(B.t)):
                continue
            if not all(isinstance(a[i], list) and isinstance(a[j], list) and len(a[i]) == len(a[j]) == len(o)
                       for a, o, _t in ex):
                continue
            rows, keyed, clash = [], {}, False
            for args, o, tol in ex:
                for p, q, t in zip(args[i], args[j], o):
                    kk = repr((p, q) + tuple(args))
                    if kk in keyed:
                        clash = clash or not same(keyed[kk], t)
                        continue
                    keyed[kk] = t
                    rows.append(((p, q) + tuple(args), t, tol))
            if clash or len(rows) < 3:
                continue
            sub = {"name": goal["name"], "params": ["x", "y"] + list(goal["params"]), "examples": rows, "need": 3}
            res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=max(5.0, min(20.0, deadline - time.time() - 2)))
            if res["kind"] != "expr" or (res["x"].uses & 3) != 3:
                continue
            bx = res["x"]
            x = X(("zip", bx), [A, B], tuple(outs), 1 + A.size + B.size + bx.size, True, uses=bx.uses >> 2)
            x.val = tuple(evalx(x, list(a)) for a, _o, _t in ex)
            if ok(x):
                return {"kind": "expr", "x": x, "steps": None, "bank": bank,
                        "covered": bin(x.nmask).count("1") == len(bank.namewords)}
    return None


LOOP_WORDS = "while loop until repeat repeatedly each step steps times count how many keep"
LOOP_CAP = 1000          # iterations a candidate loop may take on one example


def _samples(vals):
    """states a loop may pass through, made from the examples' own: numbers below them, texts shortened"""
    out = []
    for v in vals:
        if isinstance(v, bool):
            continue
        if isinstance(v, int):
            for w in (v, v - 1, v // 2, v // 10, v * 3 + 1, -v):
                if w not in out:
                    out.append(w)
        elif isinstance(v, str):
            for w in (v, v[1:], v[:-1], v[2:], v.strip(), ""):
                if w not in out:
                    out.append(w)
    for w in (0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 16, 25) if all(isinstance(v, int) for v in vals) else ("0", "a", " a", "00"):
        if w not in out:
            out.append(w)
    return out[:60]


def loop_candidates(goal, bank, ok, deadline):
    """a while loop over the function's one input: a test, a step, and what it gives (how many steps, the total of a value

    taken at each step, or the state it ends in). The test and the step are found by the same search, over states made from

    the examples; each loop is run on the real examples with a cap on its steps."""
    ex = goal["examples"]
    if len(ex[0][0]) != 1:
        return []
    vals = [a[0] for a, _o, _t in ex]
    if not all(isinstance(v, int) and not isinstance(v, bool) for v in vals) and not all(isinstance(v, str) for v in vals):
        return []
    outs = [o for _a, o, _t in ex]
    st = tyof(vals[0])
    samples = _samples(vals)
    sb = Bank(len(samples), min(deadline, time.time() + 10), 30000, bank.words, bank.consts, [], namewords=bank.namewords)
    sb.add(X(("in", 0), [], tuple(samples), 1, True, uses=1))
    for c in bank.consts:
        sb.add(X(("const", c), [], tuple(c for _ in samples), 1, False))
    for size in range(2, 5):
        sb.grow(size)
    live = [x for x in sb.seen.values() if not x.dead and x.inp]
    steps = sorted((x for x in live if x.t == st and x.size >= 2), key=lambda x: x.cost)[:70]
    conds = sorted((x for x in live if x.t == "bool" and x.size >= 2 and any(v is True for v in x.val)
                    and any(v is False for v in x.val)), key=lambda x: x.cost)[:40]
    band = [b for b in sb.binary if b[0] == "and"][0]
    for c1, c2 in itertools.combinations(conds[:12], 2):   # two tests together: len(s) > 1 and s[0] == '0'
        conds.append(X(("b", "and", band[3], band[2]), [c1, c2], tuple(_ap(band[2], p, q) for p, q in zip(c1.val, c2.val)),
                       c1.size + c2.size + 1, True, band[4]))
    gs = sorted((x for x in live if is_num(x.t) and x.size <= 3), key=lambda x: x.cost)[:30] \
        if all(isinstance(o, (int, float)) and not isinstance(o, bool) for o in outs) else []
    cf = [(c, _fn(c)) for c in conds]
    sf = [(s_, _fn(s_)) for s_ in steps]
    gf = [(g, _fn(g)) for g in gs]
    leaf = [x for x in bank.alive(1) if x.op[0] == "in" and x.op[1] == 0][0]
    nw = bank.nw(LOOP_WORDS)
    hits = []
    for c, cfn in cf:
        if time.time() > deadline or len(hits) >= 30:
            break
        for s_, sfn in sf:
            runs = []
            for v in vals:
                state, n, trail = v, 0, [v]
                ok_run = True
                while True:
                    t = cfn(state)
                    if t is ERR or not isinstance(t, bool):
                        ok_run = False
                        break
                    if not t:
                        break
                    state = sfn(state)
                    n += 1
                    if state is ERR or n > LOOP_CAP:
                        ok_run = False
                        break
                    trail.append(state)
                if not ok_run:
                    break
                runs.append((state, n, trail))
            if len(runs) != len(vals) or not any(n for _s, n, _t in runs):
                continue
            kinds = [("count", None, tuple(n for _s, n, _t in runs)), ("final", None, tuple(s2 for s2, _n, _t in runs))]
            for g, gfn in gf:
                tot = []
                for _s, _n, trail in runs:
                    vs_ = [gfn(z) for z in trail[:-1]]
                    tot.append(ERR if any(v_ is ERR for v_ in vs_) else sum(vs_))
                kinds.append(("total", g, tuple(tot)))
            for kind, g, got in kinds:
                if all(v_ is not ERR and same(v_, o, t) for v_, (_a, o, t) in zip(got, ex)):
                    parts_ = [c, s_] + ([g] if g is not None else [])
                    rm = nm = 0
                    pen = 0.0
                    for z in parts_:
                        rm |= z.rmask
                        nm |= z.nmask
                        pen += z.pen
                    x = X(("loop", kind, c, s_, g), [leaf], got, 2 + sum(z.size for z in parts_), True,
                          (nw[0] | rm, nw[1] | nm))
                    x.pen += pen
                    x.cost += pen
                    x.lossy = x.lossy or any(z.lossy for z in parts_)
                    x.waived = x.waived or any(z.waived for z in parts_)
                    for z in parts_:
                        x.imports |= z.imports
                    if ok(x):
                        hits.append(x)
    if not hits and time.time() < deadline - 2 and all(isinstance(o, int) and not isinstance(o, bool) for o in outs):
        hits = _branch_loops(ex, vals, samples, sb, st, conds, leaf, nw, ok, deadline)
    return hits


BRANCH_CONDS, BRANCH_A, BRANCH_B = 8, 20, 400   # tests, first sides, second sides tried for a step with a branch


def _side_loses(side, states):
    """a weak side of a branch is weak only if it throws something away on the states the test sends it: n // 2 on even n"""
    if not side.lossy:
        return False
    if side.op[0] == "b" and side.op[1] == "floordiv" and isinstance(side.args[1], X) and side.args[1].op[0] == "const"             and not side.args[0].lossy and side.args[1].op[1]:
        k = side.args[1].op[1]
        got = [evalx(side.args[0], [z]) for z in states]
        return not all(isinstance(g, int) and g % k == 0 for g in got)
    return True


def _branch_loops(ex, vals, samples, sb, st, conds, leaf, nw, ok, deadline):
    """while test: state = (a if c else b); count the steps. The sides and tests come from the same pool as plain steps

    (one size larger); each trial runs on the values the pool already has on the sample states, and stops once its count

    passes the largest count asked for."""
    sb.deadline = min(deadline - 1, time.time() + 8)
    sb.grow(5)
    live = [x for x in sb.seen.values() if not x.dead and x.inp]
    steps = sorted((x for x in live if x.t == st and x.size >= 2), key=lambda x: x.cost)
    tests = sorted((x for x in live if x.t == "bool" and x.size >= 2 and any(v is True for v in x.val)
                    and any(v is False for v in x.val)), key=lambda x: x.cost)[:BRANCH_CONDS]
    idx = {}
    for i, v in enumerate(samples):
        idx.setdefault(v, i)
    want = [o for _a, o, _t in ex]
    top = max(want)
    order = sorted(range(len(vals)), key=lambda i: want[i])

    def runs_to(lc, nxt, v, target):
        n, state, trail = 0, v, [v]
        while True:
            i = idx.get(state)
            t = lc.val[i] if i is not None else evalx(lc, [state])   # off the samples: the program itself
            if t is ERR or not isinstance(t, bool):
                return None
            if not t:
                return trail if n == target else None
            n += 1
            if n > target:
                return None
            state = nxt(state, i)
            if state is ERR:
                return None
            trail.append(state)

    seen_b, hits = set(), []
    for c in tests:
        for a in steps[:BRANCH_A]:
            for b in steps[:BRANCH_B]:
                if a is b or time.time() > deadline:
                    return hits
                bv = tuple(av if cv is True else bv_ if cv is False else ERR for cv, av, bv_ in zip(c.val, a.val, b.val))
                if bv in seen_b:
                    continue
                seen_b.add(bv)

                def nxt(state, i, bv=bv, c=c, a=a, b=b):
                    if i is not None:
                        return bv[i]
                    t = evalx(c, [state])
                    return evalx(a, [state]) if t is True else evalx(b, [state]) if t is False else ERR
                for lc in conds[:6]:
                    trails = []
                    for i in order:
                        tr = runs_to(lc, nxt, vals[i], want[i])
                        if tr is None:
                            break
                        trails.append(tr)
                    if len(trails) != len(vals):
                        continue
                    states = [z for tr in trails for z in tr[:-1]]
                    ta = [z for z in states if evalx(c, [z]) is True]
                    tb = [z for z in states if evalx(c, [z]) is False]
                    lossy = c.lossy or lc.lossy or _side_loses(a, ta) or _side_loses(b, tb)
                    br = X(("b", "branch", "({1} if {0} else {2})", lambda cv, av, bv_: av if cv else bv_), [c, a, b], bv,
                           c.size + a.size + b.size + 1, True)
                    br.lossy, br.waived = lossy, c.waived or a.waived or b.waived
                    br.pen = LOSSY_PEN if lossy else 0.0
                    br.cost = br.size - WORD_BONUS * bin(br.rmask).count("1") - NAME_BONUS * bin(br.nmask).count("1") + br.pen
                    x = X(("loop", "count", lc, br, None), [leaf], tuple(want), 2 + lc.size + br.size, True,
                          (nw[0] | lc.rmask | br.rmask, nw[1] | lc.nmask | br.nmask))
                    x.pen, x.lossy, x.waived = br.pen + lc.pen, lossy, br.waived or lc.waived
                    x.cost = x.size - WORD_BONUS * bin(x.rmask).count("1") - NAME_BONUS * bin(x.nmask).count("1") + x.pen
                    x.imports |= lc.imports | c.imports | a.imports | b.imports
                    x.val = tuple(_run_loop(x, [v]) for v in vals)
                    if ok(x):
                        hits.append(x)
                        if len(hits) >= 4:
                            return hits
    return hits


def _run_loop(x, inp):
    kind, c, s_, g = x.op[1], x.op[2], x.op[3], x.op[4]
    state = evalx(x.args[0], inp)
    if state is ERR:
        return ERR
    n, tot = 0, 0
    while True:
        t = evalx(c, [state])
        if t is ERR or not isinstance(t, bool):
            return ERR
        if not t:
            break
        if g is not None:
            gv = evalx(g, [state])
            if gv is ERR:
                return ERR
            tot += gv
        state = evalx(s_, [state])
        n += 1
        if state is ERR or n > LOOP_CAP:
            return ERR
    return n if kind == "count" else tot if kind == "total" else state


def _run_guard(x, inp):
    p, c = x.op[1], x.op[2]
    v = evalx(p, inp)
    if v is ERR:
        return None
    if c is not None and evalx(c, [v]) is not True:
        return None
    return v


# ================================================================ THE ONE LOOP (C8)
# Every goal: forward search within the bound; then each move's declared INVERSE (how a wanted result constrains the
# move's inputs) yields smaller goals, solved by this same loop; forward continuations carry any list made to a summary,
# or a state through a loop. Everything that gives the examples is a candidate, weighed together; the law judges.
def subgoal_same_inputs(goal, wanted, keep=None):
    """a goal over the same inputs with other wanted values: what an inverse asks of one side"""
    ex = goal["examples"]
    idx = range(len(ex)) if keep is None else keep
    rows = [(ex[i][0], wanted[i], ex[i][2]) for i in idx]
    sub = {"name": goal["name"], "params": list(goal["params"]), "examples": rows, "need": 0, "module": goal.get("module"),
           "module_text": ""}
    for k in ("root", "fetched", "net_scope", "no_namewords"):
        if k in goal:
            sub[k] = goal[k]
    return sub


ASKS = []   # questions met inside inverses during one goal (an ambiguous step is asked about, never dropped)


def _ask_text(sub, res):
    call = "%s" % ", ".join("%s=%r" % (n, v) for n, v in zip(sub["params"], res["probe"]))
    rv = res["rival"][2] if isinstance(res["rival"], tuple) else res["rival"]
    return ("a step inside it fits more than one program, and they answer differently elsewhere: `%s` gives %r and `%s` gives "
            "%r for %s. Which is right? Add an example or a test that decides it." % (
                bare(code(res["x"], sub["params"])), res["va"], bare(code(rv, sub["params"])), res["vb"], call))


def _solve(sub, parts, words_text, goal, deadline, share=1.0):
    secs = max(4.0, min(30.0, (deadline - time.time()) * share))
    if deadline - time.time() < 3:
        return None
    res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=secs)
    if res["kind"] == "ambiguous":
        ASKS.append(_ask_text(sub, res))
    return res["x"] if res["kind"] == "expr" else None


def inv_text(goal, bank, parts, words_text, deadline, ok):
    """joining text, backwards: the answer split by the separator (or into equal pieces, one per element of a list the

    search made) is the list that was joined - a list goal, free to be a map, a filter, a running state..."""
    ex = goal["examples"]
    outs = [o for _a, o, _t in ex]
    if not all(isinstance(o, str) for o in outs):
        return []
    found = []
    joins = [u for u in bank.unary if u[0].startswith("join")]
    lists = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and is_seq(x.t) and x.size <= 3
                    and all(isinstance(v, list) for v in x.val) and any(x.val)), key=lambda x: (x.size, x.cost))[:4]
    for name, okj, f, cd, nw, imp in joins:
        if time.time() > deadline - 3 or len(found) >= 3:
            break
        sep = ast.literal_eval(name[4:])
        wanted_sets = []
        if sep:
            pcs = [o.split(sep) if o else [] for o in outs]
            if not all(len(p) <= 1 for p in pcs):
                wanted_sets.append(pcs)
        else:
            for L in lists:                           # one piece per element: equal lengths
                if not all(lv and len(o) % len(lv) == 0 or (not lv and o == "") for lv, o in zip(L.val, outs)):
                    continue
                pcs = [[o[i * (len(o) // len(lv)):(i + 1) * (len(o) // len(lv))] for i in range(len(lv))] if lv else []
                       for lv, o in zip(L.val, outs)]
                if not all(len(p) <= 1 for p in pcs) and pcs not in wanted_sets:
                    wanted_sets.append(pcs)
        for pcs in wanted_sets[:2]:
            lx = _solve(subgoal_same_inputs(goal, pcs), parts, words_text, goal, deadline, 0.5)
            if lx is None:
                continue
            x = X(("u", name, cd, f), [lx], tuple(_ap(f, v) for v in lx.val), lx.size + 1, True, nw, imp)
            if ok(x):
                found.append(x)
    return found


def inv_guard(goal, bank, parts, words_text, deadline, ok):
    """try/except, backwards: where the answer is a value, a program that gives it (a goal over those rows); where it is

    None, that program must fail, or a test on its value must turn it away (a yes/no goal over the values)"""
    ex = goal["examples"]
    outs = [o for _a, o, _t in ex]
    if not any(o is None for o in outs) or all(o is None for o in outs):
        return []
    keep = [i for i, o in enumerate(outs) if o is not None]
    if len(keep) < 2:
        return []
    px = _solve(subgoal_same_inputs(goal, outs, keep), parts, words_text, goal, deadline, 0.5)
    if px is None:
        return []
    vals = [evalx(px, list(a)) for a, _o, _t in ex]
    refused = [i for i, (v, o) in enumerate(zip(vals, outs)) if o is None and v is not ERR]
    found = []
    if not refused:
        x = X(("guard", px, None), [], tuple(outs), px.size + 2, True, uses=px.uses)
    else:
        rows = [((v,), o is not None, None) for v, o in zip(vals, outs) if v is not ERR]
        tsub = {"name": goal["name"], "params": ["value"], "examples": rows, "need": 1, "module": goal.get("module"),
                "module_text": "", "no_namewords": True}
        res = compose_goal(tsub, parts, words_text, depth=goal.get("_depth", 0) + 1,
                           seconds=max(4.0, min(20.0, deadline - time.time())))
        if res["kind"] == "ambiguous":
            ASKS.append(_ask_text(tsub, res))
        if res["kind"] != "expr":
            return []
        c = res["x"]
        x = X(("guard", px, c), [], tuple(outs), px.size + c.size + 3, True, uses=px.uses)
    c = x.op[2]
    x.rmask = px.rmask | (c.rmask if c is not None else 0)
    x.nmask = px.nmask | (c.nmask if c is not None else 0)
    x.pen = px.pen + (c.pen if c is not None else 0)
    x.lossy = px.lossy or (c is not None and c.lossy)
    x.waived = px.waived or (c is not None and c.waived)
    x.imports = set(px.imports) | (set(c.imports) if c is not None else set())
    x.cost = x.size - WORD_BONUS * bin(x.rmask).count("1") - NAME_BONUS * bin(x.nmask).count("1") + x.pen
    if ok(x):
        found.append(x)
    return found


def inv_arith(goal, bank, parts, words_text, deadline, ok):
    """a + b, a - b, a * b, a / b, text or list joined, backwards: with one side among the programs kept, the other side's

    values are known - looked up among every program kept (meet in the middle), and, failing that, a goal of its own for

    the two plainest first sides"""
    found = join_top(bank, goal["examples"], ok, deadline)
    if found or time.time() > deadline - 5 or goal.get("_depth", 0) > 0:
        return found
    ex = goal["examples"]
    outs = [o for _a, o, _t in ex]
    binops = {b[0]: b for b in bank.binary}
    firsts = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and x.size >= 2
                     and all(v is not ERR for v in x.val)), key=lambda x: x.cost)
    tried = 0
    for a in firsts:
        if tried >= 4 or time.time() > deadline - 4:
            break
        for name in JOINS:
            _n, okf, f, cd, nw, _c = binops[name]
            for need, a_first in _needs(name, outs, a.val):
                if tried >= 4:
                    break
                tried += 1
                bx = _solve(subgoal_same_inputs(goal, need), parts, words_text, goal, deadline, 0.3)
                if bx is None:
                    continue
                args = [a, bx] if a_first else [bx, a]
                if not okf(args[0].t, args[1].t):
                    continue
                x = X(("b", name, cd, f), args, tuple(_ap(f, p, q) for p, q in zip(args[0].val, args[1].val)),
                      a.size + bx.size + 1, True, nw)
                if ok(x):
                    found.append(x)
    return found


def _as_list(r):
    if r is None:
        return [], None
    if isinstance(r, list):
        return r, None
    if r["kind"] == "expr":
        return [r["x"]], None
    if r["kind"] == "cands":
        return list(r["xs"]), None
    if r["kind"] == "ambiguous_body":
        return [], r
    return [], None


INVERSES = (   # (inverse, its share of the time): each turns the wanted answer into smaller goals for the same loop
    (deduce_scan, 0.10),     # running state: (state, element) -> next state
    (deduce_zip, 0.15),      # two lists in step: (a, b) -> each answer
    (inv_text, 0.30),        # joined text: the pieces, a list goal
    (deduce, 0.50),          # a list from a list: each element's value, or kept-or-not, or a step's values some left out
    (inv_guard, 0.65),       # try/except: the value where there is one, a test where there is none
)


def decompose(goal, bank, parts, words_text, ok, seconds=None):
    """the one loop past the forward search: every declared inverse, then the forward continuations (a summary of any list

    made, a while loop over the input, two sides joined); all candidates returned to be weighed together"""
    ex = goal["examples"]
    t0 = time.time()
    end = t0 + (seconds or CHAIN_SECONDS)
    bank.deadline = end
    hits, asked = [], None
    n_asks = len(ASKS)
    for inv, share in INVERSES:
        xs, a = _as_list(inv(goal, bank, parts, words_text, min(end, t0 + share * (end - t0) + 2), ok))
        hits += xs
        asked = asked or a
    if any(evidenced(x, len(ex)) and not x.lossy for x in hits):   # a strong fit in hand: the rest weighed beside it
        end = min(end, time.time() + CHAIN_BESIDE_SECONDS)
        bank.deadline = end
    looped = any(bank.nw(LOOP_WORDS))               # the request or the name says a loop: the loop is given most of the time
    more = loop_candidates(goal, bank, ok, min(end, time.time() + (0.7 if looped else 0.35) * max(0.0, end - time.time())))
    more += seq_stage(bank, ex, ok, min(end, time.time() + 0.5 * max(0.0, end - time.time())))
    more += inv_arith(goal, bank, parts, words_text, max(end, time.time() + 3), ok)
    if asked is None and len(ASKS) > n_asks and goal.get("_depth", 0) == 0:
        asked = {"kind": "ask", "gap": ASKS[n_asks]}
    return hits + [x for x in more if evidenced(x, len(ex))], asked


def compose_goal(goal, parts, words_text, depth=0, seconds=None):
    goal["_depth"] = depth
    ex = goal["examples"]
    names = goal["params"]
    words = {stem(w) for w in re.findall(r"[a-z]+", (words_text or "").lower())}
    namewords = [] if goal.get("no_namewords") else name_words(goal["name"])   # the name describes it too
    deadline = time.time() + (seconds or GOAL_SECONDS)
    consts = const_pool(goal, words_text)
    bank = Bank(len(ex), deadline, BANK_CAP, words, consts, parts, namewords=namewords)
    bank.ex = ex
    bank.depth = depth
    leaves_for(goal, bank, consts)
    if goal.get("root"):
        edge_leaves(goal, bank)
    nearest = None
    every = goal.get("need", (1 << len(ex[0][0])) - 1)   # every input the function takes is read (a body: its element)

    def ok(x):
        return (x.uses & every) == every and (depth > 0 or "need" in goal or x.uses == every) and \
            (x.uses != 0 or goal.get("allow_const")) and \
            fits_all(x, ex) and matters(lambda inp: evalx(x, inp), ex, x.uses)
    for size in range(1, MAX_SIZE + 1):
        bank.grow(size, lambdas=True)
        hits = [x for s in range(1, size + 1) for x in bank.alive(s) if ok(x)]
        if hits:
            best = pick(hits, bank)
            nxt = size + 1                            # a larger program may still cost less (named moves, no lossy ones)
            while nxt <= MAX_SIZE and (nxt - (1.0 + NAME_BONUS * len(namewords)) < best.cost or
                                       bin(best.nmask).count("1") < len(namewords)) and not bank.time_up():
                # the choice puts the name's words first: while a word of the name is unsaid, larger programs are grown
                bank.grow(nxt, lambdas=True)
                more = [x for x in bank.alive(nxt) if ok(x)]
                hits += more
                if more:
                    best = pick(hits, bank)
                nxt += 1
            if nxt == size + 1 and nxt <= MAX_SIZE and not bank.time_up():   # rivals one node larger must exist to compare
                bank.grow(nxt, lambdas=True)
                hits += [x for x in bank.alive(nxt) if ok(x)]
            if depth == 0:                            # the inverses are weighed beside the first fit (a short pass)
                # the fit found first does not say all its name: programs made by chains are weighed beside it. A first
                # fit that is only weak evidence is not a fit: the inverses then get their whole time
                strong = any(not x.lossy for x in hits)
                more, _asked = decompose(goal, bank, parts, words_text, ok, CHAIN_BESIDE_SECONDS if strong else None)
                hits += more
            return decide(hits, bank, ex, names, ok)
        if bank.time_up():
            break
    # past the bound: larger code as chains of the programs found (in sequence: a body as its own goal; side by side: a join)
    chain_deadline = time.time() + (CHAIN_SECONDS if depth == 0 else CHAIN_SECONDS_SUB)
    if depth < MAX_DEPTH:
        hits, asked = decompose(goal, bank, parts, words_text, ok, None if depth == 0 else CHAIN_SECONDS_SUB * (MAX_DEPTH - depth))
    else:
        bank.deadline = chain_deadline
        hits, asked = [x for x in join_top(bank, ex, ok, chain_deadline) if evidenced(x, len(ex))], None
    if hits:
        return decide(hits, bank, ex, names, ok)
    if asked is not None:
        return asked
    steps = decision_list(bank, ex, every)
    if steps and matters(lambda inp: eval_steps(steps, inp), ex):
        m = 0
        for c, e in steps:
            m |= e.nmask | (c.nmask if c is not None else 0)
        return {"kind": "branches", "steps": steps, "bank": bank, "covered": bin(m).count("1") == len(namewords)}
    for x in bank.seen.values():
        if not x.dead and x.inp:
            c = bin(mask_of(x, ex)).count("1")
            if nearest is None or (c, -x.cost) > (nearest[0], -nearest[1].cost):
                nearest = (c, x)
    return {"kind": "none", "nearest": nearest, "bank": bank,
            "searched": len(bank.seen), "time_up": time.time() > deadline, "capped": len(bank.seen) >= bank.cap}


def function_source(goal, res):
    names = goal["params"]
    imports = set()
    if res["kind"] == "expr":
        x = res["x"]
        imports |= x.imports
        body = []
        HOIST.clear()
        if x.op[0] == "loop":
            st = code(x.args[0], names)
            kind, c, s_, g = x.op[1], x.op[2], x.op[3], x.op[4]
            if kind == "count":
                body += ["    count = 0", "    while %s:" % bare(code(c, [st])), "        %s = %s" % (st, bare(code(s_, [st]))),
                         "        count += 1", "    return count"]
            elif kind == "total":
                body += ["    total = 0", "    while %s:" % bare(code(c, [st])), "        total += %s" % bare(code(g, [st])),
                         "        %s = %s" % (st, bare(code(s_, [st]))), "    return total"]
            else:
                body += ["    while %s:" % bare(code(c, [st])), "        %s = %s" % (st, bare(code(s_, [st]))),
                         "    return %s" % st]
            x = None
        elif x.op[0] == "guard":
            p_, c = x.op[1], x.op[2]
            body += ["    try:", "        value = %s" % bare(code(p_, names)),
                     "    except (ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, AttributeError):",
                     "        return None"]
            if c is not None:
                body += ["    if not (%s):" % bare(code(c, ["value"])), "        return None"]
            body += ["    return value"]
            x = None
        if x is not None and x.op[0] == "b" and x.size > MAX_SIZE:   # larger code as the chain it is: each side a named step
            taken = set(names)
            for a in x.args:
                if isinstance(a, X) and a.size >= 2 and a.live:
                    nm = step_name(a, taken)
                    taken.add(nm)
                    body.append("    %s = %s" % (nm, bare(code(a, names))))
                    HOIST[id(a)] = nm
        if x is not None:
            body.append("    return %s" % bare(code(x, names)))
        HOIST.clear()
        x = res["x"]
        moves = moves_of(x)
        size = x.size
    else:
        body, moves, size = [], [], 0
        for c, e in res["steps"]:
            imports |= e.imports | (c.imports if c else set())
            moves += moves_of(e) + (moves_of(c) if c else [])
            size += e.size + (c.size if c else 0)
            if c is None:
                body.append("    return %s" % bare(code(e, names)))
            else:
                body += ["    if %s:" % bare(code(c, names)), "        return %s" % bare(code(e, names))]
    for x in _all_nodes(res):
        if x.op[0] == "const" and isinstance(x.op[1], float) and x.op[1] == math.pi:
            imports.add("math")
    text_all = "\n".join(body)
    for mod in ("hashlib", "hmac", "base64", "re", "math", "collections", "functools", "itertools", "json", "statistics",
                "urllib.request"):
        if re.search(r"\b%s\." % re.escape(mod), text_all):
            imports.add(mod)
    src = "def %s(%s):\n%s\n" % (goal["name"], ", ".join(names), "\n".join(body))
    return src, sorted(imports), moves, size


def _all_nodes(res):
    roots = [res["x"]] if res["kind"] == "expr" else [z for st in res["steps"] for z in st if z is not None]
    stack = list(roots)
    while stack:
        x = stack.pop()
        yield x
        stack.extend(a for a in x.args if isinstance(a, X))
        if x.op[0] in ("outer", "body", "scan", "zip"):
            stack.append(x.op[1])
        if x.op[0] == "loop":
            stack.extend(z for z in x.op[2:5] if z is not None)
        if x.op[0] == "guard":
            stack.extend(z for z in x.op[1:3] if z is not None)


def via_composer_v3(goal):
    """all-number goals the shape search did not reach: composer_v3 itself (its fitted constants are refused)"""
    ex = goal["examples"]
    if not all(isinstance(a, (int, float)) and not isinstance(a, bool) for args, _o, _t in ex for a in args):
        return None
    if not all(isinstance(o, (int, float)) and not isinstance(o, bool) for _a, o, _t in ex):
        return None
    for d in (WB / "swarm", WB.parents[1] / "specbuild"):
        if (d / "composer_v3.py").is_file():
            sys.path.insert(0, str(d))
            break
    try:
        import composer_v3 as C3
    except Exception:  # noqa: BLE001
        return None
    r = C3.compose({"id": goal["name"], "title": goal["name"], "dev": [{"in": list(a), "out": o} for a, o, _t in ex]})
    if r.get("status") != "composed" or r.get("kind") != "expr" or r.get("fitted"):
        return None
    if not all(re.search(r"\bx%d\b" % (i + 1), r["expr_py"]) for i in range(len(goal["params"]))):
        return None                                    # every input is read
    expr = re.sub(r"\bx(\d+)\b", lambda m: goal["params"][int(m.group(1)) - 1], r["expr_py"])
    return {"source": "def %s(%s):\n    return %s\n" % (goal["name"], ", ".join(goal["params"]), bare(expr)),
            "imports": ["math"] if "math." in expr else [], "moves": ["composer_v3: " + r["derivation"]], "size": r.get("size")}


# ================================================================ parts: the project's functions
try:
    import signal as _signal
    _CAN_BOUND = hasattr(_signal, "setitimer")
except Exception:  # noqa: BLE001
    _CAN_BOUND = False


def is_pure(fn_node):
    for n in ast.walk(fn_node):
        if isinstance(n, (ast.Global, ast.Nonlocal, ast.Yield, ast.YieldFrom)):
            return False
        if isinstance(n, ast.While) and not _CAN_BOUND:
            return False                              # nothing would stop a loop that does not end
        if isinstance(n, ast.Call):
            f = n.func
            if isinstance(f, ast.Name) and f.id in IMPURE_CALLS:
                return False
            if isinstance(f, ast.Attribute):
                root = f
                while isinstance(root, ast.Attribute):
                    root = root.value
                if isinstance(root, ast.Name) and root.id in IMPURE_MODS:
                    return False
    return True


def read_parts(root, target_module, exclude, seen_types):
    """the project's pure functions: name, module, inputs, and the shapes of the values it is seen to take (the tests, the

    project's own calls with literal values, or its annotations)"""
    out = []
    root = Path(root)
    n = 0
    calls_seen = {}
    for p in sorted(root.rglob("*.py"))[:200]:
        try:
            for c in ast.walk(ast.parse(p.read_text(encoding="utf-8"))):
                if isinstance(c, ast.Call) and isinstance(c.func, (ast.Name, ast.Attribute)) and c.args and not c.keywords:
                    fname = c.func.id if isinstance(c.func, ast.Name) else c.func.attr
                    try:
                        calls_seen.setdefault(fname, [tyof(ast.literal_eval(x)) for x in c.args])
                    except Exception:  # noqa: BLE001
                        pass
        except Exception:  # noqa: BLE001
            continue
    for p in sorted(root.rglob("*.py")):
        rel = p.relative_to(root)
        if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv", "build", "dist")
               for part in rel.parts) or is_test_path(rel) or SECRET.search(p.name) or p.name.startswith("_hidden"):
            continue
        n += 1
        if n > 80:
            break
        try:
            tree = ast.parse(p.read_text(encoding="utf-8"))
        except Exception:  # noqa: BLE001
            continue
        mod = ".".join(rel.with_suffix("").parts)
        for node in tree.body:
            if not isinstance(node, ast.FunctionDef) or node.name in exclude or node.name.startswith("test"):
                continue
            a = node.args
            if a.vararg or a.posonlyargs or any(d is None for d in a.kw_defaults):
                continue                                  # optional keywords (with defaults, or **kw) are left as they are
            k = len(a.args) - len(a.defaults)
            if not 1 <= k <= 3 or not is_pure(node):
                continue
            types = seen_types.get(node.name) or calls_seen.get(node.name) or annotated(node)
            if not types or len(types) != k:
                continue                                  # a part is used only where its inputs' shapes are known
            out.append({"name": node.name, "module": mod, "arity": k, "types": types,
                        "code": node.name if mod == target_module else "%s.%s" % (mod, node.name),
                        "imports": () if mod == target_module else (mod,),
                        "words": " ".join(re.findall(r"[a-z]+", node.name.lower() + " " + (ast.get_docstring(node) or "").lower()))})
    return out


ANN = {"int": "int", "float": "float", "str": "str", "bool": "bool", "list": ("list", None), "dict": ("dict", None, None),
       "tuple": ("tuple", None)}


def annotated(fn):
    out = []
    for a in fn.args.args[:len(fn.args.args) - len(fn.args.defaults)]:
        h = a.annotation
        if isinstance(h, ast.Name) and h.id in ANN:
            out.append(ANN[h.id])
        elif isinstance(h, ast.Subscript) and isinstance(h.value, ast.Name) and h.value.id in ("list", "List") and \
                isinstance(h.slice, ast.Name) and h.slice.id in ANN:
            out.append(("list", ANN[h.slice.id]))
        else:
            return None
    return out


def is_test_path(rel):
    rel = Path(rel)
    return rel.name.startswith("test_") or rel.name.endswith("_test.py") or "tests" in rel.parts or rel.name == "conftest.py"


def load_part_fns(root, parts):
    import contextlib
    import importlib
    import io
    sys.path.insert(0, str(root))
    ok = []
    for p in parts:
        try:
            with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
                m = importlib.import_module(p["module"])
            p["fn"] = _guarded(getattr(m, p["name"]))
            ok.append(p)
        except Exception:  # noqa: BLE001
            continue
    return ok


def _guarded(f):
    """a project function called by the search: time-limited, its output silenced"""
    import contextlib
    import io

    def g(*a):
        import signal
        if hasattr(signal, "setitimer"):
            signal.signal(signal.SIGALRM, _alarm)
            signal.setitimer(signal.ITIMER_REAL, 0.25)
        try:
            with contextlib.redirect_stdout(io.StringIO()):
                return f(*a)
        finally:
            if hasattr(signal, "setitimer"):
                signal.setitimer(signal.ITIMER_REAL, 0)
    return g


def _alarm(*_a):
    raise TimeoutError("part ran too long")


# ================================================================ read-back: a separate interpreter
def read_back(root, module_text, name, ex):
    with tempfile.TemporaryDirectory(prefix="o7code_") as d:
        open(os.path.join(d, "o7prog.py"), "w", encoding="utf-8").write(module_text)
        runner = ("import sys, json\nsys.path[:0] = [%r, %r]\nimport o7prog\nrows = eval(sys.stdin.read())\nout = []\n"
                  "for r in rows:\n    try:\n        out.append(repr(o7prog.%s(*r)))\n    except Exception as e:\n"
                  "        out.append('<err %%s>' %% type(e).__name__)\nprint(json.dumps(out))\n" % (d, str(root), name))
        try:
            r = subprocess.run([sys.executable, "-I", "-c", runner], input=repr([list(a) for a, _o, _t in ex]),
                               capture_output=True, text=True, timeout=30, cwd=str(root) if os.path.isdir(str(root)) else d)
            got = json.loads(r.stdout)
        except Exception as e:  # noqa: BLE001
            return False, "the written function did not run: %s" % str(e)[:120]
    ok = 0
    for g, (_a, out, tol) in zip(got, ex):
        try:
            v = ast.literal_eval(g)
        except Exception:  # noqa: BLE001
            v = ERR
        ok += same(v, out, tol)
    return ok == len(ex), "read back %d/%d" % (ok, len(ex))


# ================================================================ a job: goals composed round by round
def _in_child(work, name):
    """one goal composed in a forked child: its search's memory is given back when it ends, so the next goal starts from

    the job's own size (Python keeps what it has used). Where there is no fork, in this process."""
    def oom():
        return {"name": name, "status": "declined", "seconds": 0.0,
                "gap": "composing %s ran out of memory (the bound is %d MB); nothing was written for it" % (name, MEM_MB),
                "cause": "memory"}
    if not hasattr(os, "fork"):
        try:
            return work()
        except MemoryError:
            return oom()
    rfd, wfd = os.pipe()
    pid = os.fork()
    if pid == 0:                                      # the child: compose, send the result, leave at once
        os.close(rfd)
        code_ = 0
        try:
            _MEM["over"], _MEM["hit"], _MEM["t"] = False, False, 0.0
            try:
                out = work()
            except MemoryError:
                out = oom()
            data = json.dumps(out, default=lambda o: sorted(o, key=str) if isinstance(o, (set, frozenset)) else str(o)).encode()
        except BaseException as e:  # noqa: BLE001
            data = json.dumps({"name": name, "status": "declined", "gap": "the composer stopped on %s: %s" % (
                name, repr(e)[:300]), "cause": "stopped"}).encode()
            code_ = 1
        with os.fdopen(wfd, "wb") as f:
            f.write(data)
        os._exit(code_)
    os.close(wfd)
    with os.fdopen(rfd, "rb") as f:
        data = f.read()
    _p, status = os.waitpid(pid, 0)
    try:
        return json.loads(data.decode())
    except ValueError:
        sig = os.WTERMSIG(status) if os.WIFSIGNALED(status) else 0
        return {"name": name, "status": "declined", "seconds": 0.0,
                "gap": "composing %s stopped%s; nothing was written for it" % (
                    name, " by signal %d (the system's memory stop)" % sig if sig == 9 else
                    (" by signal %d" % sig if sig else "")), "cause": "memory" if sig == 9 else "stopped"}


def run_goals(job):
    root = job["root"]
    goals = job["goals"]
    exclude = set(job.get("exclude", ()))
    tests = read_tests(root)
    seen_types = {n: [tyof(a) for a in d["examples"][0][0]] for n, d in tests.items() if d["examples"]}
    target_mods = {g["module"] for g in goals}
    parts_all = read_parts(root, next(iter(target_mods)) if len(target_mods) == 1 else None,
                           exclude | {g["name"] for g in goals}, seen_types)
    parts_all = load_part_fns(root, parts_all)
    results, library, pending = {}, [], list(goals)
    flash, stored = store_flash()
    project_names = {p["name"] for p in parts_all}
    rnd = 0
    while pending:
        rnd += 1
        progress = False
        for g in list(pending):
            g.setdefault("root", root)
            g.setdefault("net_scope", job.get("net_scope", []))
            g["project_names"] = project_names
            kept = store_parts(flash, stored, g, exclude | {x["name"] for x in goals})
            faces = kernel_faces(g, job.get("words", ""))   # the kernel's formula parts the goal's words light
            # Two passes, each with its own budget: the project's parts first, then (only if that does not compose) the
            # kept functions the goal lights as well. A kept part adds reach; it never displaces what the base finds,
            # and it never takes the base search's time (the banks are bounded by deadline, size and memory).
            r, spent = None, 0.0
            for lit in ([faces, faces + kept] if kept else [faces]):
                if r is not None and time.time() + PASS_SECONDS * len(pending) > job.get("ends_at", float("inf")):
                    break                                  # no room for it and the rest's first passes: the base answer stands
                parts = [p for p in parts_all] + [lib for lib in library] + lit
                _MEM["hit"] = False
                t_goal = time.time()
                r2 = _in_child(lambda: compose_one(root, g, parts, job.get("words", ""), library + lit), g["name"])
                spent += time.time() - t_goal         # wall time of every pass, measured outside the child
                if r is None or r2["status"] == "composed":
                    r = r2
                if r["status"] == "composed":
                    break
            r["round"] = rnd
            r["spent"] = round(spent, 3)
            results[g["name"]] = r
            if r["status"] == "composed":
                pending.remove(g)
                progress = True
                if not r.get("confirmed") or g.get("class"):
                    continue                     # a part for the next only once confirmed (three examples, or its name)
                ns = {}
                try:
                    exec(compile("\n".join("import %s" % i for i in r["imports"]) + "\n" +
                                 "\n".join(lib["source"] for lib in library) + "\n" + r["source"], g["name"], "exec"), ns)
                    library.append({"name": g["name"], "module": g["module"], "arity": len(g["params"]),
                                    "types": [tyof(a) for a in g["examples"][0][0]], "code": g["name"], "imports": (),
                                    "words": " ".join(re.findall(r"[a-z]+", g["name"].lower())),
                                    "fn": _guarded(ns[g["name"]]), "source": r["source"], "lib_imports": r["imports"]})
                except Exception:  # noqa: BLE001
                    pass
        if not progress:
            break
    try:                                              # a declined goal is a hole for the night (code_store.nightly)
        import code_store as CS
        for g in goals:
            rg = results[g["name"]]
            if rg["status"] != "composed" and not rg.get("ambiguous"):
                CS.note_hole(g, rg.get("gap"), root, cause=rg.get("cause") or "evidence", spent=rg.get("spent"),
                             work=rg.get("work"))
    except Exception:  # noqa: BLE001
        pass
    return {"results": [results[g["name"]] for g in goals]}


_FACES = {}
SI_UNITS = {"m", "kg", "s", "m^2", "m^3", "m/s", "m/s^2", "N", "Pa", "J", "W", "K", "A", "V", "Hz", "kg/m^3", "N*m", "1"}


def _organ():
    wb = Path(__file__).resolve().parent
    for d in (os.environ.get("ORACLE7_FORMULA_ORGAN"), wb.parent / "root" / "organs10" / "physics"):
        if d and (Path(d) / "swarm" / "parts.json").is_file():
            return Path(d)
    return None


def kernel_faces(g, words_text):
    """the kernel's admitted formula parts (Wikidata systems, solved and checked by substitution) a numeric goal's words

    light: the part's output is a word of the name or request, its system (a shape, a law) is one too, and it takes as

    many values as the goal. Each comes as a part with its own program, renamed, and its title kept in its docstring."""
    ex = g.get("examples") or []
    if not ex or not all(is_num(tyof(a)) for a in ex[0][0]) or not all(isinstance(o, (int, float)) and not isinstance(o, bool)
                                                                        for _a, o, _t in ex):
        return []
    org = _organ()
    if org is None:
        return []
    if "all" not in _FACES:
        faces = []
        try:
            pj = json.loads((org / "swarm" / "parts.json").read_text(encoding="utf-8"))
            for pid, pt in pj.items():
                if pt.get("kind") != "formula" or not pt.get("output"):
                    continue
                d = org / "specialists" / pid
                try:
                    title = json.loads((d / "spec.json").read_text(encoding="utf-8")).get("title", "")
                    prog = (d / "program.py").read_text(encoding="utf-8")
                except OSError:
                    continue
                units = [re.search(r"\(([^)]*)\)", x) for x in pt["inputs"] + [pt["output"]]]
                if any(u is None or u.group(1).strip() not in SI_UNITS for u in units):
                    continue                          # the plain SI faces only: no hidden unit scaling in a written function
                m = re.search(r"\(([^)]+)\)\s*$", title)
                sysw = {stem(w) for w in re.findall(r"[a-z]+", (m.group(1) if m else "").lower())}
                out_n = {stem(w) for w in re.findall(r"[a-z]+", pt["output"].split("(")[0].lower())}
                faces.append({"id": pid, "title": title, "prog": prog, "k": len(pt["inputs"]), "out": out_n, "sys": sysw,
                              "ins": [x.split("(")[0].strip() for x in pt["inputs"]]})
        except (OSError, ValueError):
            faces = []
        _FACES["all"] = faces
    ws = set(name_words(g["name"])) | {stem(w) for w in re.findall(r"[a-z]+", (words_text or "").lower())}
    k = len(ex[0][0])
    out = []
    for f in _FACES["all"]:
        if f["k"] != k or not (f["out"] & ws) or not (f["sys"] & ws):
            continue
        fname = "face_" + re.sub(r"\W+", "_", f["id"]).strip("_").lower()
        src = re.sub(r"(?m)^def compute\(", "def %s(" % fname, f["prog"])
        imports = re.findall(r"(?m)^import (\w+)\s*$", src)
        src = re.sub(r"(?m)^import \w+\s*\n", "", src).strip()
        src = re.sub(r'^"""', '"""Oracle7 kernel part %s: ' % f["id"], src, count=1) if src.startswith('"""') else src
        ns = {}
        try:
            for i in imports:
                ns[i] = __import__(i)
            exec(compile(src, "face:" + f["id"], "exec"), ns)
        except Exception:  # noqa: BLE001
            continue
        out.append({"name": fname, "module": None, "arity": k, "types": [tyof(a) for a in ex[0][0]], "code": fname,
                    "imports": (), "words": " ".join(sorted(f["out"] | f["sys"])), "fn": _guarded(ns[fname]),
                    "source": src, "lib_imports": imports, "face": {"id": f["id"], "title": f["title"]}})
        if len(out) >= 6:
            break
    return out


def store_flash():
    """Oracle7's kept functions on the spine (code_store), or (None, []) when there are none"""
    try:
        import code_store as CS
    except Exception:  # noqa: BLE001
        return None, []
    entries = CS.load()
    if not entries:
        return None, []
    try:
        return CS.CodeFlash(entries), entries
    except Exception:  # noqa: BLE001
        return None, []


def store_parts(flash, stored, g, exclude):
    """the kept functions a goal's facts light, as parts: shapes fit, source checked, the kept functions they call loaded

    first; each carries its record so the reply can say where it came from"""
    if flash is None or not g.get("examples") or g.get("class"):
        return []                                     # a class's methods stay within the class
    import code_store as CS
    ex = g["examples"]
    in_shapes = [repr(tyof(a)) for a in ex[0][0]]
    out_shape = repr(ty_of_vals([o for _a, o, _t in ex]))
    lit = flash.light(in_shapes, out_shape, name_words(g["name"]))
    by_sha = {e["sha256"]: e for e in stored}
    known = {e["name"] for e in stored}
    taken = set(g.get("project_names") or [])           # the project's own functions keep their names
    out, loaded, ids = [], {}, {}

    def load(e, depth=0):
        if e["name"] in loaded:                        # one name, one implementation: a different record is not used
            return loaded[e["name"]] if ids.get(e["name"]) == e["sha256"] else None
        if depth > 6 or e["name"] in taken:
            return None
        for dn, dsha in (e.get("deps") or {}).items():  # what it calls, by the exact source it was checked with
            dep = by_sha.get(dsha)
            if dep is None or load(dep, depth + 1) is None:
                return None
        if CS.checked_source(e["source"], e["name"], known) is not None:
            return None
        ns = {}
        try:
            import importlib
            for m in e.get("imports") or []:
                ns[m.split(".")[0]] = importlib.import_module(m)
            for dn, dp in loaded.items():
                if dp is not None:
                    ns[dn] = dp["fn"]
            exec(compile(e["source"], "store:" + e["name"], "exec"), ns)
        except Exception:  # noqa: BLE001
            return None
        part = {"name": e["name"], "module": None, "arity": len(e["params"]), "code": e["name"], "imports": (),
                "types": [ast.literal_eval(t) if t.startswith(("(", "'")) else t for t in e.get("in_shapes") or []] or None,
                "words": " ".join(re.findall(r"[a-z]+", e["name"].lower())), "fn": _guarded(ns[e["name"]]),
                "source": e["source"], "lib_imports": list(e.get("imports") or []), "store": {"project": e.get("project"),
                                                                                          "id": e["id"]}}
        loaded[e["name"]] = part
        ids[e["name"]] = e["sha256"]
        return part
    for _res, e in lit:
        if e["name"] in exclude or e["name"] == g["name"]:
            continue
        if len(e.get("params") or []) > 3:
            continue
        pt = load(e)
        if pt is not None and pt not in out:
            out.append(pt)
    for dn, dp in loaded.items():                      # what a lit function calls comes with it
        if dp is not None and dp not in out:
            out.append(dp)
    return out


def compose_one(root, g, parts, words_text, library):
    """one goal composed; its result carries the work it was given (12.5 step 6)"""
    _WORK.update(bank=0, probe=0, last=None)
    r = _compose_one(root, g, parts, words_text, library)
    if isinstance(r, dict):
        r = dict(r, work={"bank": _WORK["bank"], "probe": _WORK["probe"], "stage": _WORK["last"]})
    return r


def _compose_one(root, g, parts, words_text, library):
    ex = g["examples"]
    if not ex:
        return {"name": g["name"], "status": "declined", "gap": "no examples or tests say what %s gives" % g["name"]}
    keyed = {}
    for a, o, _t in ex:
        k = repr(a)
        if k in keyed and not same(keyed[k], o):
            return {"name": g["name"], "status": "declined", "gap": "the examples disagree: %s gives two answers for %s" % (g["name"], k)}
        keyed[k] = o
    if len({len(a) for a, _o, _t in ex}) != 1:
        return {"name": g["name"], "status": "declined", "gap": "%s is called with different numbers of inputs" % g["name"]}
    t0 = time.time()
    pages, gap = fetch_examples(g)
    if gap:
        return {"name": g["name"], "status": "declined", "gap": gap, "network": True}
    g["fetched"] = pages
    res = compose_goal(g, parts, words_text)
    if res["kind"] == "ask":                          # a step inside it, read two ways
        return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "ambiguous": True,
                "gap": "the %d examples of %s are within reach, but %s" % (len(ex), g["name"], res["gap"])}
    if res["kind"] == "ambiguous_body":               # the body of a comprehension, composed as its own goal, read two ways
        sub, br = res["sub"], res["res"]
        el = repr(br["probe"][0])
        others = ", ".join("%s=%r" % (n, v) for n, v in zip(g["params"], br["probe"][1:]))
        if isinstance(br["rival"], tuple):
            _s, node, alt = br["rival"]
            HOIST.clear()
            HOIST[id(node)] = bare(code(alt, sub["params"]))
            rcode = bare(code(br["x"], sub["params"]))
            HOIST.clear()
        else:
            rcode = bare(code(br["rival"], sub["params"]))
        return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "ambiguous": True,
                "gap": "the %d examples make %s a list built from `%s`, %s, but the step for each element fits more than "
                       "one program, and they answer differently elsewhere: for the element %s (with %s), `%s` gives %r and "
                       "`%s` gives %r. Which is right? Add an example (or a test) that has such an element." % (
                           len(ex), g["name"], bare(code(res["L"], g["params"])),
                           "one value per element" if res["lam"] == "map" else "keeping some elements", el, others,
                           bare(code(br["x"], sub["params"])), br["va"], rcode, br["vb"])}
    if res["kind"] == "ambiguous":
        call = "%s(%s)" % (g["name"], ", ".join(repr(v) for v in res["probe"]))
        if isinstance(res["rival"], tuple):           # a part of it read another way
            _s, node, alt = res["rival"]
            return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "ambiguous": True,
                    "gap": "the %d examples fit more than one program, and they answer differently elsewhere: `%s` gives %r "
                           "for %s, but with `%s` read as `%s` it gives %r. Which is right? Say it as an example (%s == ...) "
                           "or add it to the tests." % (len(ex), bare(code(res["x"], g["params"])), res["va"], call,
                                                        bare(code(node, g["params"])), bare(code(alt, g["params"])), res["vb"], call)}
        return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "ambiguous": True,
                "gap": "the %d examples fit more than one program, and they answer differently elsewhere: `%s` gives %r "
                       "for %s, `%s` gives %r. Which is right? Say it as an example (%s == ...) or add it to the tests." % (
                           len(ex), bare(code(res["x"], g["params"])), res["va"], call,
                           bare(code(res["rival"], g["params"])), res["vb"], call)}
    if res["kind"] == "unsaid":
        return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1),
                "gap": "the name says '%s' and the data has it, but the program found for the %d examples does not use it: "
                       "`%s`. That fits by coincidence as likely as not, so it was not written; add an example where it "
                       "matters, or say how '%s' is meant." % (res["word"], len(ex), bare(code(res["x"], g["params"])),
                                                              res["word"])}
    lossy = res["kind"] in ("expr", "branches") and any(x.lossy for x in _all_nodes(res))
    v3 = via_composer_v3(g) if lossy else None        # a fit through an unnamed lossy move: composer_v3 has none of those
    if v3 is not None:
        src, imports, moves, size = v3["source"], v3["imports"], v3["moves"], v3["size"]
    elif lossy:                                       # weak evidence: say what it would be, write nothing
        prog = bare(code(res["x"], g["params"])) if res["kind"] == "expr" else "a branch list"
        return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1),
                "gap": "the only programs within reach that give the %d examples of %s throw information away (rounding, "
                       "//, %%, a fixed position, or a number's digits read as text): `%s`. That is weak evidence, so it "
                       "was not written; if that reading is meant, say so in the request (e.g. 'by its digits'), or add "
                       "examples." % (len(ex), g["name"], prog)}
    elif res["kind"] in ("expr", "branches"):
        try:                                          # 12.5 12c(i): the sufficiency judge in shadow (changes no answer)
            import shadow as _shadow
            _shadow.record(res, ex, g["name"], sys.modules[__name__])
        except Exception:  # noqa: BLE001
            pass
        src, imports, moves, size = function_source(g, res)
    else:
        v3 = via_composer_v3(g)
        if v3 is None:
            near = res.get("nearest")
            near_txt = ""
            if near and near[0]:
                near_txt = " The nearest program gives %d of the %d: %s" % (near[0], len(ex), bare(code(near[1], g["params"])))
            bound = "memory" if _MEM["hit"] else "time" if res.get("time_up") else "cap" if res.get("capped") else None
            if bound:                                 # 12.5 C33: a stopped search did not cover the space; it says so
                gap = ("the search for %s stopped at its %s after %d distinct programs, none giving all %d examples; the "
                       "programs within %d moves were not all tried, so one may still exist.%s" % (
                           g["name"], "memory bound (%d MB)" % MEM_MB if bound == "memory" else
                           "bound of %d kept programs" % BANK_CAP if bound == "cap" else "time limit",
                           res.get("searched", 0), len(ex), MAX_SIZE, near_txt))
            else:
                gap = ("no program within %d moves over these shapes (nor a branch list whose branches each rest on two "
                       "examples) gives all %d examples of %s; %d distinct programs were tried.%s" % (
                           MAX_SIZE, len(ex), g["name"], res.get("searched", 0), near_txt))
            return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "gap": gap,
                    "cause": bound or "searched"}
        src, imports, moves, size = v3["source"], v3["imports"], v3["moves"], v3["size"]
    used_lib = [lib for lib in library if re.search(r"\b%s\(" % re.escape(lib["name"]), src)]
    grew = True
    while grew:
        grew = False
        for lib in library:
            if lib not in used_lib and any(re.search(r"\b%s\(" % re.escape(lib["name"]), u.get("source") or "") for u in used_lib):
                used_lib.insert(0, lib)
                grew = True
    lib_imports = sorted({i for lib in used_lib for i in lib.get("lib_imports", [])})
    base = g.get("module_text", "")
    base = _drop_function(base, g["name"])
    mod_imports = sorted(set(imports) | set(lib_imports))
    text = "\n".join("import %s" % i for i in mod_imports) + "\n" + base + "\n\n" + \
        "\n\n".join(lib["source"] for lib in used_lib) + "\n\n" + src
    ok, note = read_back(root, text, g["name"], ex)
    if not ok:
        return {"name": g["name"], "status": "declined", "gap": "the written %s disagreed with its examples (%s)" % (g["name"], note)}
    confirmed = len(ex) >= 3 or bool(res.get("covered") and v3 is None)
    evidence = []
    for a, o, _t in ex:
        try:
            json.dumps([list(a), o])
            evidence.append([list(a), o])
        except Exception:  # noqa: BLE001
            pass
    from_store = [{"name": lib["name"], "project": lib["store"].get("project"), "id": lib["store"].get("id")}
                  for lib in used_lib if lib.get("store")]
    deps = {lib["name"]: hashlib.sha256((lib["name"] + "\n" + lib["source"]).encode()).hexdigest()
            for lib in used_lib if lib.get("source")}
    return {"name": g["name"], "status": "composed", "source": src, "imports": imports, "moves": moves, "size": size,
            "confirmed": confirmed, "evidence": evidence[:40], "in_shapes": [repr(tyof(a)) for a in ex[0][0]],
            "out_shape": repr(ty_of_vals([o for _a, o, _t in ex])), "words": name_words(g["name"]),
            "from_store": from_store, "deps": deps,
            "examples": len(ex), "read_back": note, "seconds": round(time.time() - t0, 1),
            "uses": [lib["name"] for lib in used_lib], "branches": res["kind"] == "branches",
            # the parts from outside the project (kept functions, the kernel's formula faces) travel with it: what is
            # written must run where it is written (12.0 C8h)
            "support": [lib["source"] for lib in used_lib if (lib.get("store") or lib.get("face")) and lib.get("source")],
            "support_imports": sorted({i for lib in used_lib if lib.get("store") or lib.get("face")
                                       for i in lib.get("lib_imports", [])})}


def _drop_function(text, name):
    try:
        tree = ast.parse(text)
    except Exception:  # noqa: BLE001
        return text
    lines = text.splitlines()
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) and node.name == name:
            start = node.lineno - 1 - len(node.decorator_list)
            return "\n".join(lines[:start] + lines[node.end_lineno:])
    return text


# ================================================================ evidence (read in the bench's own process: parsing only)
def _lit(n, env):
    if isinstance(n, ast.Name) and n.id in env:
        return env[n.id]
    return ast.literal_eval(n)


def read_tests(root, only=None):
    """{name: {"module": m, "examples": [(args, out, tol)], "files": [...]}} from the project's test files"""
    root = Path(root)
    found = {}
    for p in sorted(root.rglob("*.py")):
        rel = p.relative_to(root)
        if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv") for part in rel.parts):
            continue
        if not is_test_path(rel) or p.name.startswith("_hidden"):
            continue
        if only and p.name not in only and str(rel).replace(os.sep, "/") not in only:
            continue
        try:
            tree = ast.parse(p.read_text(encoding="utf-8"))
        except Exception:  # noqa: BLE001
            continue
        env, names, mods = {}, {}, {}
        for node in tree.body:
            if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
                try:
                    env[node.targets[0].id] = ast.literal_eval(node.value)
                except Exception:  # noqa: BLE001
                    pass
        for node in ast.walk(tree):
            if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and \
                    node.module.split(".")[0] not in sys.stdlib_module_names and node.module not in ("pytest", "unittest"):
                for a in node.names:
                    if a.name != "*":
                        names[a.asname or a.name] = (node.module, a.name)
                    else:
                        names.setdefault("*", []).append(node.module)
            elif isinstance(node, ast.Import):
                for a in node.names:
                    if a.name.split(".")[0] not in sys.stdlib_module_names and a.name not in ("pytest", "unittest"):
                        mods[a.asname or a.name] = a.name

        def target(call):
            if not isinstance(call, ast.Call) or call.keywords:
                return None
            f = call.func
            if isinstance(f, ast.Name) and f.id in names and f.id != "*":
                return names[f.id]
            if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name) and f.value.id in mods:
                return (mods[f.value.id], f.attr)
            if isinstance(f, ast.Name) and "*" in names and not f.id[0].isupper() and f.id not in dir(builtins):
                return (names["*"][0], f.id)
            return None

        def record(call, out, tol=None):
            t = target(call)
            if t is None:
                return
            try:
                args = tuple(_lit(a, env) for a in call.args)
            except Exception:  # noqa: BLE001
                return
            d = found.setdefault(t[1], {"module": t[0], "examples": [], "files": []})
            if repr((args, out)) not in {repr((a, o)) for a, o, _t in d["examples"]}:
                d["examples"].append((args, out, tol))
            if str(rel) not in d["files"]:
                d["files"].append(str(rel).replace(os.sep, "/"))

        def value(n):
            if isinstance(n, ast.Call) and isinstance(n.func, (ast.Attribute, ast.Name)) and \
                    (getattr(n.func, "attr", None) == "approx" or getattr(n.func, "id", None) == "approx") and n.args:
                return _lit(n.args[0], env), 1e-6 * max(1.0, abs(_lit(n.args[0], env)))
            return _lit(n, env), None

        for node in ast.walk(tree):
            try:
                if isinstance(node, ast.Assert):
                    tst = node.test
                    if isinstance(tst, ast.Compare) and len(tst.ops) == 1:
                        op, left, right = tst.ops[0], tst.left, tst.comparators[0]
                        if isinstance(op, ast.Eq):
                            if target(left):
                                v, tol = value(right)
                                record(left, v, tol)
                            elif target(right):
                                v, tol = value(left)
                                record(right, v, tol)
                        elif isinstance(op, ast.Is) and isinstance(right, ast.Constant) and target(left):
                            record(left, right.value)
                        elif isinstance(op, (ast.Lt, ast.LtE)) and isinstance(left, ast.Call) and \
                                getattr(left.func, "id", None) == "abs" and len(left.args) == 1 and \
                                isinstance(left.args[0], ast.BinOp) and isinstance(left.args[0].op, ast.Sub):
                            a, b = left.args[0].left, left.args[0].right
                            eps = _lit(right, env)
                            if target(a):
                                record(a, _lit(b, env), eps)
                            elif target(b):
                                record(b, _lit(a, env), eps)
                    elif target(tst):
                        record(tst, True)
                    elif isinstance(tst, ast.UnaryOp) and isinstance(tst.op, ast.Not) and target(tst.operand):
                        record(tst.operand, False)
                elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.args:
                    m = node.func.attr
                    a0 = node.args[0]
                    if m in ("assertEqual", "assertEquals") and len(node.args) >= 2:
                        if target(a0):
                            record(a0, _lit(node.args[1], env))
                        elif target(node.args[1]):
                            record(node.args[1], _lit(a0, env))
                    elif m == "assertAlmostEqual" and len(node.args) >= 2 and target(a0):
                        places = _lit(node.args[2], env) if len(node.args) > 2 else 7
                        record(a0, _lit(node.args[1], env), 0.5 * 10 ** (-places))
                    elif m == "assertTrue" and target(a0):
                        record(a0, True)
                    elif m == "assertFalse" and target(a0):
                        record(a0, False)
                    elif m == "assertIsNone" and target(a0):
                        record(a0, None)
            except Exception:  # noqa: BLE001
                continue
    return found


def _scan_value(s):
    """the literal at the start of s: the shortest prefix, cut at a comma, semicolon or 'and' outside brackets and quotes"""
    depth, q, cuts = 0, None, []
    i = 0
    while i < len(s):
        ch = s[i]
        if q:
            if ch == "\\":
                i += 2
                continue
            if ch == q:
                q = None
        elif ch in "'\"":
            q = ch
        elif ch in "([{":
            depth += 1
        elif ch in ")]}":
            depth -= 1
            if depth < 0:
                cuts.append(i)
                break
        elif depth == 0 and (ch in ",;" or s[i:i + 5] == " and " or (ch == "." and (i + 1 == len(s) or s[i + 1] == " "))):
            cuts.append(i)
        i += 1
    cuts.append(len(s))
    for c in cuts:
        try:
            return ast.literal_eval(s[:c].strip()), True
        except Exception:  # noqa: BLE001
            continue
    return None, False


def _quoted_breaks(s):
    """a line break inside a quoted text is written as \\n, so the literal reads (a Python literal cannot hold a bare one)"""
    out, q = [], None
    for ch in s:
        if q:
            if ch == q:
                q = None
            elif ch == "\n":
                ch = "\\n"
        elif ch in "'\"":
            q = ch
        out.append(ch)
    return "".join(out)


def examples_in(text, name):
    """examples written in the request: name(args) == v / -> v / returns v / gives v / is v / should be v"""
    out = []
    for m in re.finditer(r"\b%s\s*\(" % re.escape(name), text or ""):
        i, depth, q = m.end() - 1, 0, None
        j = i
        while j < len(text):
            ch = text[j]
            if q:
                if ch == "\\":
                    j += 2
                    continue
                if ch == q:
                    q = None
            elif ch in "'\"":
                q = ch
            elif ch in "([{":
                depth += 1
            elif ch in ")]}":
                depth -= 1
                if depth == 0:
                    break
            j += 1
        inner = _quoted_breaks(text[i + 1:j])        # a line break typed inside a quoted example is \n
        rest = text[j + 1:]
        mm = re.match(r"\s*(?:==|->|=>|\u2192|returns?|gives?|should (?:be|give|return)|is)\s*", rest)
        if not mm:
            continue
        try:
            args = ast.literal_eval("(%s,)" % inner) if inner.strip() else ()
        except Exception:  # noqa: BLE001
            continue
        v, ok = _scan_value(_quoted_breaks(rest[mm.end():]))
        if ok:
            out.append((tuple(args), v, None))
    return out


def param_names(ex, given=None):
    if given:
        return list(given)
    out = []
    for a in ex[0][0]:
        t = tyof(a)
        base = "xs" if is_seq(t) and t[1] in ("int", "float", None) else "items" if is_seq(t) else "text" if t == "str" else \
            "mapping" if is_dict(t) else "flag" if t == "bool" else "n" if t == "int" else "x"
        name, k = base, 2
        while name in out:
            name, k = "%s%d" % (base, k), k + 1
        out.append(name)
    if out == ["x", "x2"]:
        out = ["a", "b"]
    if out == ["n", "n2"]:
        out = ["a", "b"]
    return out


# ================================================================ classes: an object's state is what was done to it
# ================================================================ objects as a state carried through ordered actions
def read_object_runs(root, only=None):
    """{Class: {"module", "files", "ctor", "mutators", "runs": [{"ctor": args, "events": [(m, args)], "obs": [(k, q, qargs,

    out)]}]}} - every object the tests make, the actions done to it IN ORDER, and what each query gave after the first k of

    them. Order between different actions is kept (the class-history representation lost it: set;reset == reset;set)."""
    root = Path(root)
    found = {}
    for p in sorted(root.rglob("*.py")):
        rel = p.relative_to(root)
        if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv") for part in rel.parts):
            continue
        if not is_test_path(rel) or p.name.startswith("_hidden"):
            continue
        if only and p.name not in only and str(rel).replace(os.sep, "/") not in only:
            continue
        try:
            tree = ast.parse(p.read_text(encoding="utf-8"))
        except Exception:  # noqa: BLE001
            continue
        classes = {}
        for node in ast.walk(tree):
            if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and \
                    node.module.split(".")[0] not in sys.stdlib_module_names:
                for a in node.names:
                    if a.name[:1].isupper():
                        classes[a.asname or a.name] = (node.module, a.name)
        if not classes:
            continue
        bodies = [tree.body] + [n.body for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]
        for body in bodies:
            objs, env = {}, {}
            for st in body:
                try:
                    if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name):
                        v = st.value
                        if isinstance(v, ast.Call) and isinstance(v.func, ast.Name) and v.func.id in classes and not v.keywords:
                            mod, real = classes[v.func.id]
                            d = found.setdefault(real, {"module": mod, "files": [], "ctor": len(v.args), "mutators": [], "runs": []})
                            run = {"ctor": tuple(_lit(a, env) for a in v.args), "events": [], "obs": []}
                            d["runs"].append(run)
                            objs[st.targets[0].id] = (real, run)
                            if str(rel) not in d["files"]:
                                d["files"].append(str(rel).replace(os.sep, "/"))
                        else:
                            try:
                                env[st.targets[0].id] = ast.literal_eval(v)
                            except Exception:  # noqa: BLE001
                                pass
                    elif isinstance(st, ast.Expr) and isinstance(st.value, ast.Call) and \
                            isinstance(st.value.func, ast.Attribute) and isinstance(st.value.func.value, ast.Name) and \
                            st.value.func.value.id in objs:
                        real, run = objs[st.value.func.value.id]
                        m = st.value.func.attr
                        run["events"].append((m, tuple(_lit(a, env) for a in st.value.args)))
                        if m not in found[real]["mutators"]:
                            found[real]["mutators"].append(m)
                    elif isinstance(st, ast.Assert) and isinstance(st.test, ast.Compare) and len(st.test.ops) == 1 and \
                            isinstance(st.test.ops[0], (ast.Eq, ast.Is)):
                        left, right = st.test.left, st.test.comparators[0]
                        if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Attribute)):
                            left, right = right, left
                        if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Attribute)):
                            continue
                        holder = left.func.value
                        out = _lit(right, env) if not (isinstance(right, ast.Constant) and right.value is None) else None
                        qargs = tuple(_lit(a, env) for a in left.args)
                        if isinstance(holder, ast.Name) and holder.id in objs:
                            _real, run = objs[holder.id]
                            run["obs"].append((len(run["events"]), left.func.attr, qargs, out))
                        elif isinstance(holder, ast.Call) and isinstance(holder.func, ast.Name) and holder.func.id in classes:
                            mod, real = classes[holder.func.id]
                            d = found.setdefault(real, {"module": mod, "files": [], "ctor": len(holder.args), "mutators": [],
                                                        "runs": []})
                            d["runs"].append({"ctor": tuple(_lit(a, env) for a in holder.args), "events": [],
                                              "obs": [(0, left.func.attr, qargs, out)]})
                            if str(rel) not in d["files"]:
                                d["files"].append(str(rel).replace(os.sep, "/"))
                except Exception:  # noqa: BLE001
                    continue
    return found


def _queries(d):
    qs = []
    for run in d["runs"]:
        for _k, q, _qa, _o in run["obs"]:
            if q not in qs:
                qs.append(q)
    return qs


def _replay(init, trans, run, q):
    """the query's state through the run's actions in order -> [(k, state)] at each observation, or None on an error"""
    st = init(run["ctor"])
    if st is ERR:
        return None
    out, k = [], 0
    obs = sorted([(kk, o) for kk, qq, qa, o in run["obs"] if qq == q and not qa])
    for kk, _o in obs:
        while k < kk:
            m, args = run["events"][k]
            f = trans.get(m)
            if f is None:
                return None
            st = f(st, args, run["ctor"])
            if st is ERR:
                return None
            k += 1
        out.append((kk, st))
    return out


def state_plan(cname, d, deadline):
    """each query without arguments as a state carried through the ordered actions: an initial state from the fields, and a

    transition for each action. Transitions shown directly (asked right before and right after one action) are composed as

    goals of their own; the rest are searched together, every combination replayed through every ordered run. -> {q: plan}

    or a reason"""
    plans = {}
    for q in _queries(d):
        if any(qa for run in d["runs"] for _k, qq, qa, _o in run["obs"] if qq == q):
            return None, "%s.%s takes arguments; its state through the actions is not one value" % (cname, q)
        inits, direct = [], {m: [] for m in d["mutators"]}
        for run in d["runs"]:
            seen = {kk: o for kk, qq, _qa, o in run["obs"] if qq == q}
            if 0 in seen:
                inits.append((tuple(run["ctor"]), seen[0], None))
            for kk, o in seen.items():
                if kk >= 1 and kk - 1 in seen:
                    m, args = run["events"][kk - 1]
                    direct[m].append(((seen[kk - 1],) + tuple(args) + tuple(run["ctor"]), o, None))
        plans[q] = {"inits": inits, "direct": direct}
    return plans, None


def compose_states(cname, d, job, deadline):
    """compose every argument-free query of a class as a carried state -> (sources by query, imports, reason)"""
    plans, why = state_plan(cname, d, deadline)
    if plans is None:
        return None, None, why
    root = job["root"]
    nf = d["ctor"]
    fparams = param_names([(tuple(run["ctor"]), None, None) for run in d["runs"]])[:nf] if nf else []
    out, imports = {}, set()
    for q, pl in plans.items():
        # the initial state: a constant, or composed from the fields
        vals = {repr(o) for _a, o, _t in pl["inits"]}
        if pl["inits"] and len(vals) == 1 and nf == 0:
            init_v = pl["inits"][0][1]
            init_src = repr(init_v)
            consistent = all(same(o, init_v) for _a, o, _t in pl["inits"])
            init_fn = (lambda c, v=init_v: v) if consistent else None
            if nf and len({repr(a) for a, _o, _t in pl["inits"]}) > 1:
                init_fn = None                         # different fields, one value: still try the fields below
        else:
            init_fn, init_src = None, None
        if init_fn is None and nf and pl["inits"]:
            g = {"name": "%s_start" % q, "params": fparams, "module": "m", "examples": pl["inits"], "module_text": "",
                 "root": root, "need": 0, "no_namewords": True}
            r = compose_one(root, g, [], job.get("words", ""), [])
            if r["status"] != "composed":
                return None, None, "%s.%s right after it is made: %s" % (cname, q, r.get("gap"))
            ns = {}
            exec(compile("\n".join("import %s" % i for i in r["imports"]) + "\n" + r["source"], "init", "exec"), ns)
            f0 = ns[g["name"]]
            init_fn = lambda c, f0=f0: _ap(f0, *c)
            init_src = "%s(%s)" % (g["name"], ", ".join(fparams))
            imports |= set(r["imports"])
            out.setdefault("_helpers", []).append(r["source"])
        init_choices = None
        if init_fn is None:                           # never asked right after it is made: starts tried with the rest
            seen_t = ty_of_vals([o for run in d["runs"] for _k, qq, qa, o in run["obs"] if qq == q and not qa])
            init_choices = [((lambda c, v=v: v), repr(v)) for v in (0, "", [], None)
                            if v is None or tyof(v) == seen_t or (is_num(tyof(v)) and is_num(seen_t)) or
                            (is_seq(tyof(v)) and is_seq(seen_t))]      # only in the shape its answers have
            init_choices += [((lambda c, i=i: c[i]), fparams[i]) for i in range(nf)
                             if all(tyof(run["ctor"][i]) == seen_t or (is_num(tyof(run["ctor"][i])) and is_num(seen_t))
                                    for run in d["runs"])]
            init_choices = [ic for ic in init_choices if ic[1] != "None"] or init_choices
            init_fn, init_src = init_choices[0]
        # transitions: composed from direct rows where the tests show them
        trans, tsrc = {}, {}
        missing = list(d["mutators"])
        if missing:
            found, why_ask = None, None
            for ifn, isrc in (init_choices or [(init_fn, init_src)]):
                f2, ask2 = _search_transitions(q, d, ifn, trans, missing, fparams, deadline, pl["direct"])
                if ask2:
                    why_ask = ask2
                if f2 is not None:
                    if found is not None:
                        why_ask = "%s.%s could start as %s or as %s; ask it right after the object is made" % (
                            cname, q, init_src, isrc)
                        break
                    found, init_fn, init_src = f2, ifn, isrc
            if why_ask:
                return None, None, why_ask
            if found is None:
                return None, None, ("the tests never show what %s does to %s.%s on its own, and no small transition for it "
                                    "reproduces every ordered run; add an assert on %s after a %s" % (
                                        ", ".join(missing), cname, q, q, missing[0]))
            for m, (fn, src) in found.items():
                trans[m] = fn
                tsrc[m] = {"source": src, "imports": []}
        for run in d["runs"]:                          # the whole plan replays every run, in order
            got = _replay(init_fn, trans, run, q)
            want = sorted([(kk, o) for kk, qq, qa, o in run["obs"] if qq == q and not qa])
            if got is None or len(got) != len(want) or not all(same(a[1], b[1]) for a, b in zip(got, want)):
                return None, None, "the state plan for %s.%s does not replay every run" % (cname, q)
        out[q] = {"init": init_src, "trans": tsrc, "fparams": fparams}
    return out, sorted(imports), None


def _search_transitions(q, d, init_fn, trans, missing, fparams, deadline, direct=None):
    """each action's transition: small programs of (state, the action's values, the fields). Where the tests show an action

    on its own, its candidates are the programs that fit those rows; the rest come from states the runs pass through. The

    combination is chosen by replaying every ordered run, the cheapest that reproduces every observation."""
    direct = direct or {}
    states, argsamp = [], {m: [] for m in missing}
    for run in d["runs"]:
        st = init_fn(run["ctor"])
        if st is not ERR and st is not None and st not in states:
            states.append(st)
        for _k, qq, qa, o in run["obs"]:
            if qq == q and not qa and o not in states:
                states.append(o)
        for m, a in run["events"]:
            if m in argsamp and a not in argsamp[m]:
                argsamp[m].append(a)
    if not states:
        return None, None
    cands = {}
    for m in missing:
        drows = direct.get(m) or []
        n = max((len(a) for a in argsamp[m]), default=0)
        rows = [(r[0][0], tuple(r[0][1:1 + n])) for r in drows]   # what the tests show of this action on its own
        k_direct = len(rows)
        rows += [(st, a) for st in states for a in (argsamp[m] or [()])][:40]   # other states: so candidates stay apart
        cb = Bank(len(rows), min(deadline, time.time() + 6), 20000, set(), [0, 1, -1, "", None, True, False, []], [],
                  namewords=[])
        cb.add(X(("in", 0), [], tuple(st for st, _a in rows), 1, True, uses=1))
        for i in range(n):
            cb.add(X(("in", i + 1), [], tuple(a[i] for _st, a in rows), 1, True, uses=1 << (i + 1)))
        for c in [0, 1, -1, "", None, True, False, []]:
            cb.add(X(("const", c), [], tuple(c for _ in rows), 1, False))
        for size in range(2, 5):
            cb.grow(size)
        want = [o for _r, o, _t in drows]
        pool = sorted((x for x in cb.seen.values() if not x.dead and all(v is not ERR for v in x.val) and
                       all(same(v, o) for v, o in zip(x.val[:k_direct], want))), key=lambda x: x.cost)[:40]
        if not pool:
            return None, None
        names = ["state"] + (["value"] if n == 1 else ["arg%d" % i for i in range(n)])
        cands[m] = [((lambda st, a, c, x=x: evalx(x, [st] + list(a))),
                     "def %s_after_%s(%s):\n    return %s\n" % (q, m, ", ".join(names + fparams), bare(code(x, names))), x)
                    for x in pool]
    best, fits = None, []
    for combo in itertools.product(*[cands[m] for m in missing]):
        if time.time() > deadline:
            break
        tr = dict(trans)
        for m, (fn, _src, _x) in zip(missing, combo):
            tr[m] = fn
        okc = True
        for run in d["runs"]:
            got = _replay(init_fn, tr, run, q)
            want = sorted([(kk, o) for kk, qq, qa, o in run["obs"] if qq == q and not qa])
            if got is None or len(got) != len(want) or not all(same(a[1], b[1]) for a, b in zip(got, want)):
                okc = False
                break
        if okc:
            cost = sum(x.cost for _f, _s, x in combo)
            fits.append((cost, combo))
            if best is None or cost < best[0]:
                best = (cost, combo)
    if best is None:
        return None, None
    # combinations that also fit and are as plain: replayed on new orders of the actions; a disagreement means ask
    probes_ = []
    for run in d["runs"]:
        ev = run["events"]
        for k in range(len(ev)):
            probes_.append({"ctor": run["ctor"], "events": ev[:k] + ev[k + 1:] + ev[k:k + 1], "obs": [(len(ev), q, (), None)]})
        probes_.append({"ctor": run["ctor"], "events": ev[::-1], "obs": [(len(ev), q, (), None)]})
        probes_.append({"ctor": run["ctor"], "events": ev + ev, "obs": [(2 * len(ev), q, (), None)]})
    def run_with(combo):
        tr = dict(trans)
        for m, (fn, _src, _x) in zip(missing, combo):
            tr[m] = fn
        return [(_replay(init_fn, tr, pr, q) or [(None, ERR)])[-1][1] for pr in probes_]
    base = run_with(best[1])
    for cost, combo in sorted(fits, key=lambda c: c[0]):
        if combo is best[1] or cost > best[0] + AMBIG:
            continue
        if all(wraps(b_src.split("return ")[-1], o_src.split("return ")[-1]) for (_f, b_src, _x), (_g, o_src, _y) in zip(best[1], combo)):
            continue                                  # the same transitions with a wrapper added are not a rival
        other = run_with(combo)
        for pr, a, b in zip(probes_, base, other):
            if a is not ERR and b is not ERR and not same(a, b):
                srcs = [(s1, s2) for (_f1, s1, _x1), (_f2, s2, _x2) in zip(best[1], combo) if s1 != s2]
                return None, ("the tests fit more than one way %s.%s changes: after %s it is %r one way and %r the other "
                              "(%s vs %s). Ask %s after an action the tests do not show on its own." % (
                                  d.get("name", "the object"), q, ", ".join("%s(%s)" % (m, ", ".join(map(repr, a_)))
                                                                            for m, a_ in pr["events"]), a, b,
                                  srcs[0][0].split("return ")[-1].strip() if srcs else "?",
                                  srcs[0][1].split("return ")[-1].strip() if srcs else "?", q))
    return {m: (fn, src) for m, (fn, src, _x) in zip(missing, best[1])}, None


def state_class_source(cname, d, plan):
    """the class: each query's state set when it is made and changed by each action, in the order the actions come"""
    fparams = next(iter(v["fparams"] for k, v in plan.items() if k != "_helpers"), [])
    lines = []
    for h in plan.get("_helpers", []):
        lines += [h.rstrip("\n"), "", ""]
    for q, pl in plan.items():
        if q == "_helpers":
            continue
        for m, r in pl["trans"].items():
            lines += [r["source"].rstrip("\n"), "", ""]
    lines += ["class %s:" % cname, "    def __init__(self%s):" % "".join(", " + f for f in fparams)]
    for f in fparams:
        lines.append("        self.%s = %s" % (f, f))
    for q, pl in plan.items():
        if q != "_helpers":
            lines.append("        self._%s = %s" % (q, pl["init"]))
    for m in d["mutators"]:
        nargs = max((len(ev[1]) for run in d["runs"] for ev in run["events"] if ev[0] == m), default=0)
        aparams = ["value"] if nargs == 1 else ["arg%d" % i for i in range(nargs)]
        lines += ["", "    def %s(self%s):" % (m, "".join(", " + a for a in aparams))]
        for q, pl in plan.items():
            if q != "_helpers" and m in pl["trans"]:
                lines.append("        self._%s = %s_after_%s(self._%s%s%s)" % (
                    q, q, m, q, "".join(", " + a for a in aparams), "".join(", self." + f for f in fparams)))
        if not any(q != "_helpers" and m in pl["trans"] for q, pl in plan.items()):
            lines.append("        pass")
    for q, pl in plan.items():
        if q != "_helpers":
            lines += ["", "    def %s(self):" % q, "        return self._%s" % q]
    return "\n".join(lines) + "\n"


def read_class_tests(root, only=None):
    """{Class: {"module", "files", "ctor": arity, "mutators": [m...], "queries": {q: [(ctor args, {m: [args]}, q args, out)]}}}

    from test files that make objects, call methods on them as statements (what is done to the object) and assert on what

    other methods give (what it is asked)"""
    root = Path(root)
    found = {}
    for p in sorted(root.rglob("*.py")):
        rel = p.relative_to(root)
        if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv") for part in rel.parts):
            continue
        if not is_test_path(rel) or p.name.startswith("_hidden"):
            continue
        if only and p.name not in only and str(rel).replace(os.sep, "/") not in only:
            continue
        try:
            tree = ast.parse(p.read_text(encoding="utf-8"))
        except Exception:  # noqa: BLE001
            continue
        classes = {}
        for node in ast.walk(tree):
            if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and \
                    node.module.split(".")[0] not in sys.stdlib_module_names:
                for a in node.names:
                    if a.name[:1].isupper():
                        classes[a.asname or a.name] = (node.module, a.name)
        if not classes:
            continue
        bodies = [tree.body] + [n.body for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]
        for body in bodies:
            objs, env = {}, {}
            for st in body:
                try:
                    if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name):
                        v = st.value
                        if isinstance(v, ast.Call) and isinstance(v.func, ast.Name) and v.func.id in classes and not v.keywords:
                            objs[st.targets[0].id] = (v.func.id, tuple(_lit(a, env) for a in v.args), {})
                        else:
                            try:
                                env[st.targets[0].id] = ast.literal_eval(v)
                            except Exception:  # noqa: BLE001
                                pass
                    elif isinstance(st, ast.Expr) and isinstance(st.value, ast.Call) and \
                            isinstance(st.value.func, ast.Attribute) and isinstance(st.value.func.value, ast.Name) and \
                            st.value.func.value.id in objs:
                        _c, _ca, hist = objs[st.value.func.value.id]
                        args = tuple(_lit(a, env) for a in st.value.args)
                        hist.setdefault(st.value.func.attr, []).append(args[0] if len(args) == 1 else args)
                    elif isinstance(st, ast.Assert) and isinstance(st.test, ast.Compare) and len(st.test.ops) == 1 and \
                            isinstance(st.test.ops[0], (ast.Eq, ast.Is)):
                        left, right = st.test.left, st.test.comparators[0]
                        if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Attribute)):
                            left, right = right, left
                        if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Attribute)):
                            continue
                        holder = left.func.value
                        if isinstance(holder, ast.Name) and holder.id in objs:
                            cname, cargs, hist = objs[holder.id]
                        elif isinstance(holder, ast.Call) and isinstance(holder.func, ast.Name) and holder.func.id in classes:
                            cname, cargs, hist = holder.func.id, tuple(_lit(a, env) for a in holder.args), {}
                        else:
                            continue
                        out = _lit(right, env) if not (isinstance(right, ast.Constant) and right.value is None) else None
                        qargs = tuple(_lit(a, env) for a in left.args)
                        mod, real = classes[cname]
                        d = found.setdefault(real, {"module": mod, "files": [], "ctor": len(cargs), "mutators": [],
                                                    "queries": {}})
                        if str(rel) not in d["files"]:
                            d["files"].append(str(rel).replace(os.sep, "/"))
                        d["queries"].setdefault(left.func.attr, []).append(
                            (cargs, {m: list(v) for m, v in hist.items()}, qargs, out))
                        for m in hist:
                            if m not in d["mutators"]:
                                d["mutators"].append(m)
                except Exception:  # noqa: BLE001
                    continue
    for d in found.values():
        d["mutators"] = sorted(d["mutators"])
    return found


def _hist_name(m):
    return m + ("_log" if m.endswith("s") else "s")


def class_goals(cname, d):
    """each query is a function of the object's fields and of the history of each thing done to it"""
    goals = []
    for q, rows in d["queries"].items():
        ex = []
        for cargs, hist, qargs, out in rows:
            ex.append((tuple(cargs) + tuple(list(hist.get(m, [])) for m in d["mutators"]) + tuple(qargs), out, None))
        if not ex or len({len(a) for a, _o, _t in ex}) != 1:
            continue
        nq = len(rows[0][2])
        cparams = param_names([(tuple(r[0]), None, None) for r in rows]) if d["ctor"] else []
        cparams = cparams[:d["ctor"]]
        qparams = param_names([(tuple(r[2]), None, None) for r in rows]) if nq else []
        qparams = [("%s_" % n if n in cparams else n) for n in qparams[:nq]]
        params = cparams + [_hist_name(m) for m in d["mutators"]] + qparams
        need = sum(1 << (len(params) - nq + i) for i in range(nq))
        goals.append({"name": q, "params": params, "module": d["module"], "examples": ex, "module_text": "", "need": need,
                      "class": cname, "ctor_params": cparams, "query_params": qparams})
    return goals


def class_source(cname, d, goals, results):
    """the class: its fields, a history for each thing done to it, and each query as composed"""
    g0 = goals[0] if goals else {"ctor_params": [], "params": []}
    cps = g0["ctor_params"]
    lines = ["class %s:" % cname, "    def __init__(self%s):" % "".join(", " + c for c in cps)]
    for c in cps:
        lines.append("        self.%s = %s" % (c, c))
    for m in d["mutators"]:
        lines.append("        self._%s = []" % _hist_name(m))
    if not cps and not d["mutators"]:
        lines.append("        pass")
    for m in d["mutators"]:
        lines += ["", "    def %s(self, *args):" % m,
                  "        self._%s.append(args[0] if len(args) == 1 else args)" % _hist_name(m)]
    for g, r in zip(goals, results):
        src = r["source"]
        body = src.split("\n", 1)[1] if "\n" in src else ""
        binds = ["%s = self.%s" % (c, c) for c in cps] + ["%s = self._%s" % (_hist_name(m), _hist_name(m)) for m in d["mutators"]]
        lines += ["", "    def %s(self%s):" % (g["name"], "".join(", " + q for q in g["query_params"]))]
        lines += ["        " + b for b in binds]
        lines += ["    " + ln if ln.strip() else ln for ln in body.rstrip("\n").split("\n")]
    return "\n".join(lines) + "\n"


def run_classes(job):
    """compose every query of every class the tests use, then write each class whole (a class with a query not composed is

    not written)"""
    root = job["root"]
    out = []
    runs = read_object_runs(root, job.get("only"))
    for cname, d in job["classes"].items():
        rd = runs.get(cname)
        if rd and len(rd["mutators"]) >= 2:          # order between kinds of action matters: a state through them
            plan, imports, why = compose_states(cname, rd, job, time.time() + 240)
            if plan is None:
                out.append({"class": cname, "status": "declined", "module": d["module"], "gap": why})
                continue
            out.append({"class": cname, "status": "composed", "module": d["module"], "imports": imports,
                        "source": state_class_source(cname, rd, plan), "mutators": rd["mutators"], "form": "state",
                        "queries": [{"name": q, "moves": ["state through %s" % ", ".join(rd["mutators"])], "size": None,
                                     "examples": sum(1 for run in rd["runs"] for o in run["obs"] if o[1] == q),
                                     "read_back": "replayed every ordered run"} for q in plan if q != "_helpers"]})
            continue
        goals = class_goals(cname, d)
        if not goals:
            out.append({"class": cname, "status": "declined", "gap": "the tests ask %s nothing I can read" % cname})
            continue
        r = run_goals({"root": root, "goals": goals, "words": job.get("words", ""), "exclude": [g["name"] for g in goals],
                       "net_scope": job.get("net_scope", [])})
        res = r["results"]
        bad = [x for x in res if x["status"] != "composed"]
        if bad:
            out.append({"class": cname, "status": "declined", "module": d["module"],
                        "gap": "; ".join("%s.%s: %s" % (cname, x["name"], x.get("gap", "")) for x in bad)})
            continue
        imports = sorted({i for x in res for i in x.get("imports", [])})
        out.append({"class": cname, "status": "composed", "module": d["module"], "imports": imports,
                    "source": class_source(cname, d, goals, res),
                    "queries": [{"name": x["name"], "moves": x.get("moves"), "size": x.get("size"), "examples": x["examples"],
                                 "read_back": x["read_back"]} for x in res],
                    "mutators": d["mutators"]})
    return {"classes": out}


# ================================================================ files and the network at the edge
URL_RE = re.compile(r"^https?://[^\s/]+")
EDGE_CAP = 2_000_000


def _read_inside(root, p):
    """a file of the project, read-only: inside the project, not a secret, not too large (else it raises)"""
    if not isinstance(p, str) or not p or os.path.isabs(p) or ".." in Path(p).parts or SECRET.search(p):
        raise ValueError("not a project file")
    full = (Path(root) / p).resolve()
    if not str(full).startswith(str(Path(root).resolve())) or not full.is_file() or full.stat().st_size > EDGE_CAP:
        raise ValueError("not a project file")
    return full.read_text(encoding="utf-8", errors="replace")


EDGE_READS = ("readtext", "fetch")   # the moves that read the world: their results are leaves for three-input moves


def edge_leaves(goal, bank):
    """an input that names files of the project: their text, lines or JSON, read once; an input of URLs inside the

    conversation's network scope: the pages, fetched once each before the search (never during it)"""
    ex = goal["examples"]
    root = goal.get("root")
    fetched = goal.get("fetched") or {}
    leaves = {x.op[1]: x for x in bank.alive(1) if x.op[0] == "in"}
    for i, leaf in leaves.items():
        vals = [a[i] for a, _o, _t in ex]
        if not all(isinstance(v, str) for v in vals):
            continue
        if root:
            try:
                texts = [_read_inside(root, v) for v in vals]
            except Exception:  # noqa: BLE001
                texts = None
            if texts is not None:
                cache = dict(zip(vals, texts))

                def rd(pth, cache=cache, root=root):
                    return cache[pth] if pth in cache else _read_inside(root, pth)
                bank.add(X(("u", "readtext", "open({0}).read()", rd), [leaf], tuple(texts), 2, True,
                           bank.nw("file read open contents text whole")))
                bank.add(X(("u", "readlines", "open({0}).read().splitlines()", lambda pth, rd=rd: rd(pth).splitlines()),
                           [leaf], tuple(t.splitlines() for t in texts), 2, True,
                           bank.nw("file lines line log read open each entries")))
                try:
                    js = [json.loads(t) for t in texts]
                    bank.add(X(("u", "readjson", "json.load(open({0}))", lambda pth, rd=rd: json.loads(rd(pth))), [leaf],
                               tuple(js), 2, True, bank.nw("json load parse file records read"), ("json",)))
                except Exception:  # noqa: BLE001
                    pass
                continue
        if all(URL_RE.match(v) for v in vals) and all(v in fetched for v in vals):
            def fe(u, fetched=fetched):
                if u not in fetched:
                    raise ValueError("not fetched")   # the search never reaches the network
                return fetched[u]
            bank.add(X(("u", "fetch", "urllib.request.urlopen({0}, timeout=10).read().decode()", fe), [leaf],
                       tuple(fetched[v] for v in vals), 2, True, bank.nw("page fetch download url web http get site read"),
                       ("urllib.request",)))


def fetch_examples(g):
    """the example URLs, fetched once each, only for hosts inside the conversation's network scope -> (pages, gap)"""
    urls = []
    for a, _o, _t in g["examples"]:
        for v in a:
            if isinstance(v, str) and URL_RE.match(v) and v not in urls:
                urls.append(v)
    if not urls:
        return {}, None
    from urllib.parse import urlparse
    hosts = sorted({urlparse(u).hostname or "" for u in urls})
    scope = set(g.get("net_scope") or [])
    outside = [h for h in hosts if h not in scope]
    if outside:
        return None, ("this conversation has no network scope for %s, so nothing was fetched and nothing was written. Say "
                      "\"allow network to %s\" to let Oracle7 read the example pages (once each, while composing) and let this "
                      "project's runs reach that host." % (", ".join(outside), outside[0]))
    import urllib.request
    pages = {}
    for u in urls[:12]:
        try:
            with urllib.request.urlopen(u, timeout=8) as r:
                body = r.read(EDGE_CAP + 1)
            if len(body) > EDGE_CAP:
                return None, "the page %s is larger than %d bytes" % (u, EDGE_CAP)
            pages[u] = body.decode("utf-8", errors="replace")
        except Exception as e:  # noqa: BLE001
            return None, "the example page %s could not be read (%s)" % (u, str(e)[:80])
    return pages, None


def run_job(root, goals, words="", exclude=(), timeout=None, net_scope=(), classes=None):
    """compose in a child process (the project's functions are imported there, never in the bench)"""
    timeout = timeout or max(600, 150 + 220 * len(goals))   # each goal: its search, then its chains
    job = {"root": str(root), "goals": goals, "words": words, "exclude": list(exclude), "net_scope": list(net_scope)}
    if classes:
        job["classes"] = classes
        timeout = max(timeout, 150 + 220 * sum(len(d["queries"]) for d in classes.values()))
    job["ends_at"] = time.time() + timeout            # the job's own stop: a second (kept-part) pass must finish before it
    with tempfile.TemporaryDirectory(prefix="o7job_") as d:
        jp, op = os.path.join(d, "job.txt"), os.path.join(d, "out.txt")
        open(jp, "w", encoding="utf-8").write(repr(job))
        # 12.0 C14: the child is watched, not waited on blindly - a stop asked of the turn job that runs this (continuation's
        # stop_requested) ends it at once, inside the stage, not after it
        ct = sys.modules.get("continuation")
        stop_asked = getattr(ct, "stop_requested", None)
        # its output goes to files and the child is polled (pipes held open by the composer's own children would block a
        # wait); it runs in its own process group, so a stop or a timeout ends the composer and everything it started
        fo, fe = open(os.path.join(d, "stdout.txt"), "w"), open(os.path.join(d, "stderr.txt"), "w")
        p = subprocess.Popen([sys.executable, "-I", str(Path(__file__).resolve()), jp, op], stdout=fo, stderr=fe, text=True,
                             cwd=d, env=__import__("runjail").env(root=d, PYTHONDONTWRITEBYTECODE="1", PYTHONHASHSEED="0", **_child_settings()),
                             start_new_session=(os.name != "nt"))

        def _end():
            try:
                os.killpg(p.pid, 9) if os.name != "nt" else p.kill()
            except (ProcessLookupError, PermissionError, OSError):
                pass
            p.wait()
            fo.close()
            fe.close()
        t0 = time.time()
        while p.poll() is None:
            if stop_asked is not None and stop_asked():
                _end()
                return {"error": "stopped as asked, %.1f s into composing" % (time.time() - t0), "stopped": True}
            if time.time() - t0 > timeout:
                _end()
                return {"error": "the composer ran past %d s" % timeout}
            time.sleep(0.2)
        fo.close()
        fe.close()
        r = subprocess.CompletedProcess(p.args, p.returncode, open(os.path.join(d, "stdout.txt")).read(),
                                        open(os.path.join(d, "stderr.txt")).read())
        if not os.path.exists(op):
            if r.returncode < 0:                      # stopped by a signal: say which (9 is the system's memory stop)
                return {"error": "the composer was stopped by signal %d%s" % (
                    -r.returncode, " (the system stops a process this way when memory runs out)" if r.returncode == -9 else "")}
            return {"error": "the composer stopped (exit %d): %s" % (r.returncode, (r.stderr or "").strip()[-300:] or
                                                                     "no message")}
        return json.loads(open(op, encoding="utf-8").read())


def _child_settings():
    """round-3 R2: the composer's job child is Oracle7's own search, so it gets the settings it reads (its memory bound, the

    formula organ, and the kept-parts store resolved here), and nothing else of Oracle7's state. Named gap: the child also

    inspects project code, which can therefore see that one store file."""
    import code_store
    out = {k: os.environ[k] for k in ("O7_COMPOSE_MEM_MB", "ORACLE7_FORMULA_ORGAN") if k in os.environ}
    out["ORACLE7_CODE_STORE"] = str(code_store.store_path())
    return out


def main():
    # -I deliberately excludes the script directory. Reconnect the installed
    # workbench before inspecting project code, so kept parts remain available
    # and a project file named code_store.py cannot replace the native store.
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import code_store as native_store
    try:
        import resource
        cap = (MEM_MB + 1400) << 20
        resource.setrlimit(resource.RLIMIT_AS, (cap, cap))
    except (ImportError, ValueError, OSError):
        pass
    job = ast.literal_eval(open(sys.argv[1], encoding="utf-8").read())
    out = run_classes(job) if job.get("classes") else run_goals(job)
    out["connections"] = {"code_store": str(Path(native_store.__file__).resolve()),
                          "store_path": str(native_store.store_path())}
    open(sys.argv[2], "w", encoding="utf-8").write(json.dumps(out))


if __name__ == "__main__":
    main()