Smart scope-matching queries

Also fix some bugs in the Ruby scope resolution code