I can’t really help you understand the sonic pi codebase, but I do have a suggestion for your MIDI issues. Sonic Pi supports reading MIDI and OSC data from other sources already .there’s a thread here and here, which got me started using touchOSC to control sonic pi.
TouchOSC messages can, in principle, be sent from anything that can run a library and a network connection, so there’s plenty of stuff to look at outside of pi itself and that’s what I would focus on.