Provided that Starfleet did have Kirk under constant, strict surveillance and worry about him snapping a twig, why test the M5 on his ship? Why not test it on a ship where the captain wouldn't be as unhappy with becoming redundant?
Because if everyone always does the most logical thing, nothing bad ever happens and you don't have a show.
This is an episode about people making the WRONG call, out of hubris. Daystrom made the wrong call, and so did Wesley, by buying into the M-5 hype and empowering him.
This is pretty much the same backdrop for other "Technology goes wrong" stories like Westworld or Wargames or Skynet in Terminator. You can't have a clusterf*ck unless people in power express too much faith in technology and give that tech too much power.
One can also see analogies to nuclear accidents like 3-mile island, Chernobyl, or Fukushima. There's always a zillion red flags visible in the rear-view-mirror, but the people in power, either through their own stupidity, cheapness, or faith in technology, did not take proper precautions. This stuff happens all the time. People do dumb things, and apparently still do in the 23rd century.